如何使用python中的随机数生成器将AI添加到Tic Tac Toe游戏中?
这是我参加在线Python课程的第一个程序之一。我已经拼凑了一些代码来完成大部分工作,但我仍然很难让我的电脑播放器移动到使用随机数库并将它们读到黑板上。我尝试将如何使用python中的随机数生成器将AI添加到Tic Tac Toe游戏中?,python,tic-tac-toe,Python,Tic Tac Toe,这是我参加在线Python课程的第一个程序之一。我已经拼凑了一些代码来完成大部分工作,但我仍然很难让我的电脑播放器移动到使用随机数库并将它们读到黑板上。我尝试将DrawMove()中的代码直接移动到主代码中,但没有成功。目前我已经设置好了它,这样两个玩家可以互相比赛,但我想在“X”玩家中添加randrange,这样玩家就可以与电脑比赛了 import itertools from random import randrange board = [[1,2,3], [4,'X'
DrawMove()
中的代码直接移动到主代码中,但没有成功。目前我已经设置好了它,这样两个玩家可以互相比赛,但我想在“X”玩家中添加randrange
,这样玩家就可以与电脑比赛了
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
<>这可能更适合于一个地方开始考虑你的<代码>板>代码>变量作为“游戏状态”。 与其让AI选择任何行/列,不如只选择尚未占用的行/列 所以你可以把你的棋盘看作是一个初始值,最终填满了不可玩的空格,而不是“随机数”,你可以把它看作是从这个选择池中随机抽取的。想想“从一副牌中抽牌”而不是“告诉我一个随机数” 我认为这比随机选择一个有效的职位更有效率 例如,在一个简单的1行版本的tic-tac-toe中:
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]
每次while play循环运行时,您都会重置电路板我不清楚这个问题。你的具体编程问题是什么?这是一个很好的评论,但它并没有回答OP的问题。我把它记下来是因为OP立即使用了随机值,因为他们在那之后直接重置了电路板,这可能会被视为不起作用