欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用 python 实现单人AI 扫雷游戏

程序员文章站 2022-03-09 10:46:18
ai玩扫雷很高兴又见面了!????扫雷是一款单人益智游戏,相信大部分人都在以前上微机课的时候玩过。游戏的目标是借助每个区域中相邻地雷数量的线索,清除包含隐藏的“地雷”或炸弹的单元格,但不引爆...

ai玩扫雷

很高兴又见面了!????

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

看看我们将要实现的最终样子。????

使用 python 实现单人AI 扫雷游戏

运行扫雷

1.确保安装了python 3.6+。
2.安装pygame。
3.克隆这个存储库:

github地址:https://github.com/wanghao221/minesweeper

设置 minesweeper.py ⚓

扫雷游戏表示

class minesweeper():

def __init__(self, height=8, width=8, mines=8):
    
    # 设置初始宽度、高度和地雷数量    
    self.height = height
    self.width = width
    self.mines = set()

    # 初始化一个没有地雷的空字段    
    self.board = []    
    for i in range(self.height):
        row = []        
        for j in range(self.width):
            row.append(false)
        self.board.append(row)

    # 随机添加地雷    
    while len(self.mines) != mines:        
        i = random.randrange(height)
        j = random.randrange(width)        
        if not self.board[i][j]:
            self.mines.add((i, j))
            self.board[i][j] = true

    # 最开始,玩家没有发现地雷    
    self.mines_found = set()

输出地雷所在位置的基于文本的表示

def print(self):
for i in range(self.height):
        print("--" * self.width + "-")
        
        for j in range(self.width):
            
            if self.board[i][j]:
                print("|x", end="")
            
            else:
                print("| ", end="")
        print("|")
    
    print("--" * self.width + "-")


def is_mine(self, cell):
    i, j = cell
    return self.board[i][j]

def nearby_mines(self, cell):

返回给定单元格的一行和一列内的地雷数,不包括单元格本身。

def nearby_mines(self, cell):

        # 保持附近地雷的数量
        count = 0

        # 遍历一行和一列内的所有单元格
        for i in range(cell[0] - 1, cell[0] + 2):
            for j in range(cell[1] - 1, cell[1] + 2):

                # 忽略单元格本身
                if (i, j) == cell:
                    continue

                # 如果单元格在边界内并且是地雷,则更新计数
                if 0 <= i < self.height and 0 <= j < self.width:
                    if self.board[i][j]:
                        count += 1
        return count

检查是否已标记所有地雷。

def won(self):
        return self.mines_found == self.mines

关于扫雷游戏的逻辑语句
一个句子由一组棋盘单元和这些单元格的数量组成。

class sentence():
    def __init__(self, cells, count):
        self.cells = set(cells)
        self.count = count

    def __eq__(self, other):
        return self.cells == other.cells and self.count == other.count

    def __str__(self):
        return f"{self.cells} = {self.count}"

    def known_mines(self):

返回 self.cells 中已知为地雷的所有单元格的集合。

def known_mines(self):	
	if len(self.cells) == self.count:
		return self.cells

返回 self.cells 中已知安全的所有单元格的集合。

def known_safes(self):      
	if self.count == 0:
		return self.cells

鉴于已知单元格是地雷,更新内部知识表示。

def mark_mine(self, cell):       
	if cell in self.cells:
		self.cells.discard(cell)
		self.count -= 1

鉴于已知单元格是安全的,更新内部知识表示。

def mark_safe(self, cell):  
        if cell in self.cells:
            self.cells.discard(cell)

扫雷游戏玩家

class minesweeperai():
    def __init__(self, height=8, width=8):
        # 设置初始高度和宽度        
        self.height = height
        self.width = width
        # 跟踪点击了哪些单元格
        self.moves_made = set()
        # 跟踪已知安全或地雷的细胞        
        self.mines = set()
        self.safes = set()
        # 关于已知为真游戏的句子列表
        self.knowledge = []

将一个单元格标记为地雷,并更新所有知识以将该单元格也标记为地雷。

def mark_mine(self, cell):
       self.mines.add(cell)
       
       for sentence in self.knowledge:
           sentence.mark_mine(cell)

将一个单元格标记为安全,并更新所有知识以将该单元格也标记为安全。

def mark_safe(self, cell):  
    self.safes.add(cell)        
        for sentence in self.knowledge:
            sentence.mark_safe(cell)

用于获取所有附近的单元格

def nearby_cells(self, cell):
	cells = set()
	
	        for i in range(cell[0] - 1, cell[0] + 2):
	            for j in range(cell[1] - 1, cell[1] + 2):
	
	                if (i, j) == cell:
	                    continue
	
	                if 0 <= i < self.height and 0 <= j < self.width:
	                    cells.add((i, j))
	
	        return cells

当扫雷板告诉我们,对于给定的安全单元,有多少相邻单元中有地雷时调用。
这个功能应该:
1)将单元格标记为已进行的移动
2)将单元格标记为安全
3)根据 cellcount 的值在 ai 的知识库中添加一个新句子
4)如果可以根据 ai 的知识库得出结论,则将任何其他单元格标记为安全或地雷
5) 如果可以从现有知识中推断出任何新句子,则将其添加到 ai 的知识库中

def add_knowledge(self, cell, count): 
        self.moves_made.add(cell)

        # 标记单元格安全

        if cell not in self.safes:    
            self.mark_safe(cell)
                    
        # 获取所有附近的单元格

        nearby = self.nearby_cells(cell)       
        nearby -= self.safes | self.moves_made     
        new_sentence = sentence(nearby, count)
        self.knowledge.append(new_sentence)

        new_safes = set()
        new_mines = set()

        for sentence in self.knowledge:
            
            if len(sentence.cells) == 0:
                self.knowledge.remove(sentence)           
            else:
                tmp_new_safes = sentence.known_safes()
                tmp_new_mines = sentence.known_mines()                
                if type(tmp_new_safes) is set:
                    new_safes |= tmp_new_safes
                
                if type(tmp_new_mines) is set:
                    new_mines |= tmp_new_mines        
        for safe in new_safes:
            self.mark_safe(safe)        
        for mine in new_mines:
            self.mark_mine(mine)
        prev_sentence = new_sentence
        new_inferences = []
        for sentence in self.knowledge:
            if len(sentence.cells) == 0:
                self.knowledge.remove(sentence)
            elif prev_sentence == sentence:
                break
            elif prev_sentence.cells <= sentence.cells:
                inf_cells = sentence.cells - prev_sentence.cells
                inf_count = sentence.count - prev_sentence.count
                new_inferences.append(sentence(inf_cells, inf_count))
            prev_sentence = sentence
        self.knowledge += new_inferences
    def make_safe_move(self):

返回一个安全的单元格以在扫雷板上选择。必须知道该移动是安全的,而不是已经做出的移动。
该函数可以使用 self.mines、self.safes 和 self.moves_made 中的知识,但不应修改任何这些值。

def make_safe_move(self): 
	safe_moves = self.safes.copy()
	safe_moves -= self.moves_made
	if len(safe_moves) == 0:
	return none
	return safe_moves.pop()
	def make_random_move(self):

返回在扫雷板上进行的移动。应该在以下单元格中随机选择:
1) 尚未被选中
2) 不知道是地雷

def make_random_move(self):
	if len(self.moves_made) == 56:
	    return none
	
	random_move = random.randrange(self.height), random.randrange(self.height)
	
	not_safe_moves = self.moves_made | self.mines
	
	while random_move in not_safe_moves:
	    random_move = random.randrange(self.height), random.randrange(self.height)
	
	return random_move

使用 python 实现单人AI 扫雷游戏

设置 runner.py 运行程序

颜色

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)

字体

字体可以在自己电脑中c:\windows\fonts的位置选择自己喜欢的复制到项目中 assets/fonts目录下即可,我用的是楷体

使用 python 实现单人AI 扫雷游戏

open_sans = "assets/fonts/simkai.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)

添加图片
这里我们只用了两张图,一个是地雷,一个是用来标记地雷的旗帜

使用 python 实现单人AI 扫雷游戏使用 python 实现单人AI 扫雷游戏

flag = pygame.image.load("assets/images/flag.png")
flag = pygame.transform.scale(flag, (cell_size, cell_size))
mine = pygame.image.load("assets/images/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

最初显示游戏说明

使用 python 实现单人AI 扫雷游戏

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("海拥 | 扫雷", true, white)
        titlerect = title.get_rect()
        titlerect.center = ((width / 2), 50)
        screen.blit(title, titlerect)

        # rules
        rules = [
            "单击一个单元格以显示它",
            "右键单击一个单元格以将其标记为地雷",
            "成功标记所有地雷以获胜!"
        ]
        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("开始游戏", 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 移动", 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("重置", true, black)
    buttonrect = buttontext.get_rect()
    buttonrect.center = resetbutton.center
    pygame.draw.rect(screen, white, resetbutton)
    screen.blit(buttontext, buttonrect)

显示文字

text = "失败" if lost else "获胜" 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 实现单人ai 扫雷游戏的文章就介绍到这了,更多相关python扫雷游戏内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!