From 2b3953c0d4af78ba379d49950cba222983d20c8a Mon Sep 17 00:00:00 2001 From: Peter Ward Date: Mon, 28 Sep 2009 11:48:20 +1000 Subject: Random bot colours, improvements to random bots. --- bots.py | 35 ++++++++++++++++++++++++++++++++--- snake.py | 15 +++++++++------ 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/bots.py b/bots.py index dba440d..f3e7cee 100644 --- a/bots.py +++ b/bots.py @@ -1,9 +1,14 @@ import random +from common import * + def right_bot(board, (x, y)): return 'R' def random_bot(board, (x, y)): + return random.choice('UDLR') + +def random_bounds_bot(board, (x, y)): height = len(board) width = len(board[0]) moves = [] @@ -15,9 +20,33 @@ def random_bot(board, (x, y)): moves.append('U') if y < height - 1: moves.append('D') - return random.choice(moves) -def random_bot2(board, (x, y)): + move = 'U' + while moves and move not in moves: + move = random_bot(board, (x, y)) + return move + +def random_square_bot(board, (x, y)): + def in_bounds(x, y, w, h): + return x >= 0 and y >= 0 and x < w and y < h + + h = len(board) + w = len(board[0]) + + todo = directions.keys() + move = random_bot(board, (x, y)) - nx, ny = x + dx, dy = directions[move] + nx = x + dx + ny = y + dy + + while todo and in_bounds(nx, ny, w, h) and \ + board[ny][nx] not in (Squares.EMPTY, Squares.APPLE): + if move in todo: + todo.remove(move) + move = random_bot(board, (x, y)) + dx, dy = directions[move] + nx = x + dx + ny = y + dy + return move diff --git a/snake.py b/snake.py index 9350502..a4b7112 100755 --- a/snake.py +++ b/snake.py @@ -3,7 +3,7 @@ from __future__ import division import string -import random +from random import randint from collections import deque from copy import deepcopy import traceback @@ -49,8 +49,8 @@ class SnakeEngine(object): self.new_game(rows, columns, n_apples) def get_random_position(self): - x = random.randint(0, self.columns - 1) - y = random.randint(0, self.rows - 1) + x = randint(0, self.columns - 1) + y = randint(0, self.rows - 1) return (x, y) def new_game(self, rows, columns, n_apples): @@ -98,7 +98,7 @@ class SnakeEngine(object): else: raise KeyError, "Could not insert snake into the board." - colour = (255, 0, 0) + colour = (randint(0, 255), randint(0, 255), randint(0, 255)) self.bots[letter] = [bot, colour, deque([(x, y)])] self.board[y][x] = letter.upper() return letter @@ -215,7 +215,7 @@ class SnakeEngine(object): # Update the display. pygame.display.flip() - clock.tick(5) + clock.tick(20) # Let the snakes move! self.update_snakes() @@ -226,7 +226,10 @@ class SnakeEngine(object): if __name__ == '__main__': from bots import * - game = SnakeEngine(25, 25, 10) + game = SnakeEngine(25, 25, 50) game.add_bot(right_bot) + game.add_bot(random_bot) + game.add_bot(random_bounds_bot) + game.add_bot(random_square_bot) game.run() -- cgit v1.2.3