Advertisement
Guest User

CS61A Hog Contest - Tool for compressing your strategies

a guest
Sep 14th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.71 KB | None | 0 0
  1. #!/bin/python3
  2. from __future__ import print_function
  3. import os, sys, imp
  4.  
  5. GOAL = 100 # goal score for Hog
  6.  
  7. STRATEGY_FUNC_ATTR = 'final_strategy' # attribute of student's module that contains the strategy function
  8. TEAM_NAME_ATTRS = ['PLAYER_NAME', 'TEAM_NAME'] # attributes for the team name (should really be "PLAYER_NAME" but keeping "TEAM_NAME" for compatibility)
  9.  
  10. MIN_ROLLS, MAX_ROLLS = 0, 10 # min, max roll numbers
  11. ERROR_DEFAULT_ROLL = 5 # default roll in case of invalid strategy function (will tell you if this happens somehow)
  12.  
  13. # output file format
  14. OUTPUT_FILE_PREFIX = "PLAYER_NAME = '{}'\ndef final_strategy(score, opponent_score):\n    return [" # outputted before matrix of roll numbers
  15. OUTPUT_FILE_SUFFIX = "][score][opponent_score]\n" # outputted after matrix
  16.  
  17. def eprint(*args, **kwargs):
  18.     """ print to stderr """
  19.     print(*args, file=sys.stderr, **kwargs)
  20.    
  21. def convert(file, out_path):  
  22.     """ convert a single file to matrix form """
  23.     module_path = file[:-3] # cut off .py
  24.     module_dir, module_name = os.path.split(module_path)
  25.    
  26.     # make sure module's dependencies work by appending to path
  27.     sys.path[-1] = module_dir
  28.     sys.path.append(os.path.dirname(os.path.realpath(__file__)))
  29.    
  30.     # import module
  31.     try:
  32.         module = imp.load_source(module_name, file)
  33.     except Exception as e:
  34.         # report any errors encountered while importing
  35.         eprint ("\nERROR: error occurred while loading " + file + ":")
  36.         eprint (type(e).__name__ + ': ' + str(e))
  37.         import traceback
  38.         traceback.print_stack() # try to be helpful
  39.         sys.exit(1)
  40.    
  41.     if hasattr(module, STRATEGY_FUNC_ATTR):
  42.         strat = getattr(module, STRATEGY_FUNC_ATTR)
  43.     else:
  44.         eprint ("ERROR: the python script you selected " + file + " has no required function '" + STRATEGY_FUNC_ATTR + "'!")
  45.         sys.exit(2)
  46.    
  47.     strat_name = ""
  48.     for attr in TEAM_NAME_ATTRS:
  49.         if hasattr(module, attr):
  50.             val = getattr(module, attr)
  51.             if val:
  52.                 strat_name = getattr(module, attr)
  53.             setattr(module, attr, "")
  54.            
  55.     if not strat_name:
  56.         eprint ("ERROR: you have not specified a player name! Please fill in the PLAYER_NAME='' filed at the top of the hog_contest.py.")
  57.         sys.exit(3)
  58.    
  59.     # check for team names that are too long
  60.     out = open(out_path, 'w', encoding='utf-8')
  61.    
  62.     # write out new strategy
  63.     try:
  64.         skip_rest = False
  65.         out.write(OUTPUT_FILE_PREFIX.format(strat_name))
  66.        
  67.         for i in range(GOAL):
  68.             if i:
  69.                 out.write(',\n')
  70.             out.write('[')
  71.             for j in range(GOAL):
  72.                 if j:
  73.                     out.write(', ')
  74.                 if not skip_rest:
  75.                     rolls = strat(i, j)
  76.                
  77.                     # check if output valid
  78.                     if type(rolls) != int or rolls < MIN_ROLLS or rolls > MAX_ROLLS:
  79.                         if type(rolls) != int:
  80.                             eprint("WARNING: for (score, opponent_score) = {} your strategy function outputted something other than a number! Pretending you roll 5...".format((i,j)))
  81.                         else:
  82.                             eprint("WARNING: for (score, opponent_score) = {} your strategy function outputted an invalid number of rolls:",
  83.                                 rolls + "! Pretending you roll 5...".format((i,j)))
  84.                         rolls = ERROR_DEFAULT_ROLL
  85.                
  86.                 out.write(str(rolls))
  87.             out.write(']')
  88.         out.write(OUTPUT_FILE_SUFFIX)
  89.            
  90.     except Exception as e:
  91.         # report errors encountered while running strategy
  92.         eprint ("\nERROR: error occurred while running '" + STRATEGY_FUNC_ATTR + "' in " + file + ":")
  93.         eprint (type(e).__name__ + ': ' + str(e))
  94.         import traceback
  95.         traceback.print_stack() # try to be helpful
  96.         sys.exit(4)
  97.     out.close()
  98.    
  99. sys.path.append('')
  100. if len(sys.argv) != 3:
  101.     print ("""hogmat.py - A tool for "streamlining" hog contest strategies.
  102. Created by FA2018 CS61A course staff / Alex Yu
  103.  
  104. usage: python3 hogmat.py hog_contest.py output.py
  105. where hog_contest.py is your original hog_contest.py file, and output.py is the python file to output to
  106.  
  107. This script will run your final_strategy function for every possible pair of inputs and output a "cached" version of the function that does not depend on any external files.""")
  108.     sys.exit(0)
  109.  
  110. in_file, out_file = sys.argv[1:]
  111. convert(in_file, out_file)
  112.    
  113. print ("Conversion success :) output saved to: " + out_file)
  114. print ("You should now be able to submit " + out_file + " directly to okpy. GL HF!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement