python 写一个程序 井字棋
时间: 2023-05-19 10:04:39 浏览: 111
以下是 Python 编写的井字棋程序:
```python
def print_board(board):
print("-------------")
for i in range(3):
print("|", end=" ")
for j in range(3):
print(board[i][j], "|", end=" ")
print()
print("-------------")
def check_win(board):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != " ":
return True
if board[0][i] == board[1][i] == board[2][i] and board[0][i] != " ":
return True
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != " ":
return True
if board[0][2] == board[1][1] == board[2][0] and board[0][2] != " ":
return True
return False
def tic_tac_toe():
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
player = "X"
while True:
print_board(board)
row = int(input("Enter row number (1-3): ")) - 1
col = int(input("Enter column number (1-3): ")) - 1
if board[row][col] == " ":
board[row][col] = player
if check_win(board):
print_board(board)
print(player, "wins!")
break
if player == "X":
player = "O"
else:
player = "X"
else:
print("That spot is already taken. Try again.")
tic_tac_toe()
```
这个程序实现了一个简单的井字棋游戏,玩家可以通过输入行和列的数字来下棋,程序会检查是否有玩家获胜。
阅读全文