栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python大作业——扫雷游戏

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python大作业——扫雷游戏

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

# main.py
import sys

import 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_up
        self._BLOCK_WIDTH = set_up[0]
        self._BLOCK_HEIGHT = set_up[1]
        self._MINe_COUNT = set_up[2]

    def get_Width(self):
        return self._BLOCK_WIDTH

    def set_Width(self, w):
        self._BLOCK_WIDTH = w

    BLOCK_WIDTH = property(fget=get_Width, fset=set_Width)  # 修饰类中属性get,set

    def get_Height(self):
        return self._BLOCK_HEIGHT

    def set_Height(self, h):
        self._BLOCK_HEIGHT = h

    BLOCK_HEIGHT = property(fget=get_Height, fset=set_Height)

    def get_MINe_COUNT(self):
        return self._MINe_COUNT

    def set_MINe_COUNT(self, m):
        self._MINe_COUNT = m

    MINe_COUNT = property(fget=get_MINe_COUNT, fset=set_MINe_COUNT)  # 修饰类中属性get,set





class Button:
    def __init__(self, x, y, w, h):
        self.rect = pg.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = "START"
        self.text_surface = FONT.render(self.text, True, self.color)
        self.active = False

    def handle_event(self, event, BOX1, BOX2, BOX3):

        if event.type == pg.MOUSEBUTTONDOWN:
            # 用户选择盒子时
            if self.rect.collidepoint(event.pos):
                # 将盒子的状态改为选中
                self.active = not self.active
            else:
                self.active = False
            # 改变盒子颜色
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if 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_INACTIVE
        self.text = text
        self.id = id
        self._F_text = FONT.render(F_text, True, self.color)
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            # 用户选择盒子时
            if self.rect.collidepoint(event.pos):
                # 将盒子的状态改为选中
                self.active = not self.active
            else:
                self.active = False
            # 改变盒子颜色
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pg.KEYDOWN:
            if self.active:
                if event.key == pg.K_RETURN:  # 回车
                    set_up[self.id] = self.text
                elif 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 = width

    def 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):
                pass


        for 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.py

import 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 = x
        self._y = y
        self._value = 0
        self._around_mine_count = -1
        self._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._x

    def set_x(self, x):
        self._x = x

    x = property(fget=get_x, fset=set_x)  # 修饰类中属性get,set

    def get_y(self):
        return self._y

    def set_y(self, y):
        self._y = y

    y = property(fget=get_y, fset=set_y)

    def get_value(self):
        return self._value

    def set_value(self, value):
        if value:
            self._value = 1
        else:
            self._value = 0

    value = property(fget=get_value, fset=set_value, doc='0:非地雷 1:雷')

    def get_around_mine_count(self):
        return self._around_mine_count

    def set_around_mine_count(self, around_mine_count):  # 获取周围地雷数量
        self._around_mine_count = around_mine_count

    around_mine_count = property(fget=get_around_mine_count, fset=set_around_mine_count, doc='四周地雷数量')

    def get_status(self):  # 获取砖块状态
        return self._status

    def set_status(self, value):  # 写入砖块状态
        self._status = value

    status = 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.setter

    def get_block(self):  # 获取砖块情况
        return self._block

    block = 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

        # 先把状态改为 opened
        self._block[y][x].status = BlockStatus.opened  # 未踩到雷

        around = _get_around(x, y)  # 获取周围砖块的坐标

        _sum = 0
        for i, j in around:  # 例遍坐标,查看有几颗雷
            if self._block[j][i].value:
                _sum += 1
        self._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 True

    def double_mouse_button_down(self, x, y):
        if self._block[y][x].around_mine_count == 0:
            return True

        self._block[y][x].status = BlockStatus.double

        around = _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 = True
        if 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 = False
        else:
            for i, j in around:
                if self._block[j][i].status == BlockStatus.normal:
                    self._block[j][i].status = BlockStatus.hint
        return result

    def double_mouse_button_up(self, x, y):
        self._block[y][x].status = BlockStatus.opened
        for i, j in _get_around(x, y):
            if self._block[j][i].status == BlockStatus.hint:
                self._block[j][i].status = BlockStatus.normal


def _get_around(x, y):
    """返回(x, y)周围的点的坐标"""
    # 这里注意,range 末尾是开区间,所以要加 1
    return [(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) * SIZE


class GameStatus(Enum):  # 游戏情况
    readied = 1,
    started = 2,
    over = 3,
    win = 4


def 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) // 2
    face_pos_y = (SIZE * 2 - face_size) // 2

    img_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 // SIZE
                y = mouse_y // SIZE - 2  # 这里减2是因为上面我们用2 SIZE作为计数版
                b1, b2, b3 = pygame.mouse.get_pressed()  # 监控鼠标动作,左键,滚轮,右键 点击为True
                if 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.over
            elif 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.readied
                        block = MineBlock()  # 砖块实体
                        start_time = time.time()
                        elapsed_time = 0
                        continue

                if game_status == GameStatus.readied:
                    game_status = GameStatus.started
                    start_time = time.time()
                    elapsed_time = 0

                if 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.over
                    elif not b1 and b3:  # 按鼠标右键, 标记
                        if mine.status == BlockStatus.normal:  # 三种状态循环
                            mine.status = BlockStatus.flag
                        elif mine.status == BlockStatus.flag:
                            mine.status = BlockStatus.ask
                        elif mine.status == BlockStatus.ask:
                            mine.status = BlockStatus.normal
                    elif b1 and b3:
                        if mine.status == BlockStatus.double:
                            block.double_mouse_button_up(x, y)

        flag_count = 0
        opened_count = 0

        for 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 += 1
                elif 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 += 1
                elif 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.win

        if 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()

图片


















转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号