前言
今天给大家分享是扫雷小游戏,废话不多说,让我们愉快地开始吧~
效果展示
开发工具
Python版本: 3.6.4
相关模块:
pygame模块;
以及一些python自带的模块。
环境搭建
安装Python并添加到环境变量,pip安装需要的相关模块即可。
原理简介
这这里我简单介绍一下游戏的实现思路。
相信大家对扫雷这款windows自带的经典小游戏都不陌生,它的游戏规则很简单:
游戏界面左上角的数字代表所有方格中埋有雷的数目,右上角是一个计时器。你要做的就是根据提示找出方格中所有的雷。
那么提示是啥呢?就是游戏刚开始的时候你需要随便点一个方格,就像这样:
上面的数字代表以该数字为中心的九宫格内埋有的雷的数目。所以如果你人品不好,一开始就点到雷的话,这局游戏就直接结束了。
ok,了解了游戏规则之后,我们就可以开始写代码了。首先还是先初始化一下游戏:
# 游戏初始化
pygame.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('mine sweeper —— ilove-python')
复制代码
然后把需要用到的字体,图片,音乐啥的都导入进来:
# 导入所有图片
images = {}
for key, value in cfg.IMAGE_PATHS.items():
if key in ['face_fail', 'face_normal', 'face_success']:
image = pygame.image.load(value)
images[key] = pygame.transform.smoothscale(image, (int(cfg.GRIDSIZE*1.25), int(cfg.GRIDSIZE*1.25)))
else:
image = pygame.image.load(value).convert()
images[key] = pygame.transform.smoothscale(image, (cfg.GRIDSIZE, cfg.GRIDSIZE))
# 载入字体
font = pygame.font.Font(cfg.FONT_PATH, cfg.FONT_SIZE)
# 导入并播放背景音乐
pygame.mixer.music.load(cfg.BGM_PATH)
pygame.mixer.music.play(-1)
复制代码
接着,我们来定义一个文字板,用于显示左上角的埋雷数量和右上角的游戏已进行时间:
'''文字板'''
class TextBoard(pygame.sprite.Sprite):
def __init__(self, text, font, position, color, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.text = text
self.font = font
self.position = position
self.color = color
def draw(self, screen):
text_render = self.font.render(self.text, True, self.color)
screen.blit(text_render, self.position)
def update(self, text):
self.text = text
复制代码
其实很简单,只需要把用字体渲染之后的文本对象绑定到屏幕上就行,然后设置一个update函数,来实时更新里面的文本内容。
然后,我们再定义一个表情按钮类:
'''表情按钮'''
class EmojiButton(pygame.sprite.Sprite):
def __init__(self, images, position, status_code=0, **kwargs):
pygame.sprite.Sprite.__init__(self)
# 导入图片
self.images = images
self.image = self.images['face_normal']
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
# 表情按钮的当前状态
self.status_code = status_code
'''画到屏幕上'''
def draw(self, screen):
# 状态码为0, 代表正常的表情
if self.status_code == 0:
self.image = self.images['face_normal']
# 状态码为1, 代表失败的表情
elif self.status_code