python五子棋小游戏代码
时间: 2023-07-22 20:35:28 浏览: 39
下面是一个简单的 Python 五子棋小游戏代码,可以在控制台中运行:
```python
import numpy as np
# 定义棋盘大小
board_size = 15
# 定义棋盘
board = np.zeros((board_size, board_size), dtype=int)
# 定义棋子类型
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义黑白棋子符号
stones = {EMPTY: "·", BLACK: "●", WHITE: "○"}
# 定义落子函数
def make_move(x, y, player):
global board
board[x, y] = player
# 定义判断胜负函数
def check_win(player):
global board
# 判断横向是否有五子相连
for i in range(board_size):
for j in range(board_size - 4):
if np.all(board[i, j:j+5] == player):
return True
# 判断纵向是否有五子相连
for i in range(board_size - 4):
for j in range(board_size):
if np.all(board[i:i+5, j] == player):
return True
# 判断正对角线是否有五子相连
for i in range(board_size - 4):
for j in range(board_size - 4):
if np.all(board[i:i+5, j:j+5].diagonal() == player):
return True
# 判断反对角线是否有五子相连
for i in range(4, board_size):
for j in range(board_size - 4):
if np.all(board[i-4:i+1, j:j+5].diagonal()[::-1] == player):
return True
return False
# 定义打印棋盘函数
def print_board():
global board
for i in range(board_size):
row = []
for j in range(board_size):
row.append(stones[board[i][j]])
print(" ".join(row))
# 主函数
def main():
player = BLACK
while True:
# 打印棋盘
print_board()
# 等待玩家输入落子位置
move = input("请玩家 {} 输入落子位置(x, y): ".format(stones[player]))
x, y = map(int, move.split(","))
# 判断落子位置是否合法
if x < 0 or x >= board_size or y < 0 or y >= board_size or board[x, y] != EMPTY:
print("落子位置不合法,请重新输入!")
continue
# 落子
make_move(x, y, player)
# 判断胜负
if check_win(player):
print_board()
print("玩家 {} 获胜!".format(stones[player]))
break
# 切换玩家
player = WHITE if player == BLACK else BLACK
if __name__ == "__main__":
main()
```
在控制台中运行该代码,会输出一个 15x15 的棋盘,提示黑方玩家输入落子位置。玩家可以输入类似 `3,4` 这样的坐标来落子,程序会自动判断落子是否合法,判断胜负并输出结果。
阅读全文