如何优化Python文本版国际象棋棋盘的显示效果?
Python文本版国际象棋棋盘优化方案
问题根源
原代码的核心问题在于:
- 终端字符默认宽高比约为2:1,单字符格子会导致棋盘视觉上高度远大于宽度
- 选用的边框字符(
—、|)过于纤细,布局松散,缺乏规整感 - 棋盘尺寸逻辑不符合国际象棋8x8的标准
优化方案
修改后代码
import os, readchar, time, threading, random global arrowKey global speed newchar = '' arrowKey = {'\x1b[A': 'up'} class Array: def __init__(self, x=16, y=8, board=None): self.pos = () self.x = x self.y = y self.grid = board if board is not None else [] def reload(self, say=None): os.system('clear') if say is not None: print(say) print('\n'.join(''.join(row) for row in self.grid)) def insert(self, char, x, y): self.pos = (x, y) # 每个格子占2列,所以x是列的起始位置 self.grid[y][x] = char[0] if len(char) > 1: self.grid[y][x+1] = char[1] def move(self, direction, char): poslist = [] for y, row in enumerate(self.grid): for x, c in enumerate(row): if c == char[0] and (x+1 >= len(row) or row[x+1] == char[1]): poslist.append((x, y)) break # 每个棋子占2列,找到起始位置即可 for posx, posy in poslist: if direction == 'down': if posy + 1 < self.y: self.insert(' ', posx, posy) self.insert(char, posx, posy + 1) elif direction == 'up': if posy - 1 >= 0: self.insert(' ', posx, posy) self.insert(char, posx, posy - 1) elif direction == 'left': if posx - 2 >= 0: self.insert(' ', posx, posy) self.insert(char, posx - 2, posy) elif direction == 'right': if posx + 2 < self.x: self.insert(' ', posx, posy) self.insert(char, posx + 2, posy) def getpos(self, char): poslist = [] for y, row in enumerate(self.grid): for x, c in enumerate(row): if c == char[0] and (x+1 >= len(row) or row[x+1] == char[1]): poslist.append((x, y)) break return poslist class Chess(Array): def __init__(self): # 国际象棋是8x8格子,每个格子占2列宽度 grid_width = 8*2 + 1 grid_height = 8 + 1 # 初始化棋盘框架 board = [] # 第一行 board.append(['╔'] + ['═══']*8) board[0] = ''.join(board[0]).replace('═══', '╦═══', 7) + '╗' # 中间行 for _ in range(7): row = ['║'] + [' ']*8 row = ''.join(row).replace(' ', '║ ', 7) + '║' board.append(row) separator = ['╠'] + ['═══']*8 separator = ''.join(separator).replace('═══', '╬═══', 7) + '╣' board.append(separator) # 最后一行 row = ['║'] + [' ']*8 row = ''.join(row).replace(' ', '║ ', 7) + '║' board.append(row) board.append(['╚'] + ['═══']*8) board[-1] = ''.join(board[-1]).replace('═══', '╩═══', 7) + '╝' # 转换为列表的列表方便修改 board = [list(line) for line in board] super().__init__(x=grid_width, y=grid_height, board=board) # 测试:添加几个棋子示例 board = Chess() board.insert('♖', 1, 1) # 黑车 board.insert('♘', 3, 1) # 黑马 board.insert('♔', 7, 1) # 黑王 board.insert('♙', 1, 2) # 黑兵 board.insert('♕', 7, 8) # 白后 board.insert('♗', 5, 8) # 白象 board.reload()
关键改动说明
- 宽高比例修正:每个棋盘格子采用2列宽度+1行高度的结构,抵消终端字符2:1的宽高比,让格子视觉上接近正方形
- 紧凑边框字符:使用Unicode边框字符(
╔、╦、╗、╠、╬、╣、╚、╩、╝、═、║)构建规整的棋盘框架,解决布局松散问题 - 适配棋子显示:修改
insert和move方法,支持占2列宽度的Unicode棋子字符(如♖、♘等),符合国际象棋棋子的显示需求 - 标准尺寸对齐:严格按照国际象棋8x8的标准设计棋盘尺寸,避免原代码的尺寸混乱
内容的提问来源于stack exchange,提问作者Mark Wilson
相关产品推荐
相关产品推荐

