Professional Documents
Culture Documents
Snake
Snake
import random
def appStarted(app):
app.rows = 10
app.cols = 10
app.margin = 5 # margin around
grid
app.timerDelay = 250
initSnakeAndFood(app)
app.waitingForFirstKeyPress = True
def initSnakeAndFood(app):
app.snake = [(0,0)]
app.direction = (0, +1) # (drow,
dcol)
placeFood(app)
app.gameOver = False
def timerFired(app):
if app.gameOver or
app.waitingForFirstKeyPress: return
takeStep(app)
def takeStep(app):
(drow, dcol) = app.direction
(headRow, headCol) = app.snake[0]
(newRow, newCol) = (headRow+drow,
headCol+dcol)
if ((newRow < 0) or (newRow >=
app.rows) or
(newCol < 0) or (newCol >=
app.cols) or
((newRow, newCol) in
app.snake)):
app.gameOver = True
else:
app.snake.insert(0, (newRow,
newCol))
if (app.foodPosition ==
(newRow, newCol)):
placeFood(app)
else:
# didn't eat, so remove
old tail (slither forward)
app.snake.pop()
def placeFood(app):
# Keep trying random positions
until we find one that is not in
# the snake. Note: there are more
sophisticated ways to do this.
while True:
row = random.randint(0,
app.rows-1)
col = random.randint(0,
app.cols-1)
if (row,col) not in app.snake:
app.foodPosition = (row,
col)
return
canvas.create_text(app.width/2,
app.height/2+40,
text='Press
r to restart!',
font='Arial
26 bold')
canvas.create_text(app.width/2,
app.height/2,
text='Press
any key to start!',
font='Arial
26 bold')
else:
drawBoard(app, canvas)
drawSnake(app, canvas)
drawFood(app, canvas)
drawGameOver(app, canvas)
runApp(width=400, height=400)