hello everyone
Today I will share with you a flying bird game developed with Python.
Flying Bird (English name of the game: Flappy Bird)
A mobile game developed by an independent developer in Vietnam, it was a very popular mobile game before
Mini-game goal: let the bird go through the pipe without hitting any objects, challenge a longer distance
Today, let us use python to reproduce this game together! ! !
Environmental use
- Python 3.8
–> interpreter
- Pycharm
–> editor
Required material
sound effects
Picture material
Effect display
The background and other materials can also be modified
Let me show you the background of the blogger’s magic reform
Code Display
modules used
import cfg import sys import random import pygame
game initialization
def initGame(): pygame.init() pygame. mixer. init() screen = pygame.display.set_mode((cfg.SCREENWIDTH, cfg.SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') return screen
show current score
def showScore(screen, score, number_images): digits = list(str(int(score))) width = 0 for d in digits: width += number_images.get(d).get_width() offset = (cfg. SCREENWIDTH - width) / 2 for d in digits: screen.blit(number_images.get(d), (offset, cfg.SCREENHEIGHT*0.1)) offset += number_images.get(d).get_width()
main function
def main(): screen = initGame() # Load the necessary game assets # Python learning exchange group 872937351 sounds = dict() for key, value in cfg.AUDIO_PATHS.items(): sounds[key] = pygame. mixer. Sound(value) # --Import digital image number_images = dict() for key, value in cfg.NUMBER_IMAGE_PATHS.items(): number_images[key] = pygame.image.load(value).convert_alpha() # -- pipeline pipe_images = dict() pipe_images['bottom'] = pygame.image.load(random.choice(list(cfg.PIPE_IMAGE_PATHS.values()))).convert_alpha() pipe_images['top'] = pygame.transform.rotate(pipe_images['bottom'], 180) # -- bird image bird_images = dict() for key, value in cfg.BIRD_IMAGE_PATHS[random.choice(list(cfg.BIRD_IMAGE_PATHS.keys()))].items(): bird_images[key] = pygame.image.load(value).convert_alpha() # --Background picture background_image = pygame.image.load(random.choice(list(cfg.BACKGROUND_IMAGE_PATHS.values()))).convert_alpha() # --Other pictures other_images = dict() for key, value in cfg.OTHER_IMAGE_PATHS.items(): other_images[key] = pygame.image.load(value).convert_alpha() # Game start interface game_start_info = startGame(screen, sounds, bird_images, other_images, background_image, cfg) # enter the main game score = 0 bird_pos, base_pos, bird_idx = list(game_start_info. values()) base_diff_bg = other_images['base'].get_width() - background_image.get_width() clock = pygame.time.Clock() # --Pipeline class pipe_sprites = pygame.sprite.Group() for i in range(2): pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top')) pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=(cfg.SCREENWIDTH + 200 + i*cfg.SCREENWIDTH/2, pipe_pos.get('top')[-1] ))) pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=(cfg.SCREENWIDTH + 200 + i*cfg.SCREENWIDTH/2, pipe_pos.get('bottom')[-1] ))) # --bird class bird = Bird(images=bird_images, idx=bird_idx, position=bird_pos) # --Whether to increase pipe is_add_pipe = True # -- Whether the game is in progress is_game_running = True while is_game_running: 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() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE or event.key == pygame.K_UP: bird. setFlapped() sounds['wing'].play() # --Impact checking for pipe in pipe_sprites: if pygame.sprite.collide_mask(bird, pipe): sounds['hit'].play() is_game_running = False # --Update the bird boundary_values = [0, base_pos[-1]] is_dead = bird.update(boundary_values, float(clock.tick(cfg.FPS))/1000.) if is_dead: sounds['hit'].play() is_game_running = False # --Move the base to achieve the effect of the bird flying forward base_pos[0] = -((-base_pos[0] + 4) % base_diff_bg) # --Move the pipe to achieve the effect of the bird flying forward flag = False for pipe in pipe_sprites: pipe.rect.left -= 4 if pipe.rect.centerx < bird.rect.centerx and not pipe.used_for_score: pipe.used_for_score = True score += 0.5 if '.5' in str(score): sounds['point'].play() if pipe.rect.left < 5 and pipe.rect.left > 0 and is_add_pipe: pipe_pos = Pipe.randomPipe(cfg, pipe_images.get('top')) pipe_sprites.add(Pipe(image=pipe_images.get('top'), position=pipe_pos.get('top'))) pipe_sprites.add(Pipe(image=pipe_images.get('bottom'), position=pipe_pos.get('bottom'))) is_add_pipe = False elif pipe.rect.right < 0: pipe_sprites. remove(pipe) flag = True if flag: is_add_pipe = True # -- Bind necessary elements to the screen screen.blit(backgroud_image, (0, 0)) pipe_sprites. draw(screen) screen.blit(other_images['base'], base_pos) showScore(screen, score, number_images) bird. draw(screen) pygame.display.update() clock.tick(cfg.FPS) endGame(screen, sounds, showScore, score, number_images, bird, pipe_sprites, background_image, other_images, base_pos, cfg)
In addition, I am afraid that everyone will not use it, so I have prepared the written one for everyone, download it and open it to use!
The source code is placed on the Baidu cloud disk. You need to scan the QR code of the CSDN official certification below on WeChat to get it for free
Reader benefits: If you also like programming and want to get a higher salary by learning Python, then this set of Python learning materials must be useful to you!
For 0 basic beginners:
If you are a zero-based novice, you can consider getting started with Python quickly
On the one hand, the learning time is relatively short, and the learning content is more comprehensive and concentrated
On the other hand, you can find a learning plan that suits you
Including: Python installation package + activation code, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other tutorials. Take you to learn Python systematically from zero foundation!
Reader Benefits: 2023 Zero-Basic Python Essentials (Video + Source Code + Tools + Software) Safe Links for Free Collection
1. Learning routes in all directions of Python
The route of all directions in Python is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.
Second, learning software
If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here, which saves you a lot of time.
3. Introductory learning video
When we watch videos and learn, we can’t just move our eyes and brain without using our hands. A more scientific learning method is to use them after understanding. At this time, the hands-on project is very suitable.
Fourth, actual combat cases
Optical theory is useless, you have to learn to follow along, and you have to do it yourself, so that you can apply what you have learned to practice. At this time, you can learn from some actual combat cases.
Five, 100 Python practice questions
Check the learning results.
6. Interview materials
We must learn Python to find high-paying jobs. The following interview questions are the latest interview materials from first-line Internet companies such as Ali, Tencent, and Byte, and Ali bosses have given authoritative answers. After finishing this set The interview materials believe that everyone can find a satisfactory job.
This full version of the full set of Python learning materials has been uploaded. If you need it, you can scan the CSDN official certification QR code below or click the link to get it for free【 Guaranteed 100% Free
】
Reader benefits: 2023 zero-basic Python essential materials (video + source code + tools + software) secure link for free