如何编写一个基本的井字棋(Tic-Tac-Toe)游戏的编程代码?
时间: 2024-10-25 20:10:40 浏览: 40
编写一个基本的井字棋游戏,可以用简单的控制台应用或图形化界面。这里是一个基本的Python控制台版井字棋的示例代码:
```python
import os
# 定义棋盘大小
CH_BOARD_SIZE = 3
def draw_board(board):
print('-------------')
for row in board:
print('|', ' | '.join(row), '|')
print('--')
def check_win(board, player):
# 检查每行、每列和两条对角线
for i in range(CH_BOARD_SIZE):
if all(board[i][j] == player for j in range(CH_BOARD_SIZE)):
return True
if all(board[j][i] == player for j in range(CH_BOARD_SIZE)):
return True
# 对角线检查
if (board[0][0] == player and board[1][1] == player and board[2][2] == player) or \
(board[0][2] == player and board[1][1] == player and board[2][0] == player):
return True
return False
def tic_tac_toe():
board = [[' ']*CH_BOARD_SIZE for _ in range(CH_BOARD_SIZE)]
current_player = 'X'
while True:
draw_board(board)
row = int(input(f"{current_player}, 请输入行(0-{CH_BOARD_SIZE-1}): "))
col = int(input(f"请输入列(0-{CH_BOARD_SIZE-1}): "))
if board[row][col] != ' ':
print("该位置已被占据,换别人吧!")
continue
board[row][col] = current_player
if check_win(board, current_player):
print(f"{current_player} 获胜!")
break
current_player = 'O' if current_player == 'X' else 'X'
tic_tac_toe()
```
这个代码实现了单人游戏,每次轮到玩家输入时,检查其输入的位置是否为空,然后更新棋盘状态并检查是否有人赢得比赛。当你运行这个程序时,它会交替显示X和O的玩家。
阅读全文