Skip to content

Commit d329048

Browse files
py code
1 parent f9752e6 commit d329048

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

snake-py/snake.py

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

0 commit comments

Comments
 (0)