兄弟们,爬行动物爬得太多了,对健康不好,还要考虑劳逸结合,偶尔换换口味。
[En]
Brothers, reptiles crawl too much, it is not good for health, but also consider the combination of work and rest, occasionally for a change.
今天来感受一下用python来开发一款益智游戏,来吃够!
; 准备一下
软件环境,咱们还是用python和pycharm即可。
模块的话,没有安装的安装一下 cfg 和 pygame 模块。
win+r 打开运行框输入 cmd 按回车弹出命令提示符窗口,输入pip install 模块名,如 pip install pygame 然后按回车即可安装成功。
这一步我真的写了太多次了,但我怕零基础的老人不会每次都写。
[En]
I have really written this step too many times, but I am afraid that the old man with zero foundation will not write it every time.
代码展示
然后咱们直接来吧展示
模块导入
import cfg
import pygame
from modules.misc import *
from modules.mazes import *
from modules.Sprites import *
Python学习交流群:815624229
主函数
初始化
pygame.init()
pygame.mixer.init()
pygame.font.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('迷宫益智小游戏')
font = pygame.font.SysFont('Consolas', 15)
开始界面
Interface(screen, cfg, 'game_start')
记录关卡数
num_levels = 0
记录最少用了多少步通关
best_scores = 'None'
关卡循环切换
while True:
num_levels += 1
clock = pygame.time.Clock()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
随机生成关卡地图
maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)
生成hero
hero_now = Hero(cfg.HEROPICPATH, [0, 0], cfg.BLOCKSIZE, cfg.BORDERSIZE)
统计步数
num_steps = 0
关卡内主循环
while True:
dt = clock.tick(cfg.FPS)
screen.fill((255, 255, 255))
is_move = False
↑↓←→控制hero
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:
is_move = hero_now.move('up', maze_now)
elif event.key == pygame.K_DOWN:
is_move = hero_now.move('down', maze_now)
elif event.key == pygame.K_LEFT:
is_move = hero_now.move('left', maze_now)
elif event.key == pygame.K_RIGHT:
is_move = hero_now.move('right', maze_now)
num_steps += int(is_move)
hero_now.draw(screen)
maze_now.draw(screen)
显示一些信息
showText(screen, font, 'LEVELDONE: %d' % num_levels, (255, 0, 0), (10, 10))
showText(screen, font, 'BESTSCORE: %s' % best_scores, (255, 0, 0), (210, 10))
showText(screen, font, 'USEDSTEPS: %s' % num_steps, (255, 0, 0), (410, 10))
showText(screen, font, 'S: your starting point D: your destination', (255, 0, 0), (10, 600))
判断游戏是否胜利
if (hero_now.coordinate[0] == cfg.MAZESIZE[1] - 1) and (hero_now.coordinate[1] == cfg.MAZESIZE[0] - 1):
break
pygame.display.update()
更新最优成绩
if best_scores == 'None':
best_scores = num_steps
else:
if best_scores > num_steps:
best_scores = num_steps
关卡切换
Interface(screen, cfg, mode='game_switch')
run
if __name__ == '__main__':
main(cfg)
效果展示
只需截屏即可。我不会录制这段视频的。
[En]
Just take a screenshot. I won’t record the video.
然后这个游戏的话,需要一些素材文件,大家在导入模块那部分可以领到
记得点赞收藏哈
Original: https://www.cnblogs.com/hahaa/p/16027040.html
Author: 轻松学Python
Title: 用python开发一个益智游戏,没事就锻炼锻炼自己的方向感
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/509798/
转载文章受原作者版权保护。转载请注明原作者出处!