Commits

Peter Ward committed 4bb32dd Merge

merged

  • Participants
  • Parent commits 7422bcd, 23df3cc

Comments (0)

Files changed (6)

+from collections import defaultdict
+from itertools import imap as map
+from operator import itemgetter
+
+RESULTS_FILE = 'results.csv'
+results = defaultdict(list)
+
+for line in open(RESULTS_FILE, 'rU'):
+    game, name, length, time = line[:-1].split(',')
+    length = int(length)
+    time = int(time)
+    results[name].append((length, time))
+
+def average(items):
+    s = 0.0
+    l = 0
+    for item in items:
+        s += item
+        l += 1
+    return s / l
+
+lengths = []
+times = []
+
+for name, series in results.items():
+    length_average = average(map(itemgetter(0), series))
+    lengths.append((length_average, name))
+    time_average = average(map(itemgetter(1), series))
+    times.append((time_average, name))
+
+lengths.sort(reverse=True)
+times.sort(reverse=True)
+
+print 'Lengths'
+print '======='
+for length, name in lengths:
+    print name, length
+print
+
+print 'Times'
+print '====='
+for time, name in times:
+    print name, time
+

docs/tutorial.tex

 \usepackage{minted}
 \usemintedstyle{tango}
 
-\newmint[py]{python}{}
+\newmintinline[py]{python}{}
 \newminted{python}{}
 \newmintedfile{python}{}
 
     author_email='peteraward@gmail.com',
     packages=['snakegame'],
     zip_safe=False,
+    install_requires=[
+        'six',
+    ],
     package_data={
         'snakegame': 'images/*.png',
     },

snakegame/colour.py

 import hashlib
+from random import Random
 
 def hash_colour(data):
-    data = map(ord, hashlib.md5(data).digest())
-    colour = data[::3], data[1::3], data[2::3]
-    colour = map(sum, colour)
-    return (colour[0] % 255, colour[1] % 255, colour[2] % 255)
-
+    n = int(hashlib.md5(data.encode('utf-8')).hexdigest(), 16)
+    r = Random(n)
+    return r.randrange(256), r.randrange(256), r.randrange(256)

snakegame/engine.py

 from copy import deepcopy
 from random import Random
 from string import ascii_lowercase as lowercase
-import sys
 import time
 import traceback
 
+import six
+from six.moves import xrange
+
 from snakegame.colour import hash_colour
 from snakegame import common
 
         n_ice_creams, n_shrink_potions, n_walls,
     ):
         self.game_ticks = 0
-        self.game_id = self.random.randint(0, sys.maxint)
 
         self.letters = list(lowercase)
         self.letters.reverse()
 
         position = self.replace_random(common.EMPTY, letter.upper())
         if position is None:
-            raise KeyError, "Could not insert snake into the board."
+            raise KeyError("Could not insert snake into the board.")
 
         self.bots[letter] = [bot, colour, deque([position]), team]
         return letter
     def update_snakes(self):
         self.game_ticks += 1
 
-        for letter, (bot, colour, path, team) in self.bots.items():
+        for letter, (bot, colour, path, team) in list(self.bots.items()):
             board = deepcopy(self.board)
             try:
                 x, y = path[-1]
                 delta = end - start
                 assert delta < HARD_TIME_LIMIT, 'Exceeded hard time limit.'
                 if delta >= SOFT_TIME_LIMIT:
-                    print 'Bot %s (%r) exceeded soft time limit.' % (letter.upper(), bot)
+                    print('Bot %s (%r) exceeded soft time limit.' % (letter.upper(), bot))
 
                 # Sanity checking...
-                assert isinstance(d, basestring), \
+                assert isinstance(d, six.string_types), \
                     "Return value should be a string."
                 d = d.upper()
                 assert d in common.directions, "Return value should be 'U', 'D', 'L' or 'R'."
                         path.appendleft(tail)
                         self.replace_random(common.EMPTY, common.APPLE)
                     elif oldcell == common.ICE_CREAM:
-                        for i in range(3):
+                        for i in xrange(3):
                             path.appendleft(tail)
                         self.replace_random(common.EMPTY, common.ICE_CREAM)
                     elif oldcell == common.SHRINK_POTION:
                     self.remove_bot(letter)
 
             except:
-                print "Exception in bot %s (%s):" % (letter.upper(), bot)
-                print '-'*60
+                print("Exception in bot %s (%s):" % (letter.upper(), bot))
+                print('-'*60)
                 traceback.print_exc()
-                print '-'*60
+                print('-'*60)
                 self.remove_bot(letter)
 
     def __iter__(self):

snakegame/utils.py

 except ImportError:
     MaybeOrderedDict = dict
 
-def scale_aspect((source_width, source_height), (target_width, target_height)):
+def scale_aspect(source_size, target_size):
+    source_width, source_height = source_size
+    target_width, target_height = target_size
     source_aspect = float(source_width) / source_height
     target_aspect = float(target_width) / target_height
     if source_aspect > target_aspect: