用python开发一个益智游戏,没事就锻炼锻炼自己的方向感

x33g5p2x  于2022-03-19 转载在 Python  
字(2.1k)|赞(0)|评价(0)|浏览(534)

兄弟们,爬虫爬多了,对身体不好,也要考虑劳逸结合,偶尔换换口味。

今天来感受一下用python来开发一款益智游戏,来吃够!

准备一下

软件环境,咱们还是用python和pycharm即可。
没有或者不会安装的小伙伴,直接扫一下文章左边的码

模块的话,没有安装的安装一下 cfg 和 pygame 模块。

win+r 打开运行框输入 cmd 按回车弹出命令提示符窗口,输入pip install 模块名,如 pip install pygame 然后按回车即可安装成功。

这一步我真的写了太多次了,就是怕有零基础的老铁不会,每次都写,害。

代码展示

然后咱们直接来吧展示

模块导入

  1. import cfg
  2. import pygame
  3. from modules.misc import *
  4. from modules.mazes import *
  5. from modules.Sprites import *

主函数

初始化

  1. pygame.init()
  2. pygame.mixer.init()
  3. pygame.font.init()
  4. pygame.mixer.music.load(cfg.BGMPATH)
  5. pygame.mixer.music.play(-1, 0.0)
  6. screen = pygame.display.set_mode(cfg.SCREENSIZE)
  7. pygame.display.set_caption('迷宫益智小游戏')
  8. font = pygame.font.SysFont('Consolas', 15)

开始界面

  1. Interface(screen, cfg, 'game_start')

记录关卡数

  1. num_levels = 0

记录最少用了多少步通关

  1. best_scores = 'None'

关卡循环切换

  1. while True:
  2. num_levels += 1
  3. clock = pygame.time.Clock()
  4. screen = pygame.display.set_mode(cfg.SCREENSIZE)

随机生成关卡地图

  1. maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)

生成hero

  1. hero_now = Hero(cfg.HEROPICPATH, [0, 0], cfg.BLOCKSIZE, cfg.BORDERSIZE)

统计步数

  1. num_steps = 0

关卡内主循环

  1. while True:
  2. dt = clock.tick(cfg.FPS)
  3. screen.fill((255, 255, 255))
  4. is_move = False

↑↓←→控制hero

  1. for event in pygame.event.get():
  2. if event.type == pygame.QUIT:
  3. pygame.quit()
  4. sys.exit(-1)
  5. elif event.type == pygame.KEYDOWN:
  6. if event.key == pygame.K_UP:
  7. is_move = hero_now.move('up', maze_now)
  8. elif event.key == pygame.K_DOWN:
  9. is_move = hero_now.move('down', maze_now)
  10. elif event.key == pygame.K_LEFT:
  11. is_move = hero_now.move('left', maze_now)
  12. elif event.key == pygame.K_RIGHT:
  13. is_move = hero_now.move('right', maze_now)
  14. num_steps += int(is_move)
  15. hero_now.draw(screen)
  16. maze_now.draw(screen)

显示一些信息

  1. showText(screen, font, 'LEVELDONE: %d' % num_levels, (255, 0, 0), (10, 10))
  2. showText(screen, font, 'BESTSCORE: %s' % best_scores, (255, 0, 0), (210, 10))
  3. showText(screen, font, 'USEDSTEPS: %s' % num_steps, (255, 0, 0), (410, 10))
  4. showText(screen, font, 'S: your starting point D: your destination', (255, 0, 0), (10, 600))

判断游戏是否胜利

  1. if (hero_now.coordinate[0] == cfg.MAZESIZE[1] - 1) and (hero_now.coordinate[1] == cfg.MAZESIZE[0] - 1):
  2. break
  3. pygame.display.update()

更新最优成绩

  1. if best_scores == 'None':
  2. best_scores = num_steps
  3. else:
  4. if best_scores > num_steps:
  5. best_scores = num_steps

关卡切换

  1. Interface(screen, cfg, mode='game_switch')

run

  1. if __name__ == '__main__':
  2. main(cfg)

效果展示

截个图算了,视频我就不录了
然后这个游戏的话,需要一些素材文件,大家可以点下方的扫码,或者最上面左侧扫码领取就好了

记得点赞收藏哈

相关文章