-
Notifications
You must be signed in to change notification settings - Fork 1
/
FlappyBird.py
220 lines (198 loc) · 8.39 KB
/
FlappyBird.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import random # For generating random numbers
import sys # We will use sys.exit to exit the program
import pygame
from pygame.locals import * # Basic pygame imports
import Hand_Detector
import cv2
# Global Variables for the game
FPS = 15
SCREENWIDTH = 289
SCREENHEIGHT = 511
GROUNDY = SCREENHEIGHT * 0.8
GAME_SPRITES = {}
GAME_SOUNDS = {}
SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))
PLAYER = 'images/bird.png'
BACKGROUND = 'images/background.png'
PIPE = 'images/pipe.png'
detector = Hand_Detector.handDetector(detectionCon=0.75)
wCam, hCam = 640,480
cap = cv2.VideoCapture(0)
cap.set(3,wCam)
cap.set(4,hCam)
pygame.init() # Initialize all pygame's modules
FPSCLOCK = pygame.time.Clock()
def welcomeScreen():
"""
Shows welcome images on the screen
"""
FPSCLOCK = pygame.time.Clock()
playerx = int(SCREENWIDTH/5)
playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2)
messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width())/2)
messagey = int(SCREENHEIGHT*0.13)
basex = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type==KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# If the user presses space or up key, start the game for them
elif event.type==KEYDOWN and (event.key==K_SPACE or event.key == K_UP):
return
else:
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
SCREEN.blit(GAME_SPRITES['message'], (messagex,messagey ))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
pygame.display.update()
FPSCLOCK.tick(FPS)
def mainGame():
score = 0
playerx = int(SCREENWIDTH/5)
playery = int(SCREENWIDTH/2)
basex = 0
newPipe1 = getRandomPipe()
newPipe2 = getRandomPipe()
upperPipes = [
{'x': SCREENWIDTH+200, 'y':newPipe1[0]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[0]['y']},
]
# my List of lower pipes
lowerPipes = [
{'x': SCREENWIDTH+200, 'y':newPipe1[1]['y']},
{'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y':newPipe2[1]['y']},
]
pipeVelX = -4
playerVelY = -9
playerMaxVelY = 10
playerMinVelY = -8
playerAccY = 1
playerFlapAccv = -8 # velocity while flapping
playerFlapped = False # It is true only when the bird is flapping
flag=0
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
count=0
status,img = cap.read()
img = detector.findHands(img)
myList = detector.findPosition(img,draw=False)
if(len(myList)!=0):
if (myList[8][2] < myList[6][2]) and (myList[12][2] < myList[10][2]):
if playery > 0:
playerVelY = playerFlapAccv
playerFlapped = True
GAME_SOUNDS['wing'].play()
cv2.namedWindow('Images', cv2.WINDOW_AUTOSIZE)
cv2.imshow("Images",img)
count+=1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
count=0
crashTest = isCollide(playerx, playery, upperPipes, lowerPipes) # This function will
if crashTest:
return
playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2
for pipe in upperPipes:
pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2
if pipeMidPos<= playerMidPos < pipeMidPos +4:
score +=1
print(f"Your score is {score}")
GAME_SOUNDS['point'].play()
if playerVelY <playerMaxVelY and not playerFlapped:
playerVelY += playerAccY
if playerFlapped:
playerFlapped = False
playerHeight = GAME_SPRITES['player'].get_height()
playery = playery + min(playerVelY, GROUNDY - playery - playerHeight)
for upperPipe , lowerPipe in zip(upperPipes, lowerPipes):
upperPipe['x'] += pipeVelX
lowerPipe['x'] += pipeVelX
if 0<upperPipes[0]['x']<5:
newpipe = getRandomPipe()
upperPipes.append(newpipe[0])
lowerPipes.append(newpipe[1])
if upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
upperPipes.pop(0)
lowerPipes.pop(0)
SCREEN.blit(GAME_SPRITES['background'], (0, 0))
for upperPipe, lowerPipe in zip(upperPipes, lowerPipes):
SCREEN.blit(GAME_SPRITES['pipe'][0], (upperPipe['x'], upperPipe['y']))
SCREEN.blit(GAME_SPRITES['pipe'][1], (lowerPipe['x'], lowerPipe['y']))
SCREEN.blit(GAME_SPRITES['base'], (basex, GROUNDY))
SCREEN.blit(GAME_SPRITES['player'], (playerx, playery))
myDigits = [int(x) for x in list(str(score))]
width = 0
for digit in myDigits:
width += GAME_SPRITES['numbers'][digit].get_width()
Xoffset = (SCREENWIDTH - width)/2
for digit in myDigits:
SCREEN.blit(GAME_SPRITES['numbers'][digit], (Xoffset, SCREENHEIGHT*0.12))
Xoffset += GAME_SPRITES['numbers'][digit].get_width()
pygame.display.update()
FPSCLOCK.tick(FPS)
def isCollide(playerx, playery, upperPipes, lowerPipes):
if playery> GROUNDY - 25 or playery<0:
GAME_SOUNDS['hit'].play()
return True
for pipe in upperPipes:
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
if(playery < pipeHeight + pipe['y'] and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()):
GAME_SOUNDS['hit'].play()
return True
for pipe in lowerPipes:
if (playery + GAME_SPRITES['player'].get_height() > pipe['y']) and abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width():
GAME_SOUNDS['hit'].play()
return True
return False
def getRandomPipe():
"""
Generate positions of two pipes(one bottom straight and one top rotated ) for blitting on the screen
"""
pipeHeight = GAME_SPRITES['pipe'][0].get_height()
offset = SCREENHEIGHT/3
y2 = offset + random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 *offset))
pipeX = SCREENWIDTH + 10
y1 = pipeHeight - y2 + offset
pipe = [
{'x': pipeX, 'y': -y1}, #upper Pipe
{'x': pipeX, 'y': y2} #lower Pipe
]
return pipe
def DriverGame():
# This will be the main point from where our game will start
#pygame.init() # Initialize all pygame's modules
#FPSCLOCK = pygame.time.Clock()
pygame.display.set_caption('Flappy Bird by CodeWithHarry')
GAME_SPRITES['numbers'] = (
pygame.image.load('images/0.png').convert_alpha(),
pygame.image.load('images/1.png').convert_alpha(),
pygame.image.load('images/2.png').convert_alpha(),
pygame.image.load('images/3.png').convert_alpha(),
pygame.image.load('images/4.png').convert_alpha(),
pygame.image.load('images/5.png').convert_alpha(),
pygame.image.load('images/6.png').convert_alpha(),
pygame.image.load('images/7.png').convert_alpha(),
pygame.image.load('images/8.png').convert_alpha(),
pygame.image.load('images/9.png').convert_alpha(),
)
GAME_SPRITES['message'] =pygame.image.load('images/message.png').convert_alpha()
GAME_SPRITES['base'] =pygame.image.load('images/base.png').convert_alpha()
GAME_SPRITES['pipe'] =(pygame.transform.rotate(pygame.image.load( PIPE).convert_alpha(), 180),
pygame.image.load(PIPE).convert_alpha()
)
# Game sounds
GAME_SOUNDS['die'] = pygame.mixer.Sound('music/die.wav')
GAME_SOUNDS['hit'] = pygame.mixer.Sound('music/hit.wav')
GAME_SOUNDS['point'] = pygame.mixer.Sound('music/point.wav')
GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('music/swoosh.wav')
GAME_SOUNDS['wing'] = pygame.mixer.Sound('music/wing.wav')
GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert()
GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha()
while True:
welcomeScreen() # Shows welcome screen to the user until he presses a button
mainGame() # This is the main game function