关注小编,私信小编领取哟!
当然别忘了一件三连哟~~
公众号:Python日志
可以关注小编公众号,会不定时的发布一下Python小技巧,还有很多资源可以免费领取哟!!
源码领取:加Python学习交流群:773162165 可以领取哟
Python版本:3.7.8
相关模块:
pygame模块;
random模块;
pyttsx3模块;
以及一些python自带的模块。
安装Python并添加到环境变量,pip安装需要的相关模块即可。
# print(dir()) # 已导入的包
pygame.init() # 初始化
pygame.mixer.init()
pygame.display.set_caption('开心消消乐 公众号:Python日志 学习解答加群:773162165 ')
tree = manager.ManagerTree()
m = manager.Manager(0, 0)
sound_sign = 0
world_bgm = pygame.mixer.Sound(manager.SoundPlay.world_bgm)
game_bgm = pygame.mixer.Sound(manager.SoundPlay.game_bgm)
while True:
if m.level == 0:
if sound_sign == 0:
game_bgm.stop()
world_bgm.play(-1)
sound_sign = 1
else:
if sound_sign == 1:
world_bgm.stop()
game_bgm.play(-1)
sound_sign = 0
if m.level == 0:
tree.draw_tree(m.energy_num, m.money)
else:
m.set_level_mode(m.level)
sprite_group = m.draw()
if m.type == 0:
m.eliminate_animal()
m.death_map()
m.exchange(sprite_group)
m.judge_level()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
exit()
if event.type == QUIT:
sys.exit()
m.level, m.energy_num, m.money = tree.mouse_select(event, m.level, m.energy_num, m.money)
m.mouse_select(event)
m.mouse_image()
pygame.display.flip()
if __name__ == "main":
main()
import os
import cfg
import pygame
from modules import *
'''主函数'''
def main(cfg):
# 游戏初始化
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
pygame.display.set_caption(cfg.TITLE)
# 加载游戏素材
sounds = {}
for key, value in cfg.AUDIO_PATHS.items():
sounds[key] = pygame.mixer.Sound(value)
sounds[key].set_volume(1)
# 开始界面
is_dual_mode = gameStartInterface(screen, cfg)
# 关卡数
levelfilepaths = [os.path.join(cfg.LEVELFILEDIR, filename) for filename in sorted(os.listdir(cfg.LEVELFILEDIR))]
# 主循环
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:
break
部分代码展示
'''游戏主程序'''
def main(cfg):
# 初始化
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('Q版泡泡堂 公众号:Python 学习交流群: 773162165')
# 开始界面
Interface(screen, cfg, mode='game_start')
# 游戏主循环
font = pygame.font.SysFont('Consolas', 15)
for gamemap_path in cfg.GAMEMAPPATHS:
# -地图
map_parser = mapParser(gamemap_path, bg_paths=cfg.BACKGROUNDPATHS, wall_paths=cfg.WALLPATHS, blocksize=cfg.BLOCKSIZE)
# -水果
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))
# -我方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')
# -电脑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_sprite_group = pygame.sprite.Group()
# -用于判断游戏胜利或者失败的flag
is_win_flag = False
# -主循环
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)
# --↑↓←→键控制上下左右, 空格键丢炸弹
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)
# --电脑Hero随机行动
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))
# --吃到水果加生命值(只要是Hero, 都能加)
ourhero.eatFruit(fruit_sprite_group)
for hero in aihero_sprite_group:
hero.eatFruit(fruit_sprite_group)
# --游戏元素都绑定到屏幕上
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:
# --爆炸火焰范围内的Hero生命值将持续下降
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)
# --左上角显示生命值
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])
# --我方玩家生命值小于等于0/电脑方玩家生命值均小于等于0则判断游戏结束
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')
'''游戏主程序'''
def main(cfg):
# 初始化
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('愤怒的小鸟 公众号:Python日志 问题解答学习交流群:773162165 ')
# 开始游戏
def startgame():
game_levels = GameLevels(cfg, screen)
game_levels.start()
# 退出游戏
def quitgame():
pygame.quit()
sys.exit()
# 开始界面
components = pygame.sprite.Group()
title_label = Label(screen, 700, 100, 400, 200)
title_label.addtext('ANGRY BIRDS', 80, cfg.FONTPATH['arfmoochikncheez'], (236, 240, 241))
components.add(title_label)
start_btn = Button(screen, 500, 400, 300, 100, startgame, (244, 208, 63), (247, 220, 111))
start_btn.addtext('START GAME', 60, cfg.FONTPATH['arfmoochikncheez'], cfg.BACKGROUND_COLOR)
components.add(start_btn)
quit_btn = Button(screen, 1000, 400, 300, 100, quitgame, (241, 148, 138), (245, 183, 177))
quit_btn.addtext('QUIT', 60, cfg.FONTPATH['arfmoochikncheez'], cfg.BACKGROUND_COLOR)
components.add(quit_btn)
charles_label = Label(screen, cfg.SCREENSIZE[0] - 300, cfg.SCREENSIZE[1] - 80, 300, 100)
charles_label.addtext('CHARLES', 60, cfg.FONTPATH['arfmoochikncheez'], (41, 41, 41))
components.add(charles_label)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitgame()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
quitgame()
elif event.type == pygame.MOUSEBUTTONDOWN:
if start_btn.selected():
start_btn.action()
elif quit_btn.selected():
quit_btn.action()
screen.fill(cfg.BACKGROUND_COLOR)
for component in components: component.draw()
pygame.display.update()
clock.tick(cfg.FPS)
'''run'''
if __name__ == '__main__':
main(cfg)
'''主函数'''
def main():
# 初始化
pygame.init()
clock = pygame.time.Clock()
# 加载图片
game_img_used = pygame.image.load(GetImagePath(cfg.PICTURE_ROOT_DIR))
game_img_used = pygame.transform.scale(game_img_used, cfg.SCREENSIZE)
game_img_used_rect = game_img_used.get_rect()
# 设置窗口
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('拼图游戏 公众号:Python日志 学习交流群:773162165')
# 游戏开始界面
size = ShowStartInterface(screen, game_img_used_rect.width, game_img_used_rect.height)
assert isinstance(size, int)
num_rows, num_cols = size, size
num_cells = size * size
# 计算Cell大小
cell_width = game_img_used_rect.width // num_cols
cell_height = game_img_used_rect.height // num_rows
# 避免初始化为原图
while True:
game_board, blank_cell_idx = CreateBoard(num_rows, num_cols, num_cells)
if not isGameOver(game_board, size):
break
# 游戏主循环
is_running = True
while is_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_LEFT or event.key == ord('a'):
blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)
elif event.key == pygame.K_RIGHT or event.key == ord('d'):
blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)
elif event.key == pygame.K_UP or event.key == ord('w'):
blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)
elif event.key == pygame.K_DOWN or event.key == ord('s'):
blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)
# ----鼠标操作
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = pygame.mouse.get_pos()
x_pos = x // cell_width
y_pos = y // cell_height
idx = x_pos + y_pos * num_cols
if idx == blank_cell_idx-1:
blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)
elif idx == blank_cell_idx+1:
blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)
elif idx == blank_cell_idx+num_cols:
blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)
elif idx == blank_cell_idx-num_cols:
blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)
# --判断游戏是否结束
if isGameOver(game_board, size):
game_board[blank_cell_idx] = num_cells - 1
is_running = False
# --更新屏幕
screen.fill(cfg.BACKGROUNDCOLOR)
for i in range(num_cells):
if game_board[i] == -1:
continue
x_pos = i // num_cols
y_pos = i % num_cols
rect = pygame.Rect(y_pos*cell_width, x_pos*cell_height, cell_width, cell_height)
img_area = pygame.Rect((game_board[i]%num_cols)*cell_width, (game_board[i]//num_cols)*cell_height, cell_width, cell_height)
screen.blit(game_img_used, rect, img_area)
for i in range(num_cols+1):
pygame.draw.line(screen, cfg.BLACK, (i*cell_width, 0), (i*cell_width, game_img_used_rect.height))
for i in range(num_rows+1):
pygame.draw.line(screen, cfg.BLACK, (0, i*cell_height), (game_img_used_rect.width, i*cell_height))
pygame.display.update()
clock.tick(cfg.FPS)
# 游戏结束界面
ShowEndInterface(screen, game_img_used_rect.width, game_img_used_rect.height)
好啦今天的文章就到此结束啦
源码领取可以看相关文件哟!!!