summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Ward <peteraward@gmail.com>2009-09-28 11:29:57 +1000
committerPeter Ward <peteraward@gmail.com>2009-09-28 11:29:57 +1000
commitb781dfc5059f22d273916df88d9aef2f176358ab (patch)
treee59a31f6b8efb7986a8f76b1d42adeed3c5dba3a
parent47c02c2e6392cb1c9868062b15f4a8c1b3ed1505 (diff)
Made directions public, added bounds checking.
-rw-r--r--bots.py7
-rw-r--r--common.py7
-rwxr-xr-xsnake.py22
3 files changed, 25 insertions, 11 deletions
diff --git a/bots.py b/bots.py
index cf23602..dba440d 100644
--- a/bots.py
+++ b/bots.py
@@ -1,5 +1,8 @@
import random
+def right_bot(board, (x, y)):
+ return 'R'
+
def random_bot(board, (x, y)):
height = len(board)
width = len(board[0])
@@ -14,3 +17,7 @@ def random_bot(board, (x, y)):
moves.append('D')
return random.choice(moves)
+def random_bot2(board, (x, y)):
+ move = random_bot(board, (x, y))
+ nx, ny = x
+
diff --git a/common.py b/common.py
index 7ccf8e9..50b8eb0 100644
--- a/common.py
+++ b/common.py
@@ -1,5 +1,12 @@
import os
+directions = {
+ 'U': (0, -1),
+ 'D': (0, 1),
+ 'L': (-1, 0),
+ 'R': (1, 0),
+}
+
class Squares(object):
EMPTY = '.'
APPLE = '*'
diff --git a/snake.py b/snake.py
index 38da6e4..9350502 100755
--- a/snake.py
+++ b/snake.py
@@ -141,18 +141,14 @@ class SnakeEngine(object):
if cell.isupper(): # Snake head
self.surface.blit(self.eyes, r.topleft)
- def update_snakes(self):
- directions = {
- 'U': (0, -1),
- 'D': (0, 1),
- 'L': (-1, 0),
- 'R': (1, 0),
- }
+ def update_snakes(self, directions_id=id(directions)):
+ assert id(directions) == directions_id, \
+ "The common.directions dictionary has been modified since startup..."
for letter, (bot, colour, path) in self.bots.items():
board = deepcopy(self.board)
try:
- x, y = path[0]
+ x, y = path[-1]
d = bot(board, (x, y))
# Sanity checking...
@@ -166,6 +162,10 @@ class SnakeEngine(object):
nx = x + dx
ny = y + dy
+ if ny < 0 or ny >= self.rows or nx < 0 or nx >= self.columns:
+ self.remove_bot(letter)
+ continue
+
oldcell = self.board[ny][nx]
if oldcell in (Squares.EMPTY, Squares.APPLE):
# Move snake forward.
@@ -215,7 +215,7 @@ class SnakeEngine(object):
# Update the display.
pygame.display.flip()
- clock.tick(40)
+ clock.tick(5)
# Let the snakes move!
self.update_snakes()
@@ -224,9 +224,9 @@ class SnakeEngine(object):
pygame.display.quit()
if __name__ == '__main__':
- from bots import random_bot
+ from bots import *
game = SnakeEngine(25, 25, 10)
- game.add_bot(random_bot)
+ game.add_bot(right_bot)
game.run()