From 4f42f0a86e4ba649ae2e2ebaa66ed73f91aa799b Mon Sep 17 00:00:00 2001 From: Peter Ward Date: Sat, 21 Jul 2012 11:27:26 +1000 Subject: Add extra functions. --- snakegame/common.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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) -- cgit v1.2.3