生成一个python的五子棋
时间: 2024-05-07 10:15:57 浏览: 215
用python做的五子棋AI,高度还原,超好玩。
抱歉,作为AI语言模型,我无法生成可视化的五子棋游戏。但是以下是一个简单的五子棋代码示例,可以在Python控制台中运行:
```python
import numpy as np
# 初始化棋盘
def init_board():
board = np.zeros((15, 15), dtype=int)
return board
# 打印棋盘
def print_board(board):
print(" ", end="")
for i in range(15):
print(i + 1, end=" ")
print()
for i in range(15):
print(i + 1, end=" ")
for j in range(15):
if board[i][j] == 0:
print("+", end=" ")
elif board[i][j] == 1:
print("O", end=" ")
else:
print("X", end=" ")
print()
# 判断是否下子
def is_valid(board, x, y):
if x < 0 or x >= 15 or y < 0 or y >= 15:
return False
if board[x][y] != 0:
return False
return True
# 判断是否获胜
def check_win(board, player):
for i in range(15):
for j in range(11):
if board[i][j:j+5].tolist() == [player]*5:
return True
for j in range(11):
if board[j][i:i+5].tolist() == [player]*5:
return True
for i in range(11):
for j in range(11):
if board[i:i+5, j:j+5].diagonal().tolist() == [player]*5:
return True
if np.fliplr(board[i:i+5, j:j+5]).diagonal().tolist() == [player]*5:
return True
return False
# 下子
def play(board, player):
while True:
try:
x, y = map(int, input("Player %d's turn (x y): " % player).split())
except ValueError:
print("Invalid input. Please input two integers separated by a space.")
continue
x -= 1
y -= 1
if is_valid(board, x, y):
board[x][y] = player
break
else:
print("Invalid move. Please try again.")
print_board(board)
if check_win(board, player):
print("Player %d wins!" % player)
return True
return False
# 主函数
def main():
board = init_board()
print_board(board)
player = 1
while True:
if play(board, player):
break
player = 3 - player
if __name__ == "__main__":
main()
```
在控制台中运行后,根据提示输入坐标即可下子。第一个下子的玩家为1,第二个下子的玩家为2。当有一方获胜时,程序会自动结束。
阅读全文