我被要求将我的玩家vs.玩家tic-tac-toe改进为一个AI tic-tac-toe,玩家可以在其中与电脑对抗: 为此,我需要编写两个函数: 获取当前玩家的棋盘和符号并返回所有可能的未来棋盘列表的棋盘-每个未来棋盘都是包含两个元素的列表:一个是放置符号的位置,另一个是放置符号后的棋盘-一圈后的棋盘(我正在使用一个嵌套的列表板,如下面的代码所示(我在其中收到了帮助,here)
我需要的第二个函数是计算机转动的函数-它使用第一个函数并通过以下方式之一选择最佳移动:
或
和
我所拥有的是一个玩家对一个玩家
代码:
def get_move(whoseturn, board):
rowloc=int(input(f'{whoseturn},insert the deserved row to place your symbol: '))
coloc=int(input(f'{whoseturn} insert the deserved column to place your symbol: '))
while True:
if not (0 <= rowloc < 3 and 0 <= coloc < 3):
print('row and column must be 0, 1, or 2')
rowloc = int(input(f'{whoseturn},insert the deserved row to place your symbol: '))
coloc = int(input(f'{whoseturn} insert the deserved column to place your symbol: '))
elif board[rowloc][coloc] !='e':
print("The deserved place is taken, choose again ")
rowloc = int(input(f'{whoseturn},insert the deserved row to place your symbol: '))
coloc = int(input(f'{whoseturn} insert the deserved column to place your symbol: '))
else:
board[rowloc][coloc] = whoseturn
break
return rowloc, coloc
def display_board(board):
print('\n'.join([' '.join(board[i]) for i in range(3)]))
def win(board, whoseturn, x, y):
if board[0][y] == board[1][y] == board [2][y] == whoseturn:
return True
if board[x][0] == board[x][1] == board [x][2] == whoseturn:
return True
if x == y and board[0][0] == board[1][1] == board [2][2] == whoseturn:
return True
if x + y == 2 and board[0][2] == board[1][1] == board [2][0] == whoseturn:
return True
return False
def isfull(board):
for i in range(0,3):
for j in range(0,3):
if board[i][j]=='e':
return False
return True
def main():
board = [['e','e','e']
,['e','e','e']
,['e','e','e']]
print("Welcome to the great tic tac toe game!")
player1=input("Player 1, select your symbol (X/O): ")
if player1 =='O':
print('X is player 2s symbol')
player2 = 'X'
else:
print('O is player 2s symbol')
player2 = 'O'
print("Player 1 will start")
whoseturn=player1
while True:
display_board(board)
rowloc, coloc = get_move(whoseturn, board)
if win(board,whoseturn, rowloc, coloc):
print(f'{whoseturn} wins!')
display_board(board)
break
if isfull(board):
print('Tied')
break
if whoseturn=='O':
whoseturn='X'
else:
whoseturn='O'
if __name__ == '__main__':
main()
未来董事会功能的开始
代码:
def futuremove(board,whoseturn):
newboard=copy.deepcopy(board)
place = []
copyboard = []
arrangement=[]
final=[]
for i in range(3):
for j in range(3):
if newboard[i][j]=='e':
newboard[i][j]=whoseturn
if win(newboard,whoseturn,i,j)==True:
loctup=[i,j]
place.append(loctup)
copyboard.append(newboard)
arrangement.append(place)
arrangement.append(copyboard)
final.append(arrangement)
print(final)
else:
break
请帮助我得到一个工作的球员对电脑井字游戏! 任何帮助都将不胜感激
有很多不同的方法可以实现它,一个相当简单的方法是利用Minimax Algorithm
在一个简单的例子中,当你的程序只向前看一圈时,在游戏做出一个动作后,你的AI将为它可能做出的每一个动作生成一个棋盘,并从这些动作中生成玩家可能做出的每一个反击动作
现在你想给AI的每一个可能的动作分配一个分数,你想如何定义评分算法取决于你,但它应该代表一个特定的游戏状态对你的AI来说是好是坏
AI的每一个潜在动作的得分应该等于玩家所有反击动作的最差得分,因为我们想假设玩家将以他们的最佳利益行事
因此,您将能够确定AI的哪些潜在动作使其在当前状态下赢得游戏的可能性最大。我强烈建议阅读随附的文章,了解实现细节和更深入的理解
相关问题 更多 >
编程相关推荐