-
Notifications
You must be signed in to change notification settings - Fork 0
/
turtle_move_around.py
76 lines (60 loc) · 1.47 KB
/
turtle_move_around.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import turtle
# Set up the screen
wn = turtle.Screen()
wn.title("Move Around")
wn.bgcolor("green")
wn.setup(width=600, height=600)
# Player
player = turtle.Turtle()
player.shape("circle")
player.color("yellow")
# player.penup()
player.goto(0,0)
player.direction = "stop"
# Functions
def go_up():
if player.direction != "down":
player.direction = "up"
def go_down():
if player.direction != "up":
player.direction = "down"
def go_left():
if player.direction != "right":
player.direction = "left"
def go_right():
if player.direction != "left":
player.direction = "right"
def move():
if player.direction == "up":
y = player.ycor()
player.sety(y + 10)
if player.direction == "down":
y = player.ycor()
player.sety(y - 10)
if player.direction == "left":
x = player.xcor()
player.setx(x - 10)
if player.direction == "right":
x = player.xcor()
player.setx(x + 10)
player.direction = "stop"
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_left, "Left")
wn.onkeypress(go_right, "Right")
# Main game loop
while True:
wn.update()
# Check for a collision with the borders
if player.xcor()>290:
player.setx(290)
if player.xcor()<-290:
player.setx(-290)
if player.ycor()>290:
player.sety(290)
if player.ycor()<-290:
player.sety(-290)
move()
wn.mainloop()