IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 使用 python 的单人AI 扫雷游戏 -> 正文阅读

[Python知识库]使用 python 的单人AI 扫雷游戏

扫雷是一款单人益智游戏,相信大部分人都在以前上微机课的时候玩过。游戏的目标是借助每个区域中相邻地雷数量的线索,清除包含隐藏的“地雷”或炸弹的单元格,但不引爆其中任何一个,全部清除后即可获胜。今天我们用 Python 完成这个小程序,并且用AI来学习并实现它。

前期准备:
1.确保安装了Python 3.6+。
2.安装Pygame。
3.复制下面代码。
**请添加图片描述
**请添加图片描述

设置游戏元素

# 颜色

BLACK = (0, 0, 0)
GRAY = (180, 180, 180)
WHITE = (255, 255, 255)

# 创建游戏

pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)

# 字体


OPEN_SANS = r"C:\Users\XYSM\PycharmProjects\pythonProject7\Font.ttf"
smallFont = pygame.font.Font(OPEN_SANS, 20)
mediumFont = pygame.font.Font(OPEN_SANS, 28)
largeFont = pygame.font.Font(OPEN_SANS, 40)

# 计算面板尺寸

BOARD_PADDING = 20
board_width = ((2 / 3) * width) - (BOARD_PADDING * 2)
board_height = height - (BOARD_PADDING * 2)
cell_size = int(min(board_width / WIDTH, board_height / HEIGHT))
board_origin = (BOARD_PADDING, BOARD_PADDING)

# 添加图片

flag = pygame.image.load(r"C:\Users\XYSM\PycharmProjects\pythonProject7\flag.png")
flag = pygame.transform.scale(flag, (cell_size, cell_size))
mine = pygame.image.load(r"C:\Users\XYSM\PycharmProjects\pythonProject7\mine.png")
mine = pygame.transform.scale(mine, (cell_size, cell_size))

字体

字体可以在自己电脑中

C:\Windows\Fonts

的位置选择自己喜欢的复制到项目中 assets/fonts目录下即可
我这里用的字体展示在下图:
请添加图片描述
添加图片
这里我们只用了两张图,一个是地雷,一个是用来标记地雷的旗帜

创建游戏和 AI 代理

# 创建游戏和 AI 代理

game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES)
ai = MinesweeperAI(height=HEIGHT, width=WIDTH)

# 跟踪显示的单元格、标记的单元格以及是否被地雷击中

revealed = set()
flags = set()
lost = False

#设置 AI 移动按钮

 # AI 移动按钮

    aiButton = pygame.Rect(
        (2 / 3) * width + BOARD_PADDING, (1 / 3) * height - 50,
        (width / 3) - BOARD_PADDING * 2, 50
    )
    buttonText = mediumFont.render("AI Moving", True, BLACK)
    buttonRect = buttonText.get_rect()
    buttonRect.center = aiButton.center
    pygame.draw.rect(screen, WHITE, aiButton)
    screen.blit(buttonText, buttonRect)

    # 重置按钮

    resetButton = pygame.Rect(
        (2 / 3) * width + BOARD_PADDING, (1 / 3) * height + 20,
        (width / 3) - BOARD_PADDING * 2, 50
    )
    buttonText = mediumFont.render("Replay", True, BLACK)
    buttonRect = buttonText.get_rect()
    buttonRect.center = resetButton.center
    pygame.draw.rect(screen, WHITE, resetButton)
    screen.blit(buttonText, buttonRect)

全部代码:

import pygame
import sys
import time

from minesweeper import Minesweeper, MinesweeperAI

HEIGHT = 8
WIDTH = 8
MINES = 8

# 颜色

BLACK = (0, 0, 0)
GRAY = (180, 180, 180)
WHITE = (255, 255, 255)

# 创建游戏

pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode(size)

# 字体


OPEN_SANS = r"C:\Users\XYSM\PycharmProjects\pythonProject7\Font.ttf"
smallFont = pygame.font.Font(OPEN_SANS, 20)
mediumFont = pygame.font.Font(OPEN_SANS, 28)
largeFont = pygame.font.Font(OPEN_SANS, 40)

# 计算面板尺寸

BOARD_PADDING = 20
board_width = ((2 / 3) * width) - (BOARD_PADDING * 2)
board_height = height - (BOARD_PADDING * 2)
cell_size = int(min(board_width / WIDTH, board_height / HEIGHT))
board_origin = (BOARD_PADDING, BOARD_PADDING)

# 添加图片

flag = pygame.image.load(r"C:\Users\XYSM\PycharmProjects\pythonProject7\flag.png")
flag = pygame.transform.scale(flag, (cell_size, cell_size))
mine = pygame.image.load(r"C:\Users\XYSM\PycharmProjects\pythonProject7\mine.png")
mine = pygame.transform.scale(mine, (cell_size, cell_size))

# 创建游戏和 AI 代理

game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES)
ai = MinesweeperAI(height=HEIGHT, width=WIDTH)

# 跟踪显示的单元格、标记的单元格以及是否被地雷击中

revealed = set()
flags = set()
lost = False

# 最初显示说明

instructions = True

while True:

    # 检查游戏是否退出
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(BLACK)

    # 显示游戏说明

    if instructions:

        # 标题
        title = largeFont.render("By QQ Group:905229245", True, WHITE)
        titleRect = title.get_rect()
        titleRect.center = ((width / 2), 45)
        screen.blit(title, titleRect)

        # Rules
        rules = [
            "Click on a cell to display it",
            "Right-click a cell to mark it as a mine",
            "Successfully mark all mines to win!"
        ]
        for i, rule in enumerate(rules):
            line = smallFont.render(rule, True, WHITE)
            lineRect = line.get_rect()
            lineRect.center = ((width / 2), 150 + 30 * i)
            screen.blit(line, lineRect)

        # 开始游戏按钮

        buttonRect = pygame.Rect((width / 4), (3 / 4) * height, width / 2, 50)
        buttonText = mediumFont.render("Start", True, BLACK)
        buttonTextRect = buttonText.get_rect()
        buttonTextRect.center = buttonRect.center
        pygame.draw.rect(screen, WHITE, buttonRect)
        screen.blit(buttonText, buttonTextRect)

        # 检查是否点击播放按钮

        click, _, _ = pygame.mouse.get_pressed()
        if click == 1:
            mouse = pygame.mouse.get_pos()
            if buttonRect.collidepoint(mouse):
                instructions = False
                time.sleep(0.3)

        pygame.display.flip()
        continue

    # 画板

    cells = []
    for i in range(HEIGHT):
        row = []
        for j in range(WIDTH):

            # 为单元格绘制矩形

            rect = pygame.Rect(
                board_origin[0] + j * cell_size,
                board_origin[1] + i * cell_size,
                cell_size, cell_size
            )
            pygame.draw.rect(screen, GRAY, rect)
            pygame.draw.rect(screen, WHITE, rect, 3)

            # 如果需要,添加地雷、旗帜或数字

            if game.is_mine((i, j)) and lost:
                screen.blit(mine, rect)
            elif (i, j) in flags:
                screen.blit(flag, rect)
            elif (i, j) in revealed:
                neighbors = smallFont.render(
                    str(game.nearby_mines((i, j))),
                    True, BLACK
                )
                neighborsTextRect = neighbors.get_rect()
                neighborsTextRect.center = rect.center
                screen.blit(neighbors, neighborsTextRect)

            row.append(rect)
        cells.append(row)

    # AI 移动按钮

    aiButton = pygame.Rect(
        (2 / 3) * width + BOARD_PADDING, (1 / 3) * height - 50,
        (width / 3) - BOARD_PADDING * 2, 50
    )
    buttonText = mediumFont.render("AI Moving", True, BLACK)
    buttonRect = buttonText.get_rect()
    buttonRect.center = aiButton.center
    pygame.draw.rect(screen, WHITE, aiButton)
    screen.blit(buttonText, buttonRect)

    # 重置按钮

    resetButton = pygame.Rect(
        (2 / 3) * width + BOARD_PADDING, (1 / 3) * height + 20,
        (width / 3) - BOARD_PADDING * 2, 50
    )
    buttonText = mediumFont.render("Replay", True, BLACK)
    buttonRect = buttonText.get_rect()
    buttonRect.center = resetButton.center
    pygame.draw.rect(screen, WHITE, resetButton)
    screen.blit(buttonText, buttonRect)

    # 显示文字

    text = "You lose" if lost else "You win" if game.mines == flags else ""
    text = mediumFont.render(text, True, WHITE)
    textRect = text.get_rect()
    textRect.center = ((5 / 6) * width, (2 / 3) * height)
    screen.blit(text, textRect)

    move = None

    left, _, right = pygame.mouse.get_pressed()

    # 检查右键单击以切换标记

    if right == 1 and not lost:
        mouse = pygame.mouse.get_pos()

        for i in range(HEIGHT):

            for j in range(WIDTH):

                if cells[i][j].collidepoint(mouse) and (i, j) not in revealed:

                    if (i, j) in flags:
                        flags.remove((i, j))

                    else:
                        flags.add((i, j))
                    time.sleep(0.2)

    elif left == 1:
        mouse = pygame.mouse.get_pos()

        # 如果单击 AI 按钮,则进行 AI 移动

        if aiButton.collidepoint(mouse) and not lost:
            move = ai.make_safe_move()

            if move is None:
                move = ai.make_random_move()

                if move is None:
                    flags = ai.mines.copy()
                    print("No moves left to make.")

                else:
                    print("No known safe moves, AI making random move.")

            else:
                print("AI making safe move.")
            time.sleep(0.2)

        # 重置游戏状态

        elif resetButton.collidepoint(mouse):

            game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES)
            ai = MinesweeperAI(height=HEIGHT, width=WIDTH)
            revealed = set()
            flags = set()
            lost = False
            continue

        # 用户自定义动作

        elif not lost:

            for i in range(HEIGHT):

                for j in range(WIDTH):

                    if (cells[i][j].collidepoint(mouse)
                            and (i, j) not in flags
                            and (i, j) not in revealed):
                        move = (i, j)

    # 行动起来,更新AI知识

    if move:

        if game.is_mine(move):
            lost = True

        else:
            nearby = game.nearby_mines(move)
            revealed.add(move)
            ai.add_knowledge(move, nearby)

    pygame.display.flip()

小结:

如果有问题可以看评论区,里面有大神

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-04-09 18:19:02  更:2022-04-09 18:19:35 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 18:41:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码