diff options
author | Peter Ward <peteraward@gmail.com> | 2009-09-28 11:48:20 +1000 |
---|---|---|
committer | Peter Ward <peteraward@gmail.com> | 2009-09-28 11:48:20 +1000 |
commit | 2b3953c0d4af78ba379d49950cba222983d20c8a (patch) | |
tree | e1d3ea7c95c4c1fd4402cf8e314aaa6ac3e80e5e | |
parent | b781dfc5059f22d273916df88d9aef2f176358ab (diff) |
Random bot colours, improvements to random bots.
-rw-r--r-- | bots.py | 35 | ||||
-rwxr-xr-x | snake.py | 15 |
2 files changed, 41 insertions, 9 deletions
@@ -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 @@ -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() |