1+ from random import randrange
2+ from turtle import *
3+ import math
4+
5+ class Vector :
6+ def __init__ (self , x , y ):
7+ self .x = x
8+ self .y = y
9+
10+ def move (self , other ):
11+ """move this vector by adding another vector to it"""
12+ self .x += other .x
13+ self .y += other .y
14+
15+ def __sub__ (self , other ):
16+ """subtract two vectors to find the difference"""
17+ return Vector (self .x - other .x , self .y - other .y )
18+
19+ def __abs__ (self ):
20+ return math .hypot (self .x , self .y )
21+
22+ bird = Vector (0 , 0 )
23+ balls = []
24+ score = 0
25+ game_over = False
26+
27+ def tap (x , y ):
28+ """move bird up in response to screen tap or reset if dead"""
29+ global game_over
30+
31+ if game_over :
32+ reset_game ()
33+ else :
34+ up = Vector (0 , 30 )
35+ bird .move (up )
36+
37+ def reset_game ():
38+ """resets the game state and starts the loop again"""
39+ global game_over , score
40+ game_over = False
41+ score = 0
42+ bird .x , bird .y = 0 , 0
43+ balls .clear ()
44+ move ()
45+
46+ def inside (point ):
47+ """return True if point on screen"""
48+ return - 200 < point .x < 200 and - 200 < point .y < 200
49+
50+ def draw (alive ):
51+ clear ()
52+
53+ goto (bird .x , bird .y )
54+ if alive :
55+ dot (10 , '#06b6d4' )
56+ else :
57+ dot (10 , '#ef4444' )
58+
59+ for ball in balls :
60+ goto (ball .x , ball .y )
61+ dot (20 , '#8b5cf6' )
62+
63+ goto (- 190 , 180 )
64+ color ('white' )
65+ write (f"Score: { score } " , font = ("Arial" , 14 , "bold" ))
66+
67+ if not alive :
68+ goto (0 , 20 )
69+ write ("💥 GAME OVER 💥" , align = "center" , font = ("Arial" , 24 , "bold" ))
70+ goto (0 , - 20 )
71+ write ("🔄 Click anywhere to Play Again" , align = "center" , font = ("Arial" , 14 , "normal" ))
72+
73+ update ()
74+
75+ def move ():
76+ """update object positions"""
77+ global score , game_over
78+
79+ if game_over :
80+ return
81+
82+ bird .y -= 5
83+
84+ for ball in balls :
85+ ball .x -= 3
86+
87+ if randrange (10 ) == 0 :
88+ y = randrange (- 199 , 199 )
89+ ball = Vector (199 , y )
90+ balls .append (ball )
91+
92+ while len (balls ) > 0 and not inside (balls [0 ]):
93+ balls .pop (0 )
94+ score += 1
95+
96+ if not inside (bird ):
97+ game_over = True
98+ draw (False )
99+ return
100+
101+ for ball in balls :
102+ if abs (ball - bird ) < 15 :
103+ game_over = True
104+ draw (False )
105+ return
106+
107+ draw (True )
108+ ontimer (move , 50 )
109+
110+ setup (420 , 420 , 370 , 0 )
111+ bgcolor ('#0f172a' )
112+ hideturtle ()
113+ up ()
114+ tracer (False )
115+ onscreenclick (tap )
116+ move ()
117+ done ()
0 commit comments