TicTacToe(井字棋)是一种简单的两人对弈游戏,玩家轮流在3x3的网格上放置自己的标记(通常是“X”和“O”),谁先将自己的标记连成一条直线(横、竖、对角线)谁就获胜。
以下是一个简单的TicTacToe游戏的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(s == player for s 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 main():
board = [[" " for _ in range(3)] for _ in range(3)]
players = ["X", "O"]
current_player = 0
while True:
print_board(board)
row, col = map(int, input(f"Player {players[current_player]}, enter your move (row col): ").split())
if board[row][col] == " ":
board[row][col] = players[current_player]
if check_winner(board, players[current_player]):
print_board(board)
print(f"Player {players[current_player]} wins!")
break
current_player = 1 - current_player
else:
print("Cell already taken, try again.")
if __name__ == "__main__":
main()
通过以上步骤和示例代码,你可以开始制作自己的TicTacToe应用程序。如果需要进一步扩展功能,如网络对战,可以考虑使用腾讯云提供的云服务,如腾讯云服务器和数据库,来实现多人在线对战功能。
领取专属 10元无门槛券
手把手带您无忧上云