首页 > 解决方案 > 如何使用 python 中的随机数生成器将 AI 添加到井字游戏?

问题描述

这是我正在参加的在线 Python 课程的第一个程序之一。我拼凑了一些完成大部分工作的代码,但我仍然无法让我的电脑播放器使用随机数库并将它们读到板上。我尝试将代码DrawMove()直接移动到主代码中,但没有成功。目前我已经将它设置为两个玩家可以互相对战,但我想添加randrange到“X”玩家,以便玩家可以与电脑对战。

import itertools
from random import randrange

board = [[1,2,3],
         [4,'X',6],
         [7,8,9]]
   
         
def InitialBoard(board):
    print("+-------+-------+-------+\n|       |       |       |\n|  ",board[0][0],"  |  ",board[0][1],"  |  ",board[0][2],"  |")
    print("|       |       |       |\n+-------+-------+-------+\n|       |       |       |")
    print("|  ",board[1][0],"  |  ",'X',"  |  ",board[1][2],"  |\n|       |       |       |\n+-------+-------+-------+")
    print("|       |       |       |\n|  ",board[2][0],"  |  ",board[2][1],"  |  ",board[2][2],"  |\n|       |       |       |")
    print("+-------+-------+-------+")
    
def DisplayBoard(gameMap, playerMove, row, column):

    try:
        if board[row][column] == 'X' or board[row][column] == 'O':
            print("This space is occupied by X, please try another one.")
            return False
        gameMap[row][column] = playerMove #add parameters to our function
        for row, column in enumerate(gameMap):
            print("+-------+-------+-------+\n|       |       |       |\n|  ",board[0][0],"  |  ",board[0][1],"  |  ",board[0][2],"  |")
            print("|       |       |       |\n+-------+-------+-------+\n|       |       |       |")
            print("|  ",board[1][0],"  |  ",'X',"  |  ",board[1][2],"  |\n|       |       |       |\n+-------+-------+-------+")
            print("|       |       |       |\n|  ",board[2][0],"  |  ",board[2][1],"  |  ",board[2][2],"  |\n|       |       |       |")
            print("+-------+-------+-------+")
        return gameMap
    except IndexError: #handles index error
        print("Out of range, please choose a number between 0-2.")
        return False
    except Exception as e: #handles general errors, prints description of type of error
        print(str(e))
        return False


def VictoryFor(current_game):
   #horizontal
    for row in board:
     
        column1 = row[0] #all the same on top row
        column2 = row[1]
        column3 = row[2]
        if column1 == column2 == column3:#checks if top row same
            print(f"Player {row[0]} is the winner!")#f string is used to pass variables inside of curly braces
        

#vertical
    if board[0][0] == board[1][0] == board[2][0]:
        print("Winner in first column!")
        for row in board:
            print(row[0])
    elif board[0][1] == board[1][1] == board[2][1]:
        print("Winner in second column!")
        for row in board:
            print(row[1])
    elif board[0][2] == board[1][2] == board[2][2]:
        print("Winner in third column!")
        for row in board:
            print(row[2])

#diagonal
    if board[0][0] == board[1][1] == board[2][2]:
        print("Diagonal Winner down!")
    if board[2][0] == board[1][1] == board[0][2]:
        print("Diagonal Winner up!")


def DrawMove(board):#computer move
           
    row_choice = int(randrange(2))
    columnn_choice = int(randrange(2))

#main
play = True 
players = ['X','O']#computer is X, player is O. Computer makes first move.
while play:
    board = [[1, 2, 3],
             [4,'X',6],
             [7, 8, 9]]
             
    game_won = False
    player_cycle = itertools.cycle(['X','O'])
    InitialBoard(board)
    while not game_won:
        current_player = 'O'#computer has made move in center of board, your turn now
        current_player = next(player_cycle)
        played = False
        while not played:
            print(f"Player: {current_player}")
            column_choice = int(input("Pick a column 0-2:"))
            row_choice = int(input("Pick a row 0-2:"))
            played = DisplayBoard(board, playerMove = current_player, row = row_choice, column = column_choice)
    if VictoryFor(board):
        game_won = True
        again = input("The game is over, play again? Type (y/n)")
        if again.lower() == "y":
            print("Restarting")
        elif again.lower() == "n":
            print("Goodbye")
            play = False
        else:
            play = False

标签: pythontic-tac-toe

解决方案


这可能更适合https://codereview.stackexchange.com/,但从一个地方开始将您的board变量视为“游戏状态”。

与其让 AI 选择任何行/列,不如只选择尚未被占用的行/列。

因此,您可以将您的棋盘视为初始值,最终会填满不可玩的空间,而不是“随机数”,您可以将其视为从这个选择池中随机“抽签”。想想“从一副纸牌中抽牌”而不是“告诉我一个随机数”。

我认为这比希望随机选择一个有效位置更有效。

例如,在一个简单的 tic-tac-toe 的 1 行版本中:

row1 = [1, 2, 3]
mask = [1, 1, 1] # initial state
# human places an X at position 2:
mask = update() # mask for row1 becomes [1, 0, 1]

# AI now can determine that position 2 is not a valid spot:
valid_spots = list(filter(bool, [i*j for i,j in zip(row1, mask)])) # [1,3]

# choose a valid spot from the available indexes
choice_index = random.randint(0, len(valid_spots)-1)
new_move = row1[choice_index]

推荐阅读