forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathturtle_invaders.py
More file actions
103 lines (82 loc) · 2.19 KB
/
Copy pathturtle_invaders.py
File metadata and controls
103 lines (82 loc) · 2.19 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import turtle
CANNON_STEP = 10
LASER_LENGTH = 20
LASER_SPEED = 10
window = turtle.Screen()
window.tracer(0)
window.setup(0.5, 0.75)
window.bgcolor(0.2, 0.2, 0.2)
window.title("The Real Python Space Invaders")
LEFT = -window.window_width() / 2
RIGHT = window.window_width() / 2
TOP = window.window_height() / 2
BOTTOM = -window.window_height() / 2
FLOOR_LEVEL = 0.9 * BOTTOM
GUTTER = 0.025 * window.window_width()
# Create laser cannon
cannon = turtle.Turtle()
cannon.penup()
cannon.color(1, 1, 1)
cannon.shape("square")
cannon.setposition(0, FLOOR_LEVEL)
lasers = []
def draw_cannon():
cannon.clear()
cannon.turtlesize(1, 4) # Base
cannon.stamp()
cannon.sety(FLOOR_LEVEL + 10)
cannon.turtlesize(1, 1.5) # Next tier
cannon.stamp()
cannon.sety(FLOOR_LEVEL + 20)
cannon.turtlesize(0.8, 0.3) # Tip of cannon
cannon.stamp()
cannon.sety(FLOOR_LEVEL)
def move_left():
new_x = cannon.xcor() - CANNON_STEP
if new_x >= LEFT + GUTTER:
cannon.setx(new_x)
draw_cannon()
def move_right():
new_x = cannon.xcor() + CANNON_STEP
if new_x <= RIGHT - GUTTER:
cannon.setx(new_x)
draw_cannon()
def create_laser():
laser = turtle.Turtle()
laser.penup()
laser.color(1, 0, 0)
laser.hideturtle()
laser.setposition(cannon.xcor(), cannon.ycor())
laser.setheading(90)
# Move laser to just above cannon tip
laser.forward(20)
# Prepare to draw the laser
laser.pendown()
laser.pensize(5)
lasers.append(laser)
def move_laser(laser):
laser.clear()
laser.forward(LASER_SPEED)
# Draw the laser
laser.forward(LASER_LENGTH)
laser.forward(-LASER_LENGTH)
# Key bindings
window.onkeypress(move_left, "Left")
window.onkeypress(move_right, "Right")
window.onkeypress(create_laser, "space")
window.onkeypress(turtle.bye, "q")
window.listen()
draw_cannon()
# Game loop
while True:
# Move all lasers
for laser in lasers.copy():
move_laser(laser)
# Remove laser if it goes off screen
if laser.ycor() > TOP:
laser.clear()
laser.hideturtle()
lasers.remove(laser)
turtle.turtles().remove(laser)
window.update()
turtle.done()