主函数:输入宽高和雷的数量

# main.py
import sysimport pygame as pg
import pygame.font
# import game# import Button
pg.init()
screen = pg.display.set_mode((640, 480))
COLOR_INACTIVE = pg.Color('lightskyblue3')
COLOR_ACTIVE = pg.Color('dodgerblue2')
FONT = pg.font.Font(None, 32)
font = pygame.font.Font('resources/a.TTF', 30)
set_up = dict()class Attribute:def __init__(self):global set_upself._BLOCK_WIDTH = set_up[0]self._BLOCK_HEIGHT = set_up[1]self._MINe_COUNT = set_up[2]def get_Width(self):return self._BLOCK_WIDTHdef set_Width(self, w):self._BLOCK_WIDTH = wBLOCK_WIDTH = property(fget=get_Width, fset=set_Width)  # 修饰类中属性get,setdef get_Height(self):return self._BLOCK_HEIGHTdef set_Height(self, h):self._BLOCK_HEIGHT = hBLOCK_HEIGHT = property(fget=get_Height, fset=set_Height)def get_MINe_COUNT(self):return self._MINe_COUNTdef set_MINe_COUNT(self, m):self._MINe_COUNT = mMINe_COUNT = property(fget=get_MINe_COUNT, fset=set_MINe_COUNT)  # 修饰类中属性get,setclass Button:def __init__(self, x, y, w, h):self.rect = pg.Rect(x, y, w, h)self.color = COLOR_INACTIVEself.text = "START"self.text_surface = FONT.render(self.text, True, self.color)self.active = Falsedef handle_event(self, event, BOX1, BOX2, BOX3):if event.type == pg.MOUSEBUTTONDOWN:# 用户选择盒子时if self.rect.collidepoint(event.pos):# 将盒子的状态改为选中self.active = not self.activeelse:self.active = False# 改变盒子颜色self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVEif event.type == pg.MOUSEBUTTONUP:if self.active == True:set_up[BOX1.id] = int(BOX1.text)set_up[BOX2.id] = int(BOX2.text)set_up[BOX3.id] = int(BOX3.text)return True# import game# game.start_play()def draw(self, screen):# Blit the text.screen.blit(self.text_surface, (self.rect.x + 10, self.rect.y + 10))# Blit the rect.pg.draw.rect(screen, self.color, self.rect, 2)class InputBox:def __init__(self, x, y, w, h, id, F_text, text='20'):self.rect = pg.Rect(x, y, w, h)self.color = COLOR_INACTIVEself.text = textself.id = idself._F_text = FONT.render(F_text, True, self.color)self.txt_surface = FONT.render(text, True, self.color)self.active = Falsedef handle_event(self, event):if event.type == pg.MOUSEBUTTONDOWN:# 用户选择盒子时if self.rect.collidepoint(event.pos):# 将盒子的状态改为选中self.active = not self.activeelse:self.active = False# 改变盒子颜色self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVEif event.type == pg.KEYDOWN:if self.active:if event.key == pg.K_RETURN:  # 回车set_up[self.id] = self.textelif event.key == pg.K_BACKSPACE:  # 删除self.text = self.text[:-1]else:self.text += event.unicode# Re-render the text.self.txt_surface = FONT.render(self.text, True, self.color)def update(self):# 文本框可加长.width = max(200, self.txt_surface.get_width() + 10)self.rect.w = widthdef draw(self, screen):# Blit the text.screen.blit(self.txt_surface, (self.rect.x + 5, self.rect.y + 5))screen.blit(self._F_text, (self.rect.x - 90, self.rect.y - 5))# Blit the rect.pg.draw.rect(screen, self.color, self.rect, 2)def main():clock = pg.time.Clock()input_box1 = InputBox(200, 100, 140, 32, 0, "Widht")input_box2 = InputBox(200, 200, 140, 32, 1, "Height")input_box3 = InputBox(200, 300, 140, 32, 2, "Count")input_boxes = [input_box1, input_box2, input_box3]button = Button(250, 400, 90, 40)while True:for event in pg.event.get():if event.type == pg.QUIT:sys.exit()for box in input_boxes:box.handle_event(event)if button.handle_event(event, input_box1, input_box2, input_box3):passfor box in input_boxes:box.update()screen.fill((30, 30, 30))for box in input_boxes:box.draw(screen)button.draw(screen)pg.display.flip()clock.tick(30)if __name__ == '__main__':main()pg.quit()

设置砖块和游戏逻辑

# mineblock.pyimport random
from enum import Enum
import main
#print(At.BLOCK_WIDTH,At.BLOCK_HEIGHT,At.MINe_COUNT)a = main.Attribute()
BLOCK_WIDTH =a.BLOCK_WIDTH  # 屏幕宽
BLOCK_HEIGHT = a.BLOCK_HEIGHT  # 屏幕高
SIZE = 20  # 块大小
MINE_COUNT =a.MINe_COUNT  # 地雷数class BlockStatus(Enum):  # 砖块状态标记normal = 1  # 未点击opened = 2  # 已点击mine = 3  # 地雷flag = 4  # 标记为地雷ask = 5  # 标记为问号bomb = 6  # 踩中地雷hint = 7  # 被双击的周围double = 8  # 正被鼠标左右键双击class Mine:def __init__(self, x, y, value=0):  # 对必要数据进行封装self._x = xself._y = yself._value = 0self._around_mine_count = -1self._status = BlockStatus.normal  # 初始化砖块状态_未点击self.set_value(value)def __repr__(self):return str(self._value)  # 显示分数# return f'({self._x},{self._y})={self._value}, status={self.status}'def get_x(self):return self._xdef set_x(self, x):self._x = xx = property(fget=get_x, fset=set_x)  # 修饰类中属性get,setdef get_y(self):return self._ydef set_y(self, y):self._y = yy = property(fget=get_y, fset=set_y)def get_value(self):return self._valuedef set_value(self, value):if value:self._value = 1else:self._value = 0value = property(fget=get_value, fset=set_value, doc='0:非地雷 1:雷')def get_around_mine_count(self):return self._around_mine_countdef set_around_mine_count(self, around_mine_count):  # 获取周围地雷数量self._around_mine_count = around_mine_countaround_mine_count = property(fget=get_around_mine_count, fset=set_around_mine_count, doc='四周地雷数量')def get_status(self):  # 获取砖块状态return self._statusdef set_status(self, value):  # 写入砖块状态self._status = valuestatus = property(fget=get_status, fset=set_status, doc='BlockStatus')class MineBlock:def __init__(self):self._block = [[Mine(i, j) for i in range(BLOCK_WIDTH)] for j in range(BLOCK_HEIGHT)]# 通过二维数组,对所有地图块及进行初始化,但注意,二维数组的宽和高与游戏界面的宽高是相反的# 埋雷for i in random.sample(range(BLOCK_WIDTH * BLOCK_HEIGHT), MINE_COUNT):  # 随机生成地雷坐标self._block[i // BLOCK_WIDTH][i % BLOCK_WIDTH].value = 1  # 将地雷坐标转化为x,y坐标 , 并触发value.setterdef get_block(self):  # 获取砖块情况return self._blockblock = property(fget=get_block)def getmine(self, x, y):return self._block[y][x]def open_mine(self, x, y):# 踩到雷了if self._block[y][x].value:  # 如果value为1 则证明踩到地雷了self._block[y][x].status = BlockStatus.bomb  # 砖块状态改为踩雷return False# 先把状态改为 openedself._block[y][x].status = BlockStatus.opened  # 未踩到雷around = _get_around(x, y)  # 获取周围砖块的坐标_sum = 0for i, j in around:  # 例遍坐标,查看有几颗雷if self._block[j][i].value:_sum += 1self._block[y][x].around_mine_count = _sum  # 将雷数写入# 如果周围没有雷,那么将周围8个未中未点开的递归算一遍# 这就能实现一点出现一大片打开的效果了if _sum == 0:for i, j in around:if self._block[j][i].around_mine_count == -1:self.open_mine(i, j)return Truedef double_mouse_button_down(self, x, y):if self._block[y][x].around_mine_count == 0:return Trueself._block[y][x].status = BlockStatus.doublearound = _get_around(x, y)sumflag = 0  # 周围被标记的雷数量for i, j in _get_around(x, y):if self._block[j][i].status == BlockStatus.flag:sumflag += 1# 周边的雷已经全部被标记result = Trueif sumflag == self._block[y][x].around_mine_count:for i, j in around:if self._block[j][i].status == BlockStatus.normal:if not self.open_mine(i, j):result = Falseelse:for i, j in around:if self._block[j][i].status == BlockStatus.normal:self._block[j][i].status = BlockStatus.hintreturn resultdef double_mouse_button_up(self, x, y):self._block[y][x].status = BlockStatus.openedfor i, j in _get_around(x, y):if self._block[j][i].status == BlockStatus.hint:self._block[j][i].status = BlockStatus.normaldef _get_around(x, y):"""返回(x, y)周围的点的坐标"""# 这里注意,range 末尾是开区间,所以要加 1return [(i, j) for i in range(max(0, x - 1), min(BLOCK_WIDTH - 1, x + 1) + 1)for j in range(max(0, y - 1), min(BLOCK_HEIGHT - 1, y + 1) + 1) if i != x or j != y]

游戏界面显示

# game.py
import sys
import time
from enum import Enum
import pygame
from pygame.locals import *
from mineblock import *
import main"""游戏主体,显示界面和操作逻辑"""print(2)
# 游戏屏幕的宽
SCREEN_WIDTH =BLOCK_WIDTH * SIZE
# 游戏屏幕的高
SCREEN_HEIGHT = (BLOCK_HEIGHT + 2) * SIZEclass GameStatus(Enum):  # 游戏情况readied = 1,started = 2,over = 3,win = 4def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):imgText = font.render(text, True, fcolor)  # 字体颜色screen.blit(imgText, (x, y))def start_play():pygame.init()  # 初始化screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))  # 游戏屏幕初始化pygame.display.set_caption('扫雷')  # 屏幕标题font1 = pygame.font.Font('resources/a.TTF', SIZE * 2)  # 得分的字体fwidth, fheight = font1.size('999')red = (200, 40, 40)# 加载资源图片,因为资源文件大小不一,所以做了统一的缩放处理,统一为bmp格式img0 = pygame.image.load('resources/0.bmp').convert()img0 = pygame.transform.smoothscale(img0, (SIZE, SIZE))  # 对图片尺寸进行统一缩放img1 = pygame.image.load('resources/1.bmp').convert()img1 = pygame.transform.smoothscale(img1, (SIZE, SIZE))img2 = pygame.image.load('resources/2.bmp').convert()img2 = pygame.transform.smoothscale(img2, (SIZE, SIZE))img3 = pygame.image.load('resources/3.bmp').convert()img3 = pygame.transform.smoothscale(img3, (SIZE, SIZE))img4 = pygame.image.load('resources/4.bmp').convert()img4 = pygame.transform.smoothscale(img4, (SIZE, SIZE))img5 = pygame.image.load('resources/5.bmp').convert()img5 = pygame.transform.smoothscale(img5, (SIZE, SIZE))img6 = pygame.image.load('resources/6.bmp').convert()img6 = pygame.transform.smoothscale(img6, (SIZE, SIZE))img7 = pygame.image.load('resources/7.bmp').convert()img7 = pygame.transform.smoothscale(img7, (SIZE, SIZE))img8 = pygame.image.load('resources/8.bmp').convert()img8 = pygame.transform.smoothscale(img8, (SIZE, SIZE))img_blank = pygame.image.load('resources/blank.bmp').convert()  # 砖块img_blank = pygame.transform.smoothscale(img_blank, (SIZE, SIZE))img_flag = pygame.image.load('resources/flag.bmp').convert()  # 旗子img_flag = pygame.transform.smoothscale(img_flag, (SIZE, SIZE))img_ask = pygame.image.load('resources/ask.bmp').convert()  # 问号img_ask = pygame.transform.smoothscale(img_ask, (SIZE, SIZE))img_mine = pygame.image.load('resources/mine.bmp').convert()  # 正确雷img_mine = pygame.transform.smoothscale(img_mine, (SIZE, SIZE))img_blood = pygame.image.load('resources/blood.bmp').convert()  # 爆炸雷img_blood = pygame.transform.smoothscale(img_blood, (SIZE, SIZE))img_error = pygame.image.load('resources/error.bmp').convert()  # 错误雷img_error = pygame.transform.smoothscale(img_error, (SIZE, SIZE))face_size = int(SIZE * 1.25)  # 表情大小img_face_fail = pygame.image.load('resources/face_fail.bmp').convert()  # 失败img_face_fail = pygame.transform.smoothscale(img_face_fail, (face_size, face_size))img_face_normal = pygame.image.load('resources/face_normal.bmp').convert()  # 普通img_face_normal = pygame.transform.smoothscale(img_face_normal, (face_size, face_size))img_face_success = pygame.image.load('resources/face_success.bmp').convert()  # 成功img_face_success = pygame.transform.smoothscale(img_face_success, (face_size, face_size))face_pos_x = (SCREEN_WIDTH - face_size) // 2face_pos_y = (SIZE * 2 - face_size) // 2img_dict = {  # 建立图片字典0: img0,1: img1,2: img2,3: img3,4: img4,5: img5,6: img6,7: img7,8: img8}bgcolor = (225, 225, 225)  # 背景色block = MineBlock()  # 砖块实体game_status = GameStatus.readied  # 初始游戏状态start_time = None  # 开始时间elapsed_time = 0  # 耗时while True:  # 无条件循环# 填充背景色screen.fill(bgcolor)for event in pygame.event.get():  # 获取所有事件 如:鼠标、键盘if event.type == QUIT:  # 用户按下窗口关闭按钮sys.exit()  # 程序退出elif event.type == MOUSEBUTTONDOWN:  # 鼠标点击事件mouse_x, mouse_y = event.pos  # 相对与窗口左上角,取得鼠标的x,y值x = mouse_x // SIZEy = mouse_y // SIZE - 2  # 这里减2是因为上面我们用2 SIZE作为计数版b1, b2, b3 = pygame.mouse.get_pressed()  # 监控鼠标动作,左键,滚轮,右键 点击为Trueif game_status == GameStatus.started:# 鼠标左右键同时按下,如果已经标记了所有雷,则打开周围一圈# 如果还未标记完所有雷,则有一个周围一圈被同时按下的效果if b1 and b3:mine = block.getmine(x, y)if mine.status == BlockStatus.opened:if not block.double_mouse_button_down(x, y):game_status = GameStatus.overelif event.type == MOUSEBUTTONUP:  # 鼠标释放if y < 0:if face_pos_x <= mouse_x <= face_pos_x + face_size and face_pos_y <= mouse_y <= face_pos_y + face_size:game_status = GameStatus.readiedblock = MineBlock()  # 砖块实体start_time = time.time()elapsed_time = 0continueif game_status == GameStatus.readied:game_status = GameStatus.startedstart_time = time.time()elapsed_time = 0if game_status == GameStatus.started:mine = block.getmine(x, y)if b1 and not b3:  # 按鼠标左键,翻开if mine.status == BlockStatus.normal:  # 未点击if not block.open_mine(x, y):  # 踩雷game_status = GameStatus.overelif not b1 and b3:  # 按鼠标右键, 标记if mine.status == BlockStatus.normal:  # 三种状态循环mine.status = BlockStatus.flagelif mine.status == BlockStatus.flag:mine.status = BlockStatus.askelif mine.status == BlockStatus.ask:mine.status = BlockStatus.normalelif b1 and b3:if mine.status == BlockStatus.double:block.double_mouse_button_up(x, y)flag_count = 0opened_count = 0for row in block.block:  # 展示图片for mine in row:  # 地雷pos = (mine.x * SIZE, (mine.y + 2) * SIZE)  # 将砖块的坐标转化为游戏窗口的实际坐标if mine.status == BlockStatus.opened:screen.blit(img_dict[mine.around_mine_count], pos)  # 展示周围地雷数量的图片opened_count += 1elif mine.status == BlockStatus.double:screen.blit(img_dict[mine.around_mine_count], pos)elif mine.status == BlockStatus.bomb:  # 踩雷screen.blit(img_blood, pos)elif mine.status == BlockStatus.flag:  # 标记screen.blit(img_flag, pos)flag_count += 1elif mine.status == BlockStatus.ask:  # 疑问screen.blit(img_ask, pos)elif mine.status == BlockStatus.hint:  # 被双击的周围screen.blit(img0, pos)elif game_status == GameStatus.over and mine.value:screen.blit(img_mine, pos)elif mine.value == 0 and mine.status == BlockStatus.flag:screen.blit(img_error, pos)elif mine.status == BlockStatus.normal:screen.blit(img_blank, pos)print_text(screen, font1, 30, (SIZE * 2 - fheight) // 2 - 2, '%02d' % (MINE_COUNT - flag_count), red)  # 计分板if game_status == GameStatus.started:elapsed_time = int(time.time() - start_time)print_text(screen, font1, SCREEN_WIDTH - fwidth - 30, (SIZE * 2 - fheight) // 2 - 2, '%03d' % elapsed_time, red)  # 计时器# if flag_count + opened_count == BLOCK_WIDTH * BLOCK_HEIGHT:if BLOCK_WIDTH*BLOCK_HEIGHT - opened_count == MINE_COUNT:game_status = GameStatus.winif game_status == GameStatus.over:screen.blit(img_face_fail, (face_pos_x, face_pos_y))elif game_status == GameStatus.win:screen.blit(img_face_success, (face_pos_x, face_pos_y))else:screen.blit(img_face_normal, (face_pos_x, face_pos_y))pygame.display.update()# if __name__ == '__main__':
#     main()

图片


















python大作业——扫雷游戏相关推荐

  1. pygame飞机大战小游戏(python大作业)

    一.项目背景 python大作业,在查看了老师给的链接发现教学视频不完整,所以借用了同学的<Python编程 从入门到实践>中的一个项目,学习模仿. 二.游戏具体介绍 这是一款由辉辉亲自打 ...

  2. Python大作业-网络爬虫程序

    简介 此程序是本人大三时期的Python大作业,初学Python后所编写的一个程序,是一个网络爬虫程序,可爬取指定网站的信息. 本程序爬取的网站是Bangumi-我看过的动画,Bangumi是一个专注 ...

  3. Python008: Python大作业之移动的小火车动画(一)

    Python大作业 1. 要求 使用Python语言,使用的库不限 如下图1的火车轨道 如下图2的火车(2节车厢) 小火车可以在轨道上动态的运行 小火车的大小可调.轨道的大小可调 2. 用到的第三方库 ...

  4. python扫雷的代码及原理_基于Python实现的扫雷游戏实例代码

    摘要:这篇Python开发技术栏目下的"基于Python实现的扫雷游戏实例代码",介绍的技术点是"Python实现.Python.实例代码.扫雷游戏.扫雷.游戏" ...

  5. HTML5期末大作业:游戏网页网站设计——CCG-游戏网页介绍(6页)高质量 HTML+CSS+JavaScript

    HTML5期末大作业:游戏网页网站设计--CCG-游戏网页介绍(6页)高质量 HTML+CSS+JavaScript 常见网页设计作业题材有 个人. 美食. 公司. 学校. 旅游. 电商. 宠物. 电 ...

  6. _【超详细指北】python大作业!

    [超详细指北]python大作业! ​ 这是笔者最近写python大作业时写的一个实现过程笔记,也就是基本上可以说是本人从0开始上手的一个python练习.程序和本文档从 4.29-5.15日 总共历 ...

  7. kaggle经典题--“泰坦尼克号”--0.8275准确率--东北大学20级python大作业开源(附详细解法与全部代码以及实验报告)

    kaggle经典题--"泰坦尼克号"--0.8275准确率--东北大学20级python大作业开源(附详细解法与全部代码以及实验报告) 前言 开发环境 一.导入包: 二.实验数据的 ...

  8. Python011: Python大作业之移动的小火车动画(四)代码实现

    书接上文:Python010: Python大作业之移动的小火车动画(三)结果显示 0.注意: ​ 该项目使用的库和资源说明如下: pygame 2.0.1 (SDL 2.0.14, Python 3 ...

  9. HTML5期末大作业:游戏网站——网络游戏官网(悦世界) 6个页面 HTML+CSS+JavaScript ~ ~ 学生HTML个人网页作业作品下载...

    HTML5期末大作业:游戏网站--网络游戏官网(悦世界) 6个页面 HTML+CSS+JavaScript ~ ~ 学生HTML个人网页作业作品下载 临近期末, 你还在为HTML网页设计结课作业,老师 ...

最新文章

  1. iOS开发基础-九宫格坐标(4)
  2. poj 2515 差分序列,排列组合
  3. html中如何设置图片填充颜色渐变,实现SVG图标的渐变填充效果
  4. 2019 年度十大 AI 安防热点事件丨年终盘点
  5. bzoj 2865 字符串识别——后缀数组
  6. excel 计算复合增长率
  7. 教育技术与c语言程序设计,2018年华东师范大学885教育技术与C程序设计考研复习资料...
  8. 为什么所有APP都想获取你的定位?
  9. 杏子语录(2020年12月)
  10. 【分享】女生教你怎么追MM--送给没有女朋友的来此灌水的GG们
  11. 层次分析法——确定指标权重、解决评价类问题
  12. 班主任有趣高效的班级惩罚制度
  13. blob导出文件及文件损坏处理
  14. 华为防火墙故障处理工具之查看路由表
  15. NotBlank问题解决
  16. scrapy学习(完全版)
  17. 20181103 Nginx(布尔教育)
  18. 爱尔威火星车 AirWheel 电动独轮车
  19. 人脸识别系统包括图像摄取、人脸定位、图像预处理、以及人脸识别
  20. 《记忆力心理学》5个方法 让你过目不忘

热门文章

  1. 精英反向学习与二次插值改进的黏菌优化算法ISMA(学习笔记_13)
  2. 南瑞通讯管理机测试软件,国电南瑞NSC2200E 通讯管理机
  3. 每日一问|数据仓库面试题这些你都会吗?
  4. Flash的事件机制
  5. Develop as One | 2021 Google 开发者大会主旨演讲精彩回顾
  6. python import文件pyd_Python生成pyd文件
  7. 如何利用快播雷达搜索全国范围内共享的视频
  8. POJ1015陪审团(Jury Compromise)——dp+路径记录
  9. 抖音真的很难运营吗?》
  10. wireshark 下载