用python二维列表实现五子棋
时间: 2024-03-24 08:16:44 浏览: 52
基于python五子棋的设计与实现(论文+源码)-kaic.doc
5星 · 资源好评率100%
下面是一个用 Python 实现的五子棋程序,使用二维列表来存储棋盘的状态:
```python
# 初始化棋盘
board = [['+' for x in range(15)] for y in range(15)]
# 打印棋盘
def print_board(board):
for row in board:
print(' '.join(row))
# 判断是否胜利
def check_win(board, x, y):
# 判断横向
count = 1
for i in range(1, 5):
if x - i < 0 or board[y][x - i] != board[y][x]:
break
count += 1
for i in range(1, 5):
if x + i >= 15 or board[y][x + i] != board[y][x]:
break
count += 1
if count >= 5:
return True
# 判断纵向
count = 1
for i in range(1, 5):
if y - i < 0 or board[y - i][x] != board[y][x]:
break
count += 1
for i in range(1, 5):
if y + i >= 15 or board[y + i][x] != board[y][x]:
break
count += 1
if count >= 5:
return True
# 判断左上到右下
count = 1
for i in range(1, 5):
if x - i < 0 or y - i < 0 or board[y - i][x - i] != board[y][x]:
break
count += 1
for i in range(1, 5):
if x + i >= 15 or y + i >= 15 or board[y + i][x + i] != board[y][x]:
break
count += 1
if count >= 5:
return True
# 判断左下到右上
count = 1
for i in range(1, 5):
if x - i < 0 or y + i >= 15 or board[y + i][x - i] != board[y][x]:
break
count += 1
for i in range(1, 5):
if x + i >= 15 or y - i < 0 or board[y - i][x + i] != board[y][x]:
break
count += 1
if count >= 5:
return True
return False
# 主循环
turn = 0
while True:
# 打印棋盘
print_board(board)
# 询问玩家下棋位置
if turn % 2 == 0:
player = 'X'
else:
player = 'O'
pos = input('Player %s, please enter your position (e.g. 1,2): ' % player)
x, y = map(int, pos.split(','))
if board[y][x] != '+':
print('This position is already taken. Please choose another one.')
continue
# 下棋
board[y][x] = player
# 判断胜负
if check_win(board, x, y):
print_board(board)
print('Player %s wins!' % player)
break
# 判断是否平局
if turn == 224:
print_board(board)
print('It\'s a draw!')
break
# 轮换玩家
turn += 1
```
注意,此处的实现只是一个简单的示例,并没有考虑很多情况,比如输入的坐标不合法等等。在实际开发中,需要根据具体需求进行修改和完善。
阅读全文