-
Notifications
You must be signed in to change notification settings - Fork 0
/
flappybird.py
567 lines (474 loc) · 17.6 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# Created by hnqiu on 17/06/2020
# https://github.com/hnqiu/FlappyBird
# Copyright (C) 2020 hnqiu. All Rights Reserved.
# Licensed under the MIT License. See LICENSE for details.
"""
Flappy Bird game implementation
"""
import random
import sys
import argparse
from itertools import cycle
parser = argparse.ArgumentParser(usage='%(prog)s [-h]/[-opt]',
description='Play Flappy Bird Game',
allow_abbrev=False)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-e', '--easy', action='store_true', help='easy mode')
group.add_argument('-m', '--median', action='store_true', help='median mode')
group.add_argument('-d', '--difficult', action='store_true', help='hard mode')
args = parser.parse_args()
import pygame
class Flappy:
"""
Flappy Bird game
"""
# window settings
FPS = 30
WIDTH = 288
HEIGHT = 512
FPSCLOCK, SCREEN = {}, {}
# game definitions
SPEED = 4 # moving speed
PIPEGAP = 100 # gap between upper and lower part of pipe
PIPEGAP_H = 100 # horizontal gap between adjacent pipes
# image and sound dicts
IMAGES, SOUNDS = {}, {}
# objects
bird, pipes, base = {}, {}, {}
# welcome message
msgXY = {}
# score
score = 0
def __init__(self, mode):
"""initialization of flappy bird"""
# init window
pygame.init()
self.FPSCLOCK = pygame.time.Clock()
self.SCREEN = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
pygame.display.set_caption('Flappy Bird')
# image and sound dicts
self.IMAGES, self.SOUNDS = asset('assets/')
# welcome message
self.msgXY = [int((self.WIDTH - self.IMAGES['message'].get_width()) /2),
int(self.HEIGHT * 0.12)]
# set moving speed
self.setSpeed(mode)
# construct objects
baseXY = [0, int(self.HEIGHT * .79)]
birdXY = [int(self.WIDTH * .2),
int((self.HEIGHT - self.IMAGES['bird'][0].get_height()) / 2)]
self.base = Base(baseXY, self.SPEED, self.IMAGES)
self.bird = Bird(birdXY, baseXY[1], self.IMAGES)
# main loop
while True:
self.showWelcome()
self.play()
self.gameOver()
def showWelcome(self):
""" Shows welcome screen animation of flappy bird """
# reset
self.bird.reset()
self.pipes.clear()
self.score = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and \
(event.key == pygame.K_SPACE or event.key == pygame.K_UP):
self.SOUNDS['wing'].play()
return
# bird oscillate
self.bird.shm()
# draw sprites
self.refresh('welc')
def play(self):
""" Play the game """
self.bird.softreset()
pipe1 = self.createPipe(self.WIDTH + 200)
pipe2 = self.createPipe(self.WIDTH + 200 + pipe1.width + self.PIPEGAP_H)
self.pipes = [pipe1, pipe2]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and \
(event.key == pygame.K_SPACE or event.key == pygame.K_UP):
self.SOUNDS['wing'].play()
self.bird.flap()
# check for crash status
isCrashed = checkCrash(self.bird, self.pipes)
if isCrashed:
return
# update score
birdMidPos = self.bird.X + self.bird.width / 2
for pipe in self.pipes:
pipeMidPos = pipe.x + pipe.width / 2
if pipeMidPos <= birdMidPos < pipeMidPos + self.SPEED:
self.SOUNDS['point'].play()
self.score += 1
# update bird
self.bird.update()
# update pipes
self.updatePipes()
# draw sprites
self.refresh('play')
def gameOver(self):
""" Show gameover screen """
# play hit and die sounds
self.SOUNDS['hit'].play()
self.SOUNDS['die'].play()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and \
(event.key == pygame.K_SPACE or event.key == pygame.K_UP):
return
# bird falling down
self.bird.update()
# draw sprites
self.refresh('over')
def setSpeed(self, m):
"""
Set objects' (pipes & base) moving speed based on difficulty
If not presented use the default value
"""
difficulty = {'-e': 4, '--easy': 4,
'-m': 5, '--median': 5,
'-d': 6, '--difficult': 6}
self.SPEED = difficulty.get(m, 4)
def createPipe(self, pos_x):
""" returns a pair of randomly generated pipes (upper & lower) """
# gap between upper and lower pipe
gapY = random.randrange(0, int(self.base.Y * 0.6 - self.PIPEGAP))
gapY += int(self.base.Y * 0.2)
pipeHeight = self.IMAGES['pipe'][0].get_height()
pipeX = pos_x
pipe_pair = {
'x': pipeX,
'upper': gapY - pipeHeight, # upper y
'lower': gapY + self.PIPEGAP # lower y
}
return Pipe(pipe_pair, self.SPEED, self.IMAGES)
def updatePipes(self):
""" move pipes, create new pipes & remove old pipes """
# move pipes to left
for p in self.pipes:
p.move()
# add new pipes
if 0 < self.pipes[0].x < self.SPEED+1: # x==4
diff = self.pipes[1].x - self.pipes[0].x
p = self.createPipe(self.pipes[1].x + diff)
self.pipes.append(p)
# remove old pipes
if self.pipes[0].x < -self.pipes[0].width:
self.pipes.pop(0)
def refresh(self, flag):
""" refresh game window """
# background, pipes & base
self.SCREEN.blit(self.IMAGES['background'], (0, 0))
for p in self.pipes:
p.draw(self.SCREEN)
if flag != 'over':
self.base.update()
self.base.draw(self.SCREEN)
# messages & score
if flag == 'welc':
self.SCREEN.blit(self.IMAGES['message'], self.msgXY)
elif flag == 'over':
self.SCREEN.blit(self.IMAGES['gameover'], (50, 180))
if flag in ('play', 'over'):
self.showScore()
# bird
self.bird.flapWing()
if flag == 'over':
self.bird.draw(self.SCREEN, 'dead')
else:
self.bird.draw(self.SCREEN)
pygame.display.update()
self.FPSCLOCK.tick(self.FPS)
def showScore(self):
""" displays score in center of screen """
scoreDigits = [int(x) for x in list(str(self.score))]
totalWidth = 0 # total width of all numbers to be printed
for digit in scoreDigits:
totalWidth += self.IMAGES['numbers'][digit].get_width()
Xoffset = (self.WIDTH - totalWidth) / 2
for digit in scoreDigits:
self.SCREEN.blit( self.IMAGES['numbers'][digit],
(Xoffset, self.HEIGHT * 0.1) )
Xoffset += self.IMAGES['numbers'][digit].get_width()
class Base:
"""
Definition of Base
"""
def __init__(self, coord, speed, image):
self.x, self.Y = coord[0], coord[1]
self.speed = speed
self.IMG = image['base']
# amount base can maximum shift to left
self.SHIFT = image['base'].get_width() - image['background'].get_width()
def update(self):
""" update base position """
self.x = -((-self.x + self.speed) % self.SHIFT)
def draw(self, obj):
""" draw base on screen """
obj.blit(self.IMG, (self.x, self.Y))
class Bird:
"""
Definition of Bird
"""
# bird wing mode
wingIndex = 0 # index to load bird mode
wingMode = cycle([0, 1, 2, 1]) # wing mode
loopIter = 0
# up-down simple harmonic motion on welcome screen
birdShm = {'val': 0, 'index': 1}
# bird states
X = 0 # constant
y = 0
INITY = 0 # init y on welcome, constant
yTOP = -24 # top y, constant
yBOTTOM = 100 # bottom y, constant, set in __init__
velY = 0
velMAXY = 10 # max descend velocity, const
velMINY = -8 # min ascend vel, const
ACCY = 1 # constant
rotation = 0
rate = 3 # rotation rate
flapVel = -9 # flap speed, constant
flapped = False
# image size
width, height = {}, {}
def __init__(self, coord, baseY, image):
self.X, self.y, self.INITY = coord[0], coord[1], coord[1]
self.IMG = image['bird'] # 3 wing modes
self.width = image['bird'][0].get_width()
self.height = image['bird'][0].get_height()
self.yBOTTOM = baseY - self.height
self.MASK = (
# hitmask for different bird wing modes
getHitmask(image['bird'][0]),
getHitmask(image['bird'][1]),
getHitmask(image['bird'][2])
)
def shm(self):
"""oscillates the value of birdShm['val'] between 8 and -8"""
if abs(self.birdShm['val']) == 8:
self.birdShm['index'] *= -1
if self.birdShm['index'] == 1:
self.birdShm['val'] += 1
else:
self.birdShm['val'] -= 1
self.y += self.birdShm['val']
def softreset(self):
""" reset bird states """
self.loopIter = 0
self.wingIndex = 0
self.velY = -9
self.rotation = 30
def reset(self):
""" reset bird states """
self.softreset()
self.rotation = 0
self.y = self.INITY
self.birdShm = {'val': 0, 'index': 1}
def flapWing(self):
""" wing animation """
self.loopIter += 1
if self.loopIter == 10: # flap wing every 10 frames
self.wingIndex = next(self.wingMode)
self.loopIter = 0
def flap(self):
""" bird flapped """
self.flapped = True
def update(self):
""" update bird vel, pos & rotation """
if self.flapped:
self.velY = self.flapVel
self.rotation = 30
self.flapped = False
elif self.velY < self.velMAXY:
self.velY += self.ACCY
self.y += self.velY
if self.y < self.yTOP:
self.y = self.yTOP
elif self.y > self.yBOTTOM:
self.y = self.yBOTTOM
# do not rotate if it is on the ground
if not self.touchground():
if self.rotation > -70:
self.rotation -= self.rate
def draw(self, obj, isdead = ''):
""" draw bird on screen """
if isdead == 'dead':
# use the midflap image
rotImg = pygame.transform.rotate(self.IMG[1],self.rotation)
else:
rotImg = pygame.transform.rotate(self.IMG[self.wingIndex],
self.rotation)
obj.blit(rotImg, (self.X, self.y))
def touchground(self):
""" check if on ground """
return self.y >= self.yBOTTOM
class Pipe:
"""
Definition of Pipe
An instance contains a pair of upper and lower pipes
"""
def __init__(self, p, speed, image):
self.x = p['x']
self.upperY, self.lowerY = p['upper'], p['lower']
self.speed = speed
self.IMG = image['pipe'] # upper & lower pipes
self.width = image['pipe'][0].get_width()
self.height = image['pipe'][0].get_height()
self.MASK = (
# hitmask for pipes
getHitmask(image['pipe'][0]), # upper
getHitmask(image['pipe'][1]) # lower
)
def move(self):
""" move pipe """
self.x -= self.speed
def draw(self, obj):
""" draw upper and lower pipes """
obj.blit(self.IMG[0], (self.x, self.upperY))
obj.blit(self.IMG[1], (self.x, self.lowerY))
def getHitmask(image):
"""returns a hitmask using an image's alpha."""
mask = []
for x in range(image.get_width()):
mask.append([])
for y in range(image.get_height()):
mask[x].append(bool(image.get_at((x,y))[3]))
return mask
def checkCrash(bird, pipes):
""" Returns True if bird collders with base or pipes. """
# if crashes into ground
if bird.touchground():
return True
# if collide with pipes
birdRect = pygame.Rect(bird.X, bird.y, bird.width, bird.height)
birdMask = bird.MASK[bird.wingIndex]
for p in pipes:
uRect = pygame.Rect(p.x, p.upperY, p.width, p.height)
lRect = pygame.Rect(p.x, p.lowerY, p.width, p.height)
uMask = p.MASK[0]
lMask = p.MASK[1]
uCollide = pixelCollision(birdRect, uRect, birdMask, uMask)
lCollide = pixelCollision(birdRect, lRect, birdMask, lMask)
if uCollide or lCollide:
return True
return False
def pixelCollision(rect1, rect2, hitmask1, hitmask2):
""" Checks if two objects collide and not just their rects """
rect = rect1.clip(rect2)
if rect.width == 0 or rect.height == 0:
return False
x1, y1 = rect.x - rect1.x, rect.y - rect1.y
x2, y2 = rect.x - rect2.x, rect.y - rect2.y
for x in range(rect.width):
for y in range(rect.height):
if hitmask1[x1+x][y1+y] and hitmask2[x2+x][y2+y]:
return True
return False
def asset(asset_dir):
""" load assets: image and sound """
IMAGES, SOUNDS = {}, {}
# list of all possible players (tuple of 3 positions of flap)
BIRDS_LIST = (
# red bird
(
asset_dir + 'sprites/redbird-upflap.png',
asset_dir + 'sprites/redbird-midflap.png',
asset_dir + 'sprites/redbird-downflap.png',
),
# blue bird
(
asset_dir + 'sprites/bluebird-upflap.png',
asset_dir + 'sprites/bluebird-midflap.png',
asset_dir + 'sprites/bluebird-downflap.png',
),
# yellow bird
(
asset_dir + 'sprites/yellowbird-upflap.png',
asset_dir + 'sprites/yellowbird-midflap.png',
asset_dir + 'sprites/yellowbird-downflap.png',
),
)
# list of backgrounds
BG_LIST = (
asset_dir + 'sprites/background-day.png',
asset_dir + 'sprites/background-night.png',
)
# list of pipes
PIPES_LIST = (
asset_dir + 'sprites/pipe-green.png',
asset_dir + 'sprites/pipe-red.png',
)
# numbers sprites for score display
IMAGES['numbers'] = (
pygame.image.load(asset_dir + 'sprites/0.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/1.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/2.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/3.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/4.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/5.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/6.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/7.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/8.png').convert_alpha(),
pygame.image.load(asset_dir + 'sprites/9.png').convert_alpha()
)
# game over sprite
IMAGES['gameover'] = pygame.image.load(
asset_dir + 'sprites/gameover.png').convert_alpha()
# message sprite for welcome screen
IMAGES['message'] = pygame.image.load(
asset_dir + 'sprites/message.png').convert_alpha()
# base (ground) sprite
IMAGES['base'] = pygame.image.load(
asset_dir + 'sprites/base.png').convert_alpha()
# background sprites
bgindex = random.randint(0, len(BG_LIST) - 1)
IMAGES['background'] = pygame.image.load(BG_LIST[bgindex]).convert()
# bird sprites
birdindex = random.randint(0, len(BIRDS_LIST) - 1)
IMAGES['bird'] = (
pygame.image.load(BIRDS_LIST[birdindex][0]).convert_alpha(),
pygame.image.load(BIRDS_LIST[birdindex][1]).convert_alpha(),
pygame.image.load(BIRDS_LIST[birdindex][2]).convert_alpha(),
)
# pipe sprites
pipeindex = random.randint(0, len(PIPES_LIST) - 1)
IMAGES['pipe'] = (
pygame.transform.flip(
pygame.image.load(PIPES_LIST[pipeindex]).convert_alpha(), False, True),
pygame.image.load(PIPES_LIST[pipeindex]).convert_alpha(),
)
# sounds
if 'win' in sys.platform:
soundExt = '.wav'
else:
soundExt = '.ogg'
SOUNDS['die'] = pygame.mixer.Sound(asset_dir + 'audio/die' + soundExt)
SOUNDS['hit'] = pygame.mixer.Sound(asset_dir + 'audio/hit' + soundExt)
SOUNDS['point'] = pygame.mixer.Sound(asset_dir + 'audio/point' + soundExt)
SOUNDS['swoosh'] = pygame.mixer.Sound(asset_dir + 'audio/swoosh' + soundExt)
SOUNDS['wing'] = pygame.mixer.Sound(asset_dir + 'audio/wing' + soundExt)
return IMAGES, SOUNDS
def main(mode):
"""
Main entrance
Game mode can be easy, median or difficult
"""
Flappy(mode)
if __name__ == '__main__':
main(sys.argv[1])