turtle_invasion_1.html
001|
002|
003| import random
004| import time
005| import turtle
006|
007| from turtle_game_entities_1 import Enemy, Laser
008|
009| WIDTH = 600
010| HEIGHT = 600
011|
012| player_rotation_step = 3
013| spawn_interval_range = 1, 3
014| laser_speed = 15
015| total_ammunition = 100
016|
017|
018| enemies = []
019| lasers = []
020| score = 0
021|
022|
023| screen = turtle.Screen()
024| screen.tracer(0)
025| screen.setup(WIDTH, HEIGHT)
026| screen.bgcolor(0.2, 0.2, 0.2)
027| screen.listen()
028|
029|
030| player = turtle.Turtle()
031| player.shape("triangle")
032| player.shapesize(stretch_len=1.5)
033| player.color("purple")
034|
035| player.rotation = 0
036| player.ammunition = total_ammunition
037|
038|
039| def turn_left():
040| player.rotation = player_rotation_step
041|
042| def turn_right():
043| player.rotation = -player_rotation_step
044|
045| def stop_turning():
046| player.rotation = 0
047|
048| screen.onkeypress(turn_left, "Left")
049| screen.onkeyrelease(stop_turning, "Left")
050| screen.onkeypress(turn_right, "Right")
051| screen.onkeyrelease(stop_turning, "Right")
052|
053|
054| def shoot_laser():
055| laser = Laser(player)
056| laser.set_speed(laser_speed)
057| lasers.append(laser)
058| player.ammunition -= 1
059| if not player.ammunition:
060| screen.onkeypress(None, "space")
061|
062| screen.onkeypress(shoot_laser, "space")
063|
064|
065| def cleanup_entity(entity, entities_list):
066| entity.hideturtle()
067| entity.clear()
068| screen.update()
069| entities_list.remove(entity)
070| turtle.turtles().remove(entity)
071|
072|
073| start_enemy_spawn_timer = time.time()
074| next_enemy_spawn_delay = 0
075| while player.ammunition > 0 or lasers:
076| screen.title(
077| f"Ammunition: {player.ammunition} "
078| f"| Score: {int(score):3}"
079| )
080| player.left(player.rotation)
081|
082|
083| if (
084| time.time() - start_enemy_spawn_timer
085| > next_enemy_spawn_delay
086| ):
087| new_enemy = Enemy()
088| enemies.append(new_enemy)
089| new_enemy.set_start_position(WIDTH, HEIGHT)
090| next_enemy_spawn_delay = random.uniform(
091| *spawn_interval_range
092| )
093| start_enemy_spawn_timer = time.time()
094|
095|
096| for enemy in enemies.copy():
097| enemy.move()
098| enemy.change_direction()
099| if enemy.is_out_of_bounds(WIDTH, HEIGHT):
100| cleanup_entity(enemy, enemies)
101|
102|
103| for laser in lasers.copy():
104| laser.move()
105| if laser.is_out_of_bounds(WIDTH, HEIGHT):
106| cleanup_entity(laser, lasers)
107|
108| for enemy in enemies:
109| if laser.has_collided_with(enemy):
110| score += enemy.enemy_speed
111| cleanup_entity(enemy, enemies)
112| cleanup_entity(laser, lasers)
113|
114| screen.update()
115|
116|
117|
118| turtle.done()
119|