当前位置:网站首页>[pyGame collection] please check the game guide through childhood: are there any games you have played? (attach five source codes for self access)
[pyGame collection] please check the game guide through childhood: are there any games you have played? (attach five source codes for self access)
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article is mainly about pygame Realize five kinds of small games !
** article Source code Free access : To thank every project that pays attention to my little cute article Source code It's all nothing
Compensation sharing drop
I can get the complete source code and material for myself ! Just take the drops directly
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Text
No, no, no, No ! No, there are still people who don't know these games now ?!
Today, , You and I have grown up , From an ignorant child to an adult . Adult US , I often miss the past , pregnant
Read the carefree childhood .
In childhood , Time is like a playmate who accompanies us to play , The pace is light and slow , Where did the ant climb , The colorful shapes of the clouds ,
It's all clear . Games occupy most of our childhood happiness . Let's sit on the time machine , Back to childhood , Remember us
Childhood games , Looking for childhood fun .
Today Xiaobian will show you about , Childhood Five games The great charm of ~

One 、 Little dinosaur
1) Code display
import cfg
import sys
import random
import pygame
from modules import *
'''main'''
def main(highest_score):
# Game initialization
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(' Little dinosaur breakthrough game ')
# Import all sound files
sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
sounds[key] = pygame.mixer.Sound(value)
# Game start screen
GameStartInterface(screen, sounds, cfg)
# Define some necessary elements and variables in the game
score = 0
score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)
highest_score = highest_score
highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True)
dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1]))
cloud_sprites_group = pygame.sprite.Group()
cactus_sprites_group = pygame.sprite.Group()
ptera_sprites_group = pygame.sprite.Group()
add_obstacle_timer = 0
score_timer = 0
# The main cycle of the game
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
dino.jump(sounds)
elif event.key == pygame.K_DOWN:
dino.duck()
elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
dino.unduck()
screen.fill(cfg.BACKGROUND_COLOR)
# -- Add cloud randomly
if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75))))
# -- Add cactus randomly / Flying dragon
add_obstacle_timer += 1
if add_obstacle_timer > random.randrange(50, 150):
add_obstacle_timer = 0
random_value = random.randrange(0, 10)
if random_value >= 5 and random_value <= 7:
cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
else:
position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20]
ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys))))
# -- Update game elements
dino.update()
ground.update()
cloud_sprites_group.update()
cactus_sprites_group.update()
ptera_sprites_group.update()
score_timer += 1
if score_timer > (cfg.FPS//12):
score_timer = 0
score += 1
score = min(score, 99999)
if score > highest_score:
highest_score = score
if score % 100 == 0:
sounds['point'].play()
if score % 1000 == 0:
ground.speed -= 1
for item in cloud_sprites_group:
item.speed -= 1
for item in cactus_sprites_group:
item.speed -= 1
for item in ptera_sprites_group:
item.speed -= 1
# -- collision detection
for item in cactus_sprites_group:
if pygame.sprite.collide_mask(dino, item):
dino.die(sounds)
for item in ptera_sprites_group:
if pygame.sprite.collide_mask(dino, item):
dino.die(sounds)
# -- Draw game elements to the screen
dino.draw(screen)
ground.draw(screen)
cloud_sprites_group.draw(screen)
cactus_sprites_group.draw(screen)
ptera_sprites_group.draw(screen)
score_board.set(score)
highest_score_board.set(highest_score)
score_board.draw(screen)
highest_score_board.draw(screen)
# -- Update screen
pygame.display.update()
clock.tick(cfg.FPS)
# -- Is the game over
if dino.is_dead:
break
# Game ending screen
return GameEndInterface(screen, cfg), highest_score
'''run'''
if __name__ == '__main__':
highest_score = 0
while True:
flag, highest_score = main(highest_score)
if not flag: break2) Effect display


Two 、 Tanks war
1) Code display
import os
import cfg
import pygame
from modules import *
''' The main function '''
def main(cfg):
# Game initialization
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
pygame.display.set_caption(cfg.TITLE)
# Load game material
sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
sounds[key] = pygame.mixer.Sound(value)
sounds[key].set_volume(1)
# Start interface
is_dual_mode = gameStartInterface(screen, cfg)
# The number of levels
levelfilepaths = [os.path.join(cfg.LEVELFILEDIR, filename) for filename in sorted(os.listdir(cfg.LEVELFILEDIR))]
# Main circulation
for idx, levelfilepath in enumerate(levelfilepaths):
switchLevelIterface(screen, cfg, idx+1)
game_level = GameLevel(idx+1, levelfilepath, sounds, is_dual_mode, cfg)
is_win = game_level.start(screen)
if not is_win: break
is_quit_game = gameEndIterface(screen, cfg, is_win)
return is_quit_game
'''run'''
if __name__ == '__main__':
while True:
is_quit_game = main(cfg)
if is_quit_game:
break2) Effect display


3、 ... and 、 The bomb people
1) Code display
'''
Function:
Bomber games
'''
import sys
import cfg
import random
import pygame
from modules import *
''' The main program of the game '''
def main(cfg):
# initialization
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(' The bomb people ')
# Start interface
Interface(screen, cfg, mode='game_start')
# The main cycle of the game
font = pygame.font.SysFont('Consolas', 15)
for gamemap_path in cfg.GAMEMAPPATHS:
# - Map
map_parser = mapParser(gamemap_path, bg_paths=cfg.BACKGROUNDPATHS, wall_paths=cfg.WALLPATHS, blocksize=cfg.BLOCKSIZE)
# - Fruits
fruit_sprite_group = pygame.sprite.Group()
used_spaces = []
for i in range(5):
coordinate = map_parser.randomGetSpace(used_spaces)
used_spaces.append(coordinate)
fruit_sprite_group.add(Fruit(random.choice(cfg.FRUITPATHS), coordinate=coordinate, blocksize=cfg.BLOCKSIZE))
# - We Hero
coordinate = map_parser.randomGetSpace(used_spaces)
used_spaces.append(coordinate)
ourhero = Hero(imagepaths=cfg.HEROZELDAPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='ZELDA')
# - The computer Hero
aihero_sprite_group = pygame.sprite.Group()
coordinate = map_parser.randomGetSpace(used_spaces)
aihero_sprite_group.add(Hero(imagepaths=cfg.HEROBATMANPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='BATMAN'))
used_spaces.append(coordinate)
coordinate = map_parser.randomGetSpace(used_spaces)
aihero_sprite_group.add(Hero(imagepaths=cfg.HERODKPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='DK'))
used_spaces.append(coordinate)
# - bomb bomb
bomb_sprite_group = pygame.sprite.Group()
# - Used to judge whether a game is winning or losing flag
is_win_flag = False
# - Main circulation
screen = pygame.display.set_mode(map_parser.screen_size)
clock = pygame.time.Clock()
while True:
dt = clock.tick(cfg.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(-1)
# --↑↓←→ Key control up and down, left and right , The space bar throws bombs
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
ourhero.move('up')
elif event.key == pygame.K_DOWN:
ourhero.move('down')
elif event.key == pygame.K_LEFT:
ourhero.move('left')
elif event.key == pygame.K_RIGHT:
ourhero.move('right')
elif event.key == pygame.K_SPACE:
if ourhero.bomb_cooling_count <= 0:
bomb_sprite_group.add(ourhero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH))
screen.fill(cfg.WHITE)
# -- The computer Hero Random action
for hero in aihero_sprite_group:
action, flag = hero.randomAction(dt)
if flag and action == 'dropbomb':
bomb_sprite_group.add(hero.generateBomb(imagepath=cfg.BOMBPATH, digitalcolor=cfg.YELLOW, explode_imagepath=cfg.FIREPATH))
# -- Eat fruit and health ( As long as it is Hero, All can be added )
ourhero.eatFruit(fruit_sprite_group)
for hero in aihero_sprite_group:
hero.eatFruit(fruit_sprite_group)
# -- Game elements are all tied to the screen
map_parser.draw(screen)
for bomb in bomb_sprite_group:
if not bomb.is_being:
bomb_sprite_group.remove(bomb)
explode_area = bomb.draw(screen, dt, map_parser)
if explode_area:
# -- Within the scope of the explosion flame Hero Health will continue to decline
if ourhero.coordinate in explode_area:
ourhero.health_value -= bomb.harm_value
for hero in aihero_sprite_group:
if hero.coordinate in explode_area:
hero.health_value -= bomb.harm_value
fruit_sprite_group.draw(screen)
for hero in aihero_sprite_group:
hero.draw(screen, dt)
ourhero.draw(screen, dt)
# -- The upper left corner shows health
pos_x = showText(screen, font, text=ourhero.hero_name+'(our):'+str(ourhero.health_value), color=cfg.YELLOW, position=[5, 5])
for hero in aihero_sprite_group:
pos_x, pos_y = pos_x+15, 5
pos_x = showText(screen, font, text=hero.hero_name+'(ai):'+str(hero.health_value), color=cfg.YELLOW, position=[pos_x, pos_y])
# -- Our player's health is less than or equal to 0/ Computer player's health is less than or equal to 0 Then judge the end of the game
if ourhero.health_value <= 0:
is_win_flag = False
break
for hero in aihero_sprite_group:
if hero.health_value <= 0:
aihero_sprite_group.remove(hero)
if len(aihero_sprite_group) == 0:
is_win_flag = True
break
pygame.display.update()
clock.tick(cfg.FPS)
if is_win_flag:
Interface(screen, cfg, mode='game_switch')
else:
break
Interface(screen, cfg, mode='game_end')
'''run'''
if __name__ == '__main__':
while True:
main(cfg)2) Effect display

Four 、 Bean eater
1) Code display
import sys
import cfg
import pygame
import modules.Levels as Levels
''' Start a level game '''
def startLevelGame(level, screen, font):
clock = pygame.time.Clock()
SCORE = 0
wall_sprites = level.setupWalls(cfg.SKYBLUE)
gate_sprites = level.setupGate(cfg.WHITE)
hero_sprites, ghost_sprites = level.setupPlayers(cfg.HEROPATH, [cfg.BlinkyPATH, cfg.ClydePATH, cfg.InkyPATH, cfg.PinkyPATH])
food_sprites = level.setupFood(cfg.YELLOW, cfg.WHITE)
is_clearance = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(-1)
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
for hero in hero_sprites:
hero.changeSpeed([-1, 0])
hero.is_move = True
elif event.key == pygame.K_RIGHT:
for hero in hero_sprites:
hero.changeSpeed([1, 0])
hero.is_move = True
elif event.key == pygame.K_UP:
for hero in hero_sprites:
hero.changeSpeed([0, -1])
hero.is_move = True
elif event.key == pygame.K_DOWN:
for hero in hero_sprites:
hero.changeSpeed([0, 1])
hero.is_move = True
if event.type == pygame.KEYUP:
if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN):
hero.is_move = False
screen.fill(cfg.BLACK)
for hero in hero_sprites:
hero.update(wall_sprites, gate_sprites)
hero_sprites.draw(screen)
for hero in hero_sprites:
food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True)
SCORE += len(food_eaten)
wall_sprites.draw(screen)
gate_sprites.draw(screen)
food_sprites.draw(screen)
for ghost in ghost_sprites:
# Ghost random motion ( The effect is not good and there are BUG)
'''
res = ghost.update(wall_sprites, None)
while not res:
ghost.changeSpeed(ghost.randomDirection())
res = ghost.update(wall_sprites, None)
'''
# Specify the ghost motion path
if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
ghost.tracks_loc[1] += 1
else:
if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
ghost.tracks_loc[0] += 1
elif ghost.role_name == 'Clyde':
ghost.tracks_loc[0] = 2
else:
ghost.tracks_loc[0] = 0
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
ghost.tracks_loc[1] = 0
if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
else:
if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
loc0 = ghost.tracks_loc[0] + 1
elif ghost.role_name == 'Clyde':
loc0 = 2
else:
loc0 = 0
ghost.changeSpeed(ghost.tracks[loc0][0: 2])
ghost.update(wall_sprites, None)
ghost_sprites.draw(screen)
score_text = font.render("Score: %s" % SCORE, True, cfg.RED)
screen.blit(score_text, [10, 10])
if len(food_sprites) == 0:
is_clearance = True
break
if pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):
is_clearance = False
break
pygame.display.flip()
clock.tick(10)
return is_clearance
''' According to the text '''
def showText(screen, font, is_clearance, flag=False):
clock = pygame.time.Clock()
msg = 'Game Over!' if not is_clearance else 'Congratulations, you won!'
positions = [[235, 233], [65, 303], [170, 333]] if not is_clearance else [[145, 233], [65, 303], [170, 333]]
surface = pygame.Surface((400, 200))
surface.set_alpha(10)
surface.fill((128, 128, 128))
screen.blit(surface, (100, 200))
texts = [font.render(msg, True, cfg.WHITE),
font.render('Press ENTER to continue or play again.', True, cfg.WHITE),
font.render('Press ESCAPE to quit.', True, cfg.WHITE)]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if is_clearance:
if not flag:
return
else:
main(initialize())
else:
main(initialize())
elif event.key == pygame.K_ESCAPE:
sys.exit()
pygame.quit()
for idx, (text, position) in enumerate(zip(texts, positions)):
screen.blit(text, position)
pygame.display.flip()
clock.tick(10)
''' initialization '''
def initialize():
pygame.init()
icon_image = pygame.image.load(cfg.ICONPATH)
pygame.display.set_icon(icon_image)
screen = pygame.display.set_mode([606, 606])
pygame.display.set_caption(' Eat beans games ')
return screen
''' The main function '''
def main(screen):
pygame.mixer.init()
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
pygame.font.init()
font_small = pygame.font.Font(cfg.FONTPATH, 18)
font_big = pygame.font.Font(cfg.FONTPATH, 24)
for num_level in range(1, Levels.NUMLEVELS+1):
level = getattr(Levels, f'Level{num_level}')()
is_clearance = startLevelGame(level, screen, font_small)
if num_level == Levels.NUMLEVELS:
showText(screen, font_big, is_clearance, True)
else:
showText(screen, font_big, is_clearance)
'''run'''
if __name__ == '__main__':
main(initialize())2) Effect display

5、 ... and 、 Xiaoxiaole
1) Code display
import os
import sys
import cfg
import pygame
from modules import *
''' The main program of the game '''
def main():
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(' Happy and happy ')
# Load background music
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)
# Loading sound effects
sounds = {}
sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))
sounds['match'] = []
for i in range(6):
sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))
# Load Fonts
font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)
# Image loading
gem_imgs = []
for i in range(1, 8):
gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))
# Main circulation
game = gemGame(screen, sounds, font, gem_imgs, cfg)
while True:
score = game.start()
flag = False
# After a round of the game, players choose to play again or exit
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == pygame.KEYUP and event.key == pygame.K_r:
flag = True
if flag:
break
screen.fill((135, 206, 235))
text0 = 'Final score: %s' % score
text1 = 'Press <R> to restart the game.'
text2 = 'Press <Esc> to quit the game.'
y = 150
for idx, text in enumerate([text0, text1, text2]):
text_render = font.render(text, 1, (85, 65, 0))
rect = text_render.get_rect()
if idx == 0:
rect.left, rect.top = (212, y)
elif idx == 1:
rect.left, rect.top = (122.5, y)
else:
rect.left, rect.top = (126.5, y)
y += 100
screen.blit(text_render, rect)
pygame.display.update()
game.reset()
'''run'''
if __name__ == '__main__':
main()2) Effect display

summary
An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~
If you read a lot of articles, you will continue to share all kinds of game source code ~
Follow Xiaobian for more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need to package the complete source code + Free sharing of materials ~ Just call me !

边栏推荐
- 苹果CMS采集站源码-搭建教程-附带源码-全新源码-开发文档
- LabVIEW在波形图或波形图表上显示时间和日期
- csdn每日一练——有序表的折半查找
- Kubernetes 基本介绍及核心组件
- Shell Sort
- Flowable process deployment
- 【Pygame小游戏】激荡大脑思维,一起来玩转奇思妙想“24点”叭~(超赞滴)
- LabVIEW用VISA Read函数来读取USB中断数据
- 自制APP连接OneNET---实现数据监控和下发控制(MQTT)
- Self made app connected to onenet --- realize data monitoring and distribution control (mqtt)
猜你喜欢

curl导入postman报错小记

Difference between oscilloscope and spectrum analyzer

vtk. VTP download in JS

Create millisecond time id in LabVIEW

示波器和频谱分析仪的区别

LabVIEW and VDM extract color and generate gray image

LabVIEW error "memory full - Application stopped on node"

【Pygame小游戏】趣味益智游戏 :打地鼠,看一下能打多少只呢?(附源码)

B 树的简单认识

Fiddler simulates low-speed network environment
随机推荐
LabVIEW programming specification
Flowable process deployment
Six procurement challenges perplexing Enterprises
SystemVerilog (x) - user defined type
细数十大信息安全原则
【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)
LabVIEW displays the time and date on the waveform chart or waveform chart
Merge sort
MySQL学习之子查询
C# Tryparse的用法
LabVIEW 禁止其他可多核心处理的应用程序在所有核心上执行
Usage of C tryparse
How to generate automatic references (simple drawings)
判等问题:如何确定程序的判断是正确的?
Fiddler creates an autoresponder
Multipartfile rename upload
【Pygame小游戏】《坦克大战》,那些童年的游戏你还记得几个呢?
【 pygame Games 】 don't find, Leisure Games Theme come 丨 Bubble Dragon applet - - Leisure Games Development recommendation
How to measure the refresh rate of oscilloscope
Exception 0xc00000005 code occurred when LabVIEW called DLL
