佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > 使用 python 實(shí)現(xiàn)單人AI 掃雷游戲

使用 python 實(shí)現(xiàn)單人AI 掃雷游戲

熱門標(biāo)簽:智能手機(jī) 美圖手機(jī) 網(wǎng)站文章發(fā)布 銀行業(yè)務(wù) 鐵路電話系統(tǒng) 檢查注冊(cè)表項(xiàng) 服務(wù)器配置 呼叫中心市場(chǎng)需求

AI玩掃雷

很高興又見(jiàn)面了!😊

掃雷是一款單人益智游戲,相信大部分人都在以前上微機(jī)課的時(shí)候玩過(guò)。游戲的目標(biāo)是借助每個(gè)區(qū)域中相鄰地雷數(shù)量的線索,清除包含隱藏的“地雷”或炸彈的單元格,但不引爆其中任何一個(gè),全部清除后即可獲勝。今天我們用 Python 完成這個(gè)小程序,并且用AI來(lái)學(xué)習(xí)并實(shí)現(xiàn)它。

看看我們將要實(shí)現(xiàn)的最終樣子。👇

運(yùn)行掃雷

1.確保安裝了Python 3.6+。
2.安裝Pygame。
3.克隆這個(gè)存儲(chǔ)庫(kù):

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

設(shè)置 minesweeper.py ⚓

掃雷游戲表示

class Minesweeper():

def __init__(self, height=8, width=8, mines=8):
    
    # 設(shè)置初始寬度、高度和地雷數(shù)量    
    self.height = height
    self.width = width
    self.mines = set()

    # 初始化一個(gè)沒(méi)有地雷的空字段    
    self.board = []    
    for i in range(self.height):
        row = []        
        for j in range(self.width):
            row.append(False)
        self.board.append(row)

    # 隨機(jī)添加地雷    
    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

    # 最開(kāi)始,玩家沒(méi)有發(fā)現(xiàn)地雷    
    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):

返回給定單元格的一行和一列內(nèi)的地雷數(shù),不包括單元格本身。

def nearby_mines(self, cell):

        # 保持附近地雷的數(shù)量
        count = 0

        # 遍歷一行和一列內(nèi)的所有單元格
        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

                # 如果單元格在邊界內(nèi)并且是地雷,則更新計(jì)數(shù)
                if 0 = i  self.height and 0 = j  self.width:
                    if self.board[i][j]:
                        count += 1
        return count

檢查是否已標(biāo)記所有地雷。

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

關(guān)于掃雷游戲的邏輯語(yǔ)句
一個(gè)句子由一組棋盤單元和這些單元格的數(shù)量組成。

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

鑒于已知單元格是地雷,更新內(nèi)部知識(shí)表示。

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

鑒于已知單元格是安全的,更新內(nèi)部知識(shí)表示。

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

掃雷游戲玩家

class MinesweeperAI():
    def __init__(self, height=8, width=8):
        # 設(shè)置初始高度和寬度        
        self.height = height
        self.width = width
        # 跟蹤點(diǎn)擊了哪些單元格
        self.moves_made = set()
        # 跟蹤已知安全或地雷的細(xì)胞        
        self.mines = set()
        self.safes = set()
        # 關(guān)于已知為真游戲的句子列表
        self.knowledge = []

將一個(gè)單元格標(biāo)記為地雷,并更新所有知識(shí)以將該單元格也標(biāo)記為地雷。

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

將一個(gè)單元格標(biāo)記為安全,并更新所有知識(shí)以將該單元格也標(biāo)記為安全。

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

當(dāng)掃雷板告訴我們,對(duì)于給定的安全單元,有多少相鄰單元中有地雷時(shí)調(diào)用。
這個(gè)功能應(yīng)該:
1)將單元格標(biāo)記為已進(jìn)行的移動(dòng)
2)將單元格標(biāo)記為安全
3)根據(jù) cellcount 的值在 AI 的知識(shí)庫(kù)中添加一個(gè)新句子
4)如果可以根據(jù) AI 的知識(shí)庫(kù)得出結(jié)論,則將任何其他單元格標(biāo)記為安全或地雷
5) 如果可以從現(xiàn)有知識(shí)中推斷出任何新句子,則將其添加到 AI 的知識(shí)庫(kù)中

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

        # 標(biāo)記單元格安全

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

返回一個(gè)安全的單元格以在掃雷板上選擇。必須知道該移動(dòng)是安全的,而不是已經(jīng)做出的移動(dòng)。
該函數(shù)可以使用 self.mines、self.safes 和 self.moves_made 中的知識(shí),但不應(yīng)修改任何這些值。

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

返回在掃雷板上進(jìn)行的移動(dòng)。應(yīng)該在以下單元格中隨機(jī)選擇:
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

設(shè)置 runner.py 運(yùn)行程序

顏色

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

創(chuàng)建游戲

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

字體

字體可以在自己電腦中C:\Windows\Fonts的位置選擇自己喜歡的復(fù)制到項(xiàng)目中 assets/fonts目錄下即可,我用的是楷體

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)

計(jì)算面板尺寸

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)

添加圖片
這里我們只用了兩張圖,一個(gè)是地雷,一個(gè)是用來(lái)標(biāo)記地雷的旗幟

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

創(chuàng)建游戲和 AI 代理

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

跟蹤顯示的單元格、標(biāo)記的單元格以及是否被地雷擊中

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

最初顯示游戲說(shuō)明

instructions = True

while True:

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

    screen.fill(BLACK)

    # 顯示游戲說(shuō)明

    if instructions:

        # 標(biāo)題
        title = largeFont.render("海擁 | 掃雷", True, WHITE)
        titleRect = title.get_rect()
        titleRect.center = ((width / 2), 50)
        screen.blit(title, titleRect)

        # Rules
        rules = [
            "單擊一個(gè)單元格以顯示它",
            "右鍵單擊一個(gè)單元格以將其標(biāo)記為地雷",
            "成功標(biāo)記所有地雷以獲勝!"
        ]
        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)

        # 開(kāi)始游戲按鈕
        
        buttonRect = pygame.Rect((width / 4), (3 / 4) * height, width / 2, 50)
        buttonText = mediumFont.render("開(kāi)始游戲", True, BLACK)
        buttonTextRect = buttonText.get_rect()
        buttonTextRect.center = buttonRect.center
        pygame.draw.rect(screen, WHITE, buttonRect)
        screen.blit(buttonText, buttonTextRect)

        # 檢查是否點(diǎn)擊播放按鈕
        
        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

畫(huà)板

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)

        # 如果需要,添加地雷、旗幟或數(shù)字
        
        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 移動(dòng)按鈕

aiButton = pygame.Rect(
    (2 / 3) * width + BOARD_PADDING, (1 / 3) * height - 50,
    (width / 3) - BOARD_PADDING * 2, 50
)
buttonText = mediumFont.render("AI 移動(dòng)", 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()

檢查右鍵單擊以切換標(biāo)記

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 按鈕,則進(jìn)行 AI 移動(dòng)

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)

重置游戲狀態(tài)

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

用戶自定義動(dòng)作

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)

行動(dòng)起來(lái),更新AI知識(shí)

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

以上就是本篇文章的全部?jī)?nèi)容

這里放了項(xiàng)目的完整源碼:http://xiazai.jb51.net/202108/yuanma/haiyong_minesweeper_jb51.rar

到此這篇關(guān)于使用 python 實(shí)現(xiàn)單人AI 掃雷游戲的文章就介紹到這了,更多相關(guān)python掃雷游戲內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python用tkinter開(kāi)發(fā)的掃雷游戲
  • python實(shí)現(xiàn)掃雷游戲的示例
  • python實(shí)現(xiàn)掃雷小游戲
  • python實(shí)現(xiàn)掃雷游戲
  • 用python寫掃雷游戲?qū)嵗a分享
  • 基于Python實(shí)現(xiàn)的掃雷游戲?qū)嵗a

標(biāo)簽:河南 長(zhǎng)治 滄州 紅河 上海 新疆 樂(lè)山 沈陽(yáng)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用 python 實(shí)現(xiàn)單人AI 掃雷游戲》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    普定县| 锡林浩特市| 黎城县| 丰都县| 遵义县| 赤水市| 苍梧县| 上犹县| 札达县| 揭东县| 东海县| 商南县| 济宁市| 壶关县| 鞍山市| 韶关市| 雅江县| 永靖县| 探索| 四子王旗| 青川县| 福贡县| 高碑店市| 呼玛县| 临沂市| 双峰县| 乌兰察布市| 临猗县| 加查县| 陆川县| 吉木乃县| 连平县| 泉州市| 灵武市| 威海市| 镇雄县| 泽州县| 丰顺县| 孟连| 牡丹江市| 保靖县|