python简单的五子棋游戏
时间: 2023-07-08 15:34:53 浏览: 79
好的,以下是一个简单的五子棋游戏的 Python 代码:
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15))
return board
# 检查是否有五子连珠
def check_win(board, x, y):
# 检查行
if np.sum(board[x, :]) == 5 or np.sum(board[x, :]) == -5:
return True
# 检查列
if np.sum(board[:, y]) == 5 or np.sum(board[:, y]) == -5:
return True
# 检查对角线
if x == y:
if np.sum(np.diag(board)) == 5 or np.sum(np.diag(board)) == -5:
return True
# 检查反对角线
if x + y == 14:
if np.sum(np.diag(np.fliplr(board))) == 5 or np.sum(np.diag(np.fliplr(board))) == -5:
return True
return False
# 下棋
def play(board, x, y, player):
if(board[x][y] == 0):
board[x][y] = player
return True
else:
return False
# 打印棋盘
def print_board(board):
print(" ", end="")
for i in range(board.shape[1]):
print("{0:2d}".format(i), end="")
print()
for i in range(board.shape[0]):
print("{0:2d}".format(i), end="")
for j in range(board.shape[1]):
if board[i][j] == 1:
print(" X", end="")
elif board[i][j] == -1:
print(" O", end="")
else:
print(" .", end="")
print()
# 游戏主函数
def main():
board = init_board()
player = 1
print_board(board)
while True:
x = int(input("Player {0}'s turn, please enter x coordinate: ".format(player)))
y = int(input("Player {0}'s turn, please enter y coordinate: ".format(player)))
if play(board, x, y, player):
print_board(board)
if check_win(board, x, y):
print("Player {0} wins!".format(player))
break
player = -player
else:
print("Illegal move, please try again.")
if __name__ == "__main__":
main()
```
这个程序使用了 numpy 库来表示棋盘,其中 1 表示黑子,-1 表示白子,0 表示空。程序还实现了下棋、打印棋盘、检查胜负等功能。你可以运行这个程序并尝试与计算机对弈。
阅读全文