使用 python 的单人AI 扫雷游戏

使用 python 的单人AI 扫雷游戏,第1张

扫雷是一款单人益智游戏,相信大部分人都在以前上微机课的时候玩过。


游戏的目标是借助每个区域中相邻地雷数量的线索,清除包含隐藏的“地雷”或炸d的单元格,但不引爆其中任何一个,全部清除后即可获胜。


今天我们用 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()

小结:

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/567708.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存