summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Ward <peteraward@gmail.com>2012-07-21 11:27:26 +1000
committerPeter Ward <peteraward@gmail.com>2012-07-21 11:27:26 +1000
commit4f42f0a86e4ba649ae2e2ebaa66ed73f91aa799b (patch)
treed12f2a85176778f4129d790849575ae4a0c9a926
parent911c0f8fa11bf6a8a4d207833dc27f2d184af5b4 (diff)
Add extra functions.
-rw-r--r--snakegame/common.py24
1 files changed, 24 insertions, 0 deletions
diff --git a/snakegame/common.py b/snakegame/common.py
index a44219b..92d0e62 100644
--- a/snakegame/common.py
+++ b/snakegame/common.py
@@ -1,3 +1,4 @@
+import random
from string import ascii_lowercase as lowercase, ascii_uppercase as uppercase
alphabet = lowercase + uppercase
@@ -58,3 +59,26 @@ def get_cell(board, x, y, wrap=True):
elif not in_bounds(x, y, width, height):
return None
return board[y][x]
+
+def get_neighbours(x, y, width, height):
+ for d, (dx, dy) in directions.iteritems():
+ nx = (x + dx) % width
+ ny = (y + dy) % height
+ yield d, nx, ny
+
+def max_items(items, alpha=1.0):
+ """
+ >>> max_items([(1, 'a'), (2, 'b'), (2, 'c'), (0, 'd')])
+ [(2, 'b'), (2, 'c')]
+ """
+ max_score, _ = max(items)
+ return [
+ (score, item)
+ for score, item in items
+ if score >= max_score * alpha
+ ]
+
+def choose_move(choices, default='U', random=random):
+ if not choices:
+ return default
+ return random.choice(choices)