import numpy as np # 定义棋盘的大小 BOARD_SIZE = 15 # 定义棋子的类型 EMPTY = 0 BLACK = 1 WHITE = 2 # 定义棋子的显示符号 SYMBOLS = EMPTY BLACK x WHITE o # 初始化棋盘 board = npzerosBOARD_SIZE BOARD_SIZE dtype=n
修改后的代码如下:import numpy as np # 定义棋盘的大小 BOARD_SIZE = 15 # 定义棋子的类型 EMPTY = 0 BLACK = 1 WHITE = 2 # 定义棋子的显示符号 SYMBOLS = { EMPTY: '.', BLACK: 'x', WHITE: 'o', } # 初始化棋盘 board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=np.int8) # 定义函数:打印棋盘 def print_board(): print(' ', end='') for i in range(BOARD_SIZE): print(chr(ord('a') + i), end=' ') print() for i in range(BOARD_SIZE): print('%2d ' % (i + 1), end='') for j in range(BOARD_SIZE): print(SYMBOLS[board[i][j]], end=' ') print() # 定义函数:判断落子是否合法 def is_valid_move(x, y): return x >= 0 and x < BOARD_SIZE and y >= 0 and y < BOARD_SIZE and board[x][y] == EMPTY # 定义函数:判断是否有五子连珠 def has_five_in_a_row(x, y): # 水平方向 count = 1 i = 1 while x + i < BOARD_SIZE and board[x + i][y] == board[x][y]: count += 1 i += 1 i = 1 while x - i >= 0 and board[x - i][y] == board[x][y]: count += 1 i += 1 if count >= 5: return True # 垂直方向 count = 1 i = 1 while y + i < BOARD_SIZE and board[x][y + i] == board[x][y]: count += 1 i += 1 i = 1 while y - i >= 0 and board[x][y - i] == board[x][y]: count += 1 i += 1 if count >= 5: return True # 左上到右下方向 count = 1 i = 1 while x + i < BOARD_SIZE and y + i < BOARD_SIZE and board[x + i][y + i] == board[x][y]: count += 1 i += 1 i = 1 while x - i >= 0 and y - i >= 0 and board[x - i][y - i] == board[x][y]: count += 1 i += 1 if count >= 5: return True # 左下到右上方向 count = 1 i = 1 while x + i < BOARD_SIZE and y - i >= 0 and board[x + i][y - i] == board[x][y]: count += 1 i += 1 i = 1 while x - i >= 0 and y + i < BOARD_SIZE and board[x - i][y + i] == board[x][y]: count += 1 i += 1 if count >= 5: return True return False # 游戏主循环 player = BLACK while True: print_board() if player == BLACK: print('黑方落子:', end='') else: print('白方落子:', end='') move = input().strip() if move == 'q': break x, y = ord(move[0]) - ord('a'), int(move[1:]) - 1 if not is_valid_move(x, y): print('落子不合法!') continue board[x][y] = player if has_five_in_a_row(x, y): print_board() if player == BLACK: print('黑方获胜!') else: print('白方获胜!') break player = WHITE if player == BLACK else BLACK
原文地址: https://www.cveoy.top/t/topic/bBry 著作权归作者所有。请勿转载和采集!