当前位置:网站首页>[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 !

边栏推荐
- LeetCode 501 :二叉搜索樹中的眾數
- LabVIEW用VISA Read函数来读取USB中断数据
- 都说验证码是爬虫中的一道坎,看我只用五行代码就突破它。
- File转为MultipartFile的方法
- 【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)
- 30 | how to reset the consumer group displacement?
- 【Pygame合集】回忆杀-“童年游戏”,看看你中几枪?(附五款源码自取)
- 2022 college entrance examination quantitative paper | please answer the questions for quantitative candidates
- 怎么生成自动参考文献(简单 有图)
- Insert sort
猜你喜欢

Analysis of Genesis public chain

LabVIEW change the shape or color of point ROI overlay

【Pygame小游戏】“史上最炫酷贪吃蛇”驾到,FUN开玩(不好玩不要钱)

Difference between oscilloscope and spectrum analyzer

Ilruntime hotfix framework installation and breakpoint debugging

【AI出牌器】第一次见这么“刺激”的斗地主,胜率高的关键因素竟是......

LabVIEW obtains the information of all points found by the clamp function

【自动回复小脚本】新年快乐,每一个字都是我亲自手打的,不是转发哦~

【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)

LabVIEW uses the visa read function to read USB interrupt data
随机推荐
How to measure the refresh rate of oscilloscope
【Pygame小游戏】Chrome上的小恐龙竟可以用代码玩儿了?它看起来很好玩儿的样子~
VS的常用设置
自制APP连接OneNET---实现数据监控和下发控制(MQTT)
LabVIEW图片在从16位强制转换为8位后看起来要亮或暗
上海网上开户是安全的吗?
Hyperleger fabric installation
黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
Kubernetes 基本介绍及核心组件
How to handle the database query error with Emoji expression in Typecho- Xingze V Club
30 | 怎么重设消费者组位移?
csdn每日一练——找出最接近元素并输出下标
csdn每日一练——有序表的折半查找
LabVIEW performs a serial loopback test
LabVIEW编程规范
The serial port in the visa test panel under LabVIEW or max does not work
30 | how to reset the consumer group displacement?
【Pygame合集】滴~穿越童年游戏指南 请查收:这里面有你玩过的游戏嘛?(附五款源码自取)
LabVIEW 禁止其他可多核心处理的应用程序在所有核心上执行
【自动回复小脚本】新年快乐,每一个字都是我亲自手打的,不是转发哦~
