|
| 1 | +"""Snake, classic arcade game. |
| 2 | +Exercises |
| 3 | +1. How do you make the snake faster or slower? |
| 4 | +2. How can you make the snake go around the edges? |
| 5 | +3. How would you move the food? |
| 6 | +4. Change the snake to respond to mouse clicks. |
| 7 | +""" |
| 8 | + |
| 9 | +from random import randrange |
| 10 | +from turtle import * |
| 11 | + |
| 12 | +from freegames import square, vector |
| 13 | + |
| 14 | +food = vector(0, 0) |
| 15 | +snake = [vector(10, 0)] |
| 16 | +aim = vector(0, -10) |
| 17 | + |
| 18 | + |
| 19 | +def change(x, y): |
| 20 | + """Change snake direction.""" |
| 21 | + aim.x = x |
| 22 | + aim.y = y |
| 23 | + |
| 24 | + |
| 25 | +def inside(head): |
| 26 | + """Return True if head inside boundaries.""" |
| 27 | + return -200 < head.x < 190 and -200 < head.y < 190 |
| 28 | + |
| 29 | + |
| 30 | +def move(): |
| 31 | + """Move snake forward one segment.""" |
| 32 | + head = snake[-1].copy() |
| 33 | + head.move(aim) |
| 34 | + |
| 35 | + if not inside(head) or head in snake: |
| 36 | + square(head.x, head.y, 9, 'red') |
| 37 | + update() |
| 38 | + return |
| 39 | + |
| 40 | + snake.append(head) |
| 41 | + |
| 42 | + if head == food: |
| 43 | + print('Snake:', len(snake)) |
| 44 | + food.x = randrange(-15, 15) * 10 |
| 45 | + food.y = randrange(-15, 15) * 10 |
| 46 | + else: |
| 47 | + snake.pop(0) |
| 48 | + |
| 49 | + clear() |
| 50 | + |
| 51 | + for body in snake: |
| 52 | + square(body.x, body.y, 9, 'black') |
| 53 | + |
| 54 | + square(food.x, food.y, 9, 'green') |
| 55 | + update() |
| 56 | + ontimer(move, 100) |
| 57 | + |
| 58 | + |
| 59 | +setup(420, 420, 370, 0) |
| 60 | +hideturtle() |
| 61 | +tracer(False) |
| 62 | +listen() |
| 63 | +onkey(lambda: change(10, 0), 'Right') |
| 64 | +onkey(lambda: change(-10, 0), 'Left') |
| 65 | +onkey(lambda: change(0, 10), 'Up') |
| 66 | +onkey(lambda: change(0, -10), 'Down') |
| 67 | +move() |
| 68 | +done() |
0 commit comments