python井字棋代码
时间: 2023-07-03 13:31:21 浏览: 71
以下是一个简单的 Python 井字棋代码:
```python
# 初始化游戏棋盘
board = [' '] * 9
# 绘制游戏棋盘
def draw_board():
print(board[0] + '|' + board[1] + '|' + board[2])
print('-+-+-')
print(board[3] + '|' + board[4] + '|' + board[5])
print('-+-+-')
print(board[6] + '|' + board[7] + '|' + board[8])
# 判断玩家是否胜利
def check_win(player):
if (board[0] == player and board[1] == player and board[2] == player) or \
(board[3] == player and board[4] == player and board[5] == player) or \
(board[6] == player and board[7] == player and board[8] == player) or \
(board[0] == player and board[3] == player and board[6] == player) or \
(board[1] == player and board[4] == player and board[7] == player) or \
(board[2] == player and board[5] == player and board[8] == player) or \
(board[0] == player and board[4] == player and board[8] == player) or \
(board[2] == player and board[4] == player and board[6] == player):
return True
return False
# 主程序
def main():
# 初始化游戏
player = 'X'
draw_board()
# 开始游戏
while True:
# 玩家输入位置
move = int(input('请输入位置 (1-9): '))
if board[move - 1] == ' ':
board[move - 1] = player
else:
print('位置已经被占据,请重新输入')
continue
# 绘制游戏棋盘
draw_board()
# 检查是否胜利
if check_win(player):
print('玩家 %s 获胜!' % player)
break
# 切换玩家
if player == 'X':
player = 'O'
else:
player = 'X'
print('游戏结束')
# 启动程序
main()
```
这个代码实现了一个简单的井字棋游戏,玩家可以通过输入数字来选择落子的位置,程序会自动检测是否有玩家获胜。
阅读全文