1 条评论
-
mrhowe SU @ 2024-6-1 20:14:19
# 确定导入的文件 import sys #导入系统控制库 import time,random #时间库和随机库 import pygame from pygame.locals import * # 初始化 # 扫雷游戏的尺寸变量 BLOCK_WIDTH = 20 # 棋盘的宽度方块个数 BLOCK_HEIGHT = 10 # 棋盘的高度方块个数 SIZE = 30 # 方块的长宽 MINE_COUNT = 40 # 雷的数量 # 游戏屏幕的宽 SCREEN_WIDTH = BLOCK_WIDTH * SIZE # 游戏屏幕的高 SCREEN_HEIGHT = (BLOCK_HEIGHT + 2) * SIZE # 这里的+2是信息区的高度 def load_img(file,size): img = pygame.image.load(file).convert() return pygame.transform.smoothscale(img,(size,size)) # 定义方块类 class Mine: def __init__(self, row, column, value=0): self.row = row # 我是第几行的格子 self.column = column # 我是第几列的格子 self.pos = (self.column * SIZE, (self.row + 2) * SIZE) # 通过第几行第几列计算格子的位置 self.value = value # 1:雷 0:安全 self.around_mine_count = -1 # 周围雷的数量 self.image = pygame.image.load('resources/normal.jpg').convert()# 导入图片 self.image = pygame.transform.smoothscale(self.image,(SIZE,SIZE)) # 把图片压缩成格子大小 # 定义雷区 class MineBlock: def __init__(self): # 生成方块棋盘组成列表,无地雷,每个方块是一个Mine实例() # 在 ipython 等终端中展示一下结果,有一个直观印象。 # 列表推导式的用法 self.blocks = [Mine(r, c) for r in range(BLOCK_HEIGHT)\ for c in range(BLOCK_WIDTH)] # 埋雷 # 在总方块里随机选MINE_COUNT个数,做雷。 mines = random.sample(range(BLOCK_WIDTH * BLOCK_HEIGHT), MINE_COUNT) for i in mines: self.blocks[i].value = 1 def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)): imgText = font.render(text, True, fcolor) screen.blit(imgText, (x, y)) def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('扫雷') bgcolor = (225, 225, 225) # 背景色 #生成棋盘实例 block = MineBlock() # 生成文字 font1 = pygame.font.Font('resources/msyh.ttf', SIZE * 2) # 得分的字体 fwidth, fheight = font1.size('999') # 具体的文本 999 的宽和高 red = (200, 40, 40) # 常规的游戏循环 while True: # 填充背景色 screen.fill(bgcolor) # 把个格子画在屏幕上 for mine in block.blocks: screen.blit(mine.image,mine.pos) # 导入图片 face_size = int(SIZE * 1.25) img_face_normal = load_img("resources/face_normal.bmp",face_size) img_face_fail = load_img("resources/face_fail.bmp",face_size) img_face_win = load_img("resources/face_win.bmp",face_size) face_pos_x = (SCREEN_WIDTH - face_size) // 2 face_pos_y = (SIZE * 2 - face_size) // 2 screen.blit(img_face_normal,(face_pos_x,face_pos_y)) # 显示剩余雷和所用时间 print_text(screen,font1,30,(SIZE * 2 - fheight)//2,"000",red) # 用时 print_text(screen,font1,SCREEN_WIDTH-fwidth,(SIZE * 2 - fheight)//2,"40",red) # 剩余雷 for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() if __name__ =='__main__': main()
- 1