一个五子棋的代码
时间: 2023-09-12 19:07:34 浏览: 41
以下是一个简单的五子棋代码示例,使用 Python 语言实现:
```python
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋盘
board = [[0] * BOARD_SIZE for i in range(BOARD_SIZE)]
# 定义当前玩家(1 或 2)
current_player = 1
# 判断是否胜利
def check_win(row, col, player):
# 水平方向
count = 0
for i in range(col - 4, col + 5):
if i >= 0 and i < BOARD_SIZE and board[row][i] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 垂直方向
count = 0
for i in range(row - 4, row + 5):
if i >= 0 and i < BOARD_SIZE and board[i][col] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 左上到右下方向
count = 0
for i in range(-4, 5):
r = row + i
c = col + i
if r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
# 右上到左下方向
count = 0
for i in range(-4, 5):
r = row + i
c = col - i
if r >= 0 and r < BOARD_SIZE and c >= 0 and c < BOARD_SIZE and board[r][c] == player:
count += 1
if count == 5:
return True
else:
count = 0
return False
# 主循环
while True:
# 打印当前棋盘
for row in range(BOARD_SIZE):
print(' '.join(str(board[row][col]) for col in range(BOARD_SIZE)))
print()
# 获取玩家落子位置
while True:
try:
row = int(input('请输入行号:'))
col = int(input('请输入列号:'))
if row < 0 or row >= BOARD_SIZE or col < 0 or col >= BOARD_SIZE or board[row][col] != 0:
raise ValueError
break
except ValueError:
print('无效的输入,请重新输入!')
# 落子
board[row][col] = current_player
# 判断胜利
if check_win(row, col, current_player):
print('玩家 %d 胜利!' % current_player)
break
# 切换玩家
current_player = 3 - current_player
```
该代码实现了一个简单的五子棋游戏,玩家可以输入行号和列号来落子,程序会判断是否胜利,并在胜利时输出胜利信息。