-
Notifications
You must be signed in to change notification settings - Fork 0
/
obstacle_generator.py
58 lines (47 loc) · 1.92 KB
/
obstacle_generator.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
from turtle import Turtle
import random
import time
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
STARTING_X = 310
class ObstacleGenerator:
def __init__(self):
self.all_obstacles = []
self.level = 0
self.types = ["spaceship", "regular_asteroid", "fiery_asteroid"]
self.recycle = []
def create_obstacles(self):
"""Create obstacles and append to list for tracking"""
# Control frequency of created obstacles
obstacle_number = random.randint(0, 3)
# Obstacles are created at a higher frequency at higher levels to keep up with the increased speed of obstacles
if obstacle_number <= self.level:
if not self.recycle:
obstacle = Turtle()
obstacle.penup()
obstacle_type = random.choice(self.types)
obstacle.shape(f"images/{obstacle_type}.gif")
else:
# Recycle obstacles once they are off the screen to avoid continuously creating more objects
obstacle = self.recycle.pop()
obstacle.hideturtle()
obstacle.penup()
y_pos = random.randint(-230, 230)
x_pos = 310
obstacle.setheading(180)
self.all_obstacles.append(obstacle)
obstacle.goto(x_pos, y_pos)
obstacle.showturtle()
def obstacle_move(self):
"""Move obstacles forward with speed in accordance with game level"""
for i in self.all_obstacles:
# Remove obstacle from the all_obstacles list and add to recycle list once it is off the screen
if i.xcor() <= -350:
self.all_obstacles.remove(i)
self.recycle.append(i)
else:
i.forward(STARTING_MOVE_DISTANCE + (MOVE_INCREMENT * self.level))
def level_up(self):
"""Record increase in player level"""
self.level += 1
self.obstacle_move()