【发布时间】:2020-05-17 10:34:35
【问题描述】:
我被要求将我的玩家与玩家井字游戏改进为 AI 井字游戏,其中玩家与计算机对战: 为此,我需要编写两个函数: 一个获取当前玩家的棋盘和符号并返回所有可能的未来棋盘列表 - 每个未来棋盘都是一个包含两个元素的列表:一个是放置符号的位置,另一个是之后的棋盘放置符号 - 转一圈后的板(我正在使用嵌套列表板,如下面的代码所示(我收到了帮助,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
请帮我找一个能正常工作的玩家与电脑井字游戏! 任何帮助将不胜感激!
【问题讨论】:
标签: python artificial-intelligence tic-tac-toe