帮我写一个可以与用户交互的井字棋对抗代码python
时间: 2023-06-01 12:08:02 浏览: 99
python实现的井字棋小游戏
好的,我可以帮您写一个可以与用户交互的井字棋对抗代码,以下是Python代码示例:
```python
# 定义游戏状态
EMPTY = "-"
PLAYER_X = "X"
PLAYER_O = "O"
TIE = "TIE"
# 初始化游戏状态
board = [EMPTY] * 9
current_player = PLAYER_X
# 打印游戏棋盘
def print_board():
print(board[0] + "|" + board[1] + "|" + board[2])
print(board[3] + "|" + board[4] + "|" + board[5])
print(board[6] + "|" + board[7] + "|" + board[8])
# 判断是否有胜者
def get_winner():
for i in range(0, 9, 3):
if board[i] == board[i+1] == board[i+2] != EMPTY:
return board[i]
for i in range(0, 3):
if board[i] == board[i+3] == board[i+6] != EMPTY:
return board[i]
if board[0] == board[4] == board[8] != EMPTY:
return board[0]
if board[2] == board[4] == board[6] != EMPTY:
return board[2]
if EMPTY not in board:
return TIE
return None
# 游戏循环
while True:
print_board()
winner = get_winner()
if winner is not None:
if winner == TIE:
print("It's a Tie!")
else:
print(winner + " wins!")
break
move = input("Input move for " + current_player + " (0-8): ")
while True:
if not move.isdigit() or int(move) < 0 or int(move) > 8 or board[int(move)] != EMPTY:
move = input("Invalid move, input move for " + current_player + " (0-8): ")
else:
break
board[int(move)] = current_player
current_player = PLAYER_X if current_player == PLAYER_O else PLAYER_O
```
运行以上代码即可开始与AI进行井字棋游戏了。
阅读全文