如何用Python编写实现tic-tac-toe
时间: 2023-04-09 20:02:01 浏览: 147
你可以使用Python编写一个简单的tic-tac-toe游戏,以下是一个示例代码:
```
def print_board(board):
print("-------------")
for i in range(3):
print("|", end="")
for j in range(3):
print(" " + board[i][j] + " |", end="")
print("\n-------------")
def check_win(board, player):
for i in range(3):
if (board[i][0] == player and board[i][1] == player and board[i][2] == player):
return True
if (board[0][i] == player and board[1][i] == player and board[2][i] == player):
return True
if (board[0][0] == player and board[1][1] == player and board[2][2] == player):
return True
if (board[0][2] == player and board[1][1] == player and board[2][0] == player):
return True
return False
def tic_tac_toe():
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
players = ["X", "O"]
current_player = players[0]
print_board(board)
while True:
print("It's " + current_player + "'s turn.")
row = int(input("Enter row (0-2): "))
col = int(input("Enter column (0-2): "))
if (board[row][col] != " "):
print("That spot is already taken. Try again.")
continue
board[row][col] = current_player
print_board(board)
if (check_win(board, current_player)):
print(current_player + " wins!")
break
if (board[0].count(" ") == 0 and board[1].count(" ") == 0 and board[2].count(" ") == 0):
print("It's a tie!")
break
current_player = players[(players.index(current_player) + 1) % 2]
tic_tac_toe()
```
这个程序会让两个玩家轮流下棋,直到有一方获胜或者棋盘填满。你可以根据需要进行修改和扩展。
阅读全文