Skip to content

Commit 0835577

Browse files
authored
Create snakegame.py
Snake game
1 parent 0614f89 commit 0835577

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

snakegame.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
from random import randrange
2+
from turtle import *
3+
4+
from freegames import square, vector
5+
6+
food = vector(0, 0)
7+
snake = [vector(10, 0)]
8+
aim = vector(0, -10)
9+
10+
11+
def change(x, y):
12+
"""Change snake direction."""
13+
aim.x = x
14+
aim.y = y
15+
16+
17+
def inside(head):
18+
"""Return True if head inside boundaries."""
19+
return -200 < head.x < 190 and -200 < head.y < 190
20+
21+
22+
def move():
23+
"""Move snake forward one segment."""
24+
head = snake[-1].copy()
25+
head.move(aim)
26+
27+
if not inside(head) or head in snake:
28+
square(head.x, head.y, 9, 'red')
29+
update()
30+
return
31+
32+
snake.append(head)
33+
34+
if head == food:
35+
print('Snake:', len(snake))
36+
food.x = randrange(-15, 15) * 10
37+
food.y = randrange(-15, 15) * 10
38+
else:
39+
snake.pop(0)
40+
41+
clear()
42+
43+
for body in snake:
44+
square(body.x, body.y, 9, 'black')
45+
46+
square(food.x, food.y, 9, 'green')
47+
update()
48+
ontimer(move, 100)
49+
50+
51+
setup(420, 420, 370, 0)
52+
hideturtle()
53+
tracer(False)
54+
listen()
55+
onkey(lambda: change(10, 0), 'Right')
56+
onkey(lambda: change(-10, 0), 'Left')
57+
onkey(lambda: change(0, 10), 'Up')
58+
onkey(lambda: change(0, -10), 'Down')
59+
move()
60+
done()

0 commit comments

Comments
 (0)