用Python写一个五子棋游戏
时间: 2024-03-06 18:25:40 浏览: 109
python实现简单的五子棋游戏
5星 · 资源好评率100%
好的,以下是一个简单的 Python 五子棋游戏代码示例:
```python
import numpy as np
# 初始化棋盘
def create_board():
board = np.zeros((15, 15))
return board
# 判断是否有五子连珠
def check_winner(board, player):
# 检查横向
for i in range(15):
for j in range(11):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# 检查纵向
for i in range(11):
for j in range(15):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# 检查斜向
for i in range(11):
for j in range(11):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
for i in range(11):
for j in range(4, 15):
if board[i][j] == player and board[i+1][j-1] == player and board[i+2][j-2] == player and board[i+3][j-3] == player and board[i+4][j-4] == player:
return True
return False
# 主函数
def main():
# 初始化棋盘
board = create_board()
# 记录当前玩家
player = 1
# 游戏循环
while True:
# 打印棋盘
print(board)
# 等待玩家下棋
row = int(input("请输入落子的行号:"))
col = int(input("请输入落子的列号:"))
# 判断该位置是否可下棋
if board[row][col] != 0:
print("该位置已有棋子,请重新落子!")
continue
# 下棋
board[row][col] = player
# 判断是否获胜
if check_winner(board, player):
print("玩家 %d 获胜!" % player)
break
# 切换玩家
player = 2 if player == 1 else 1
if __name__ == "__main__":
main()
```
这个示例中,我们使用了 numpy 库来创建棋盘,使用一个二维数组表示棋盘,其中 0 表示该位置没有棋子,1 表示该位置为玩家1的棋子,2 表示该位置为玩家2的棋子。在游戏循环中,我们先打印棋盘,然后等待玩家输入落子的位置。如果该位置已有棋子,则提示玩家重新落子。如果该位置没有棋子,则下棋。然后判断是否获胜,如果获胜,则输出获胜信息并结束游戏循环。如果没有获胜,则切换玩家,继续游戏。
阅读全文