-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter5_FallingObjects.py
More file actions
95 lines (71 loc) · 2.26 KB
/
Chapter5_FallingObjects.py
File metadata and controls
95 lines (71 loc) · 2.26 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
import pygame
import random
pygame.init()
WIDTH=800
HEIGHT=600
screen=pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Catch the Object")
running=True
clock=pygame.time.Clock()
#Step-2 Basket Variable
player_width=100
player_height=20
player_x=350
player_y=550
player_speed=7
#Step-3 Falling Object
object_size=30
object_x=random.randint(0,770)
object_y=0
object_speed=5
object_type=random.choice(["ball","star","bomb"])
#Score
score=0
font=pygame.font.SysFont(None,36)
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
#Player movement (left or right)
keys=pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x-=player_speed
if keys[pygame.K_RIGHT]:
player_x+=player_speed
#object falling
object_y+=object_speed
#Collision detection
if object_y + object_size > player_y and object_x > player_x and object_x<player_x+player_width:
object_y=0
object_x=random.randint(0,770)
#assign score : logic
if object_type=="ball":
score+=1
elif object_type=="star":
score+=5
elif object_type=="bomb":
score-=5
object_type=random.choice(["ball","star","bomb"])
#draw player
pygame.draw.rect(screen, (0, 255, 0), (player_x,player_y,player_width, player_height))
#draw object
label_font=pygame.font.SysFont(None,20)
if object_type=="ball":
pygame.draw.circle(screen,(255,0,0),(object_x,object_y),15)
text=label_font.render("+1",True, (255,255,255))
screen.blit(text,(object_x-10,object_y-10))
elif object_type=="star":
pygame.draw.circle(screen,(255,255,0),(object_x,object_y),15)
text=label_font.render("+5",True, (0,0,0))
screen.blit(text,(object_x-10,object_y-10))
elif object_type=="bomb":
pygame.draw.circle(screen,(0,0,255),(object_x,object_y),15)
text=label_font.render("-5",True, (255,0,0))
screen.blit(text,(object_x-10,object_y-10))
#Show score
text=font.render(f"Score:{score}",True,(255,255,255))
screen.blit(text,(10,10))
pygame.display.update()
clock.tick(60) #fps
pygame.quit()