井字棋python简单
时间: 2024-09-09 09:06:07 浏览: 48
井字棋(Tic-Tac-Toe)是一种简单的双人游戏,通常是在3x3的网格上进行。玩家轮流在空格中放置自己的标记(通常是“X”和“O”),第一个在水平线、垂直线或对角线上排列成一线的玩家获胜。如果所有的格子都被填满,而没有玩家形成一线,则游戏以平局结束。
以下是一个简单的Python实现井字棋的示例代码:
```python
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board, player):
for row in board:
if all([spot == player for spot in row]):
return True
for col in range(3):
if all([board[row][col] == player for row in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in range(3)]):
return True
return False
def get_move(player):
while True:
try:
move = int(input(f"Player {player}, enter your move (1-9): ")) - 1
if move >= 0 and move < 9:
return move
else:
print("Invalid move. Please try again.")
except ValueError:
print("Invalid move. Please enter a number.")
def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
move = get_move(current_player)
row, col = divmod(move, 3)
if board[row][col] == " ":
board[row][col] = current_player
else:
print("This spot is already taken. Please choose another one.")
continue
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
if all(all(cell != " " for cell in row) for row in board):
print_board(board)
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"
play_game()
```
在这段代码中,我们定义了一个简单的井字棋游戏,其中包括了打印棋盘、检查获胜条件、获取玩家移动和主游戏循环的函数。游戏会在控制台中进行,玩家需要输入1到9的数字来选择放置标记的位置。
阅读全文