python五子棋源代码
时间: 2023-09-01 08:07:57 浏览: 93
以下是一个简单的 Python 五子棋游戏的源代码示例,仅供参考:
```python
import numpy as np
# 设置棋盘大小
BOARD_SIZE = 15
# 定义棋盘
board = np.zeros((BOARD_SIZE, BOARD_SIZE))
def print_board(board):
"""输出棋盘"""
print(" ", end="")
for i in range(BOARD_SIZE):
print("{:2d}".format(i), end="")
print()
for i in range(BOARD_SIZE):
print("{:2d}".format(i), end="")
for j in range(BOARD_SIZE):
if board[i][j] == 1:
print(" ●", end="")
elif board[i][j] == 2:
print(" ○", end="")
else:
print(" +", end="")
print()
def check_win(player, row, col):
"""检查是否胜利"""
# 水平方向
count = 1
for i in range(col - 1, -1, -1):
if board[row][i] == player:
count += 1
else:
break
for i in range(col + 1, BOARD_SIZE):
if board[row][i] == player:
count += 1
else:
break
if count >= 5:
return True
# 垂直方向
count = 1
for i in range(row - 1, -1, -1):
if board[i][col] == player:
count += 1
else:
break
for i in range(row + 1, BOARD_SIZE):
if board[i][col] == player:
count += 1
else:
break
if count >= 5:
return True
# 左斜方向
count = 1
i, j = row - 1, col - 1
while i >= 0 and j >= 0:
if board[i][j] == player:
count += 1
else:
break
i -= 1
j -= 1
i, j = row + 1, col + 1
while i < BOARD_SIZE and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
else:
break
i += 1
j += 1
if count >= 5:
return True
# 右斜方向
count = 1
i, j = row - 1, col + 1
while i >= 0 and j < BOARD_SIZE:
if board[i][j] == player:
count += 1
else:
break
i -= 1
j += 1
i, j = row + 1, col - 1
while i < BOARD_SIZE and j >= 0:
if board[i][j] == player:
count += 1
else:
break
i += 1
j -= 1
if count >= 5:
return True
return False
def play_game():
"""主游戏逻辑"""
player = 1
while True:
print_board(board)
row = int(input("请玩家{}输入行号:".format(player)))
col = int(input("请玩家{}输入列号:".format(player)))
if board[row][col] != 0:
print("该位置已经有棋子了,请重新输入!")
continue
board[row][col] = player
if check_win(player, row, col):
print_board(board)
print("玩家{}获胜!".format(player))
break
player = 3 - player # 切换玩家
if __name__ == "__main__":
play_game()
```
该代码使用了 numpy 库来方便地创建和操作二维数组。在 `play_game` 函数中,首先打印棋盘,然后让玩家输入要下的位置,如果该位置已经有棋子了则提示重新输入,否则将该位置的值设置为当前玩家的编号。接着调用 `check_win` 函数检查当前玩家是否胜利,如果是则打印获胜信息并结束游戏,否则切换玩家。`check_win` 函数使用了“连五”算法来判断是否胜利,即检查当前位置的水平、垂直、左斜和右斜方向上是否有连续的五个棋子。注意,这里的玩家编号是 1 和 2,而不是常见的 0 和 1。
阅读全文