python三子棋游戏代码
时间: 2023-07-09 11:42:57 浏览: 49
以下是一个简单的 Python 三子棋游戏代码示例:
```python
# 定义棋盘
board = [' '] * 9
# 绘制棋盘
def draw_board():
print(' %s | %s | %s ' % (board[0], board[1], board[2]))
print(' -----------')
print(' %s | %s | %s ' % (board[3], board[4], board[5]))
print(' -----------')
print(' %s | %s | %s ' % (board[6], board[7], board[8]))
# 判断胜者
def check_win(player):
win_pos = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
for pos in win_pos:
if board[pos[0]] == board[pos[1]] == board[pos[2]] == player:
return True
return False
# 游戏主循环
while True:
draw_board()
choice = input('请 %s 下棋,输入位置 1-9:' % ('X' if len([x for x in board if x != ' ']) % 2 == 0 else 'O'))
if board[int(choice) - 1] == ' ':
board[int(choice) - 1] = 'X' if len([x for x in board if x != ' ']) % 2 == 0 else 'O'
else:
print('该位置已经有棋子,请重新输入!')
continue
if check_win('X'):
print('X 获胜!')
draw_board()
break
if check_win('O'):
print('O 获胜!')
draw_board()
break
if ' ' not in board:
print('平局!')
draw_board()
break
```
运行这段代码,即可开始玩三子棋游戏。