📅  最后修改于: 2023-12-03 14:49:03.813000             🧑  作者: Mango
井字游戏是一种非常经典的两人对弈游戏,又称为 "井字棋"。它不仅简单易学,而且能够培养孩子的逻辑思维能力。本文将介绍如何用 Python 实现井字游戏,让您了解游戏实现的基本原理。
# 定义棋盘
board = [
['-','-','-'],
['-','-','-'],
['-','-','-']
]
# 定义当前玩家,默认为 X
current_player = 'X'
# 打印棋盘
def print_board(board):
for row in board:
print(" ".join(row))
# 判断是否获胜
def is_winner(board, player):
# 检查行
for row in board:
if row.count(player) == 3:
return True
# 检查列
for col in range(3):
if board[0][col] == player and board[1][col] == player and board[2][col] == 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 place_piece(board, player, row, col):
if board[row][col] == '-':
board[row][col] = player
return True
else:
return False
# 交换玩家
def switch_player(current_player):
if current_player == 'X':
return 'O'
else:
return 'X'
# 清屏函数
def clear_screen():
print("\n" * 50)
# 主函数
def main():
print("Welcome to Tic Tac Toe!")
while True:
print_board(board)
row = int(input(f"Player {current_player}, select a row (0, 1, 2): "))
col = int(input(f"Player {current_player}, select a col (0, 1, 2): "))
if place_piece(board, current_player, row, col):
if is_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break
elif '-' not in board[0] and '-' not in board[1] and '-' not in board[2]:
print_board(board)
print("It's a tie!")
break
else:
current_player = switch_player(current_player)
clear_screen()
else:
print("That spot is already taken. Try again.")
if __name__ == "__main__":
main()
本文介绍了如何用 Python 实现井字游戏。通过以上实现,您不仅可以更好地理解井字游戏的基本规则,而且可以通过修改代码实现更多不同的棋类游戏。希望本文能够帮助您更好地了解 Python 的编程思想与实现方式。