终端玩家网格布局重叠问题:求合理并排的位置计算方案
终端玩家网格重叠问题解决
我尝试在终端中绘制玩家网格,但无论怎么调整,网格总会完全或部分重叠,没法让网格在当前终端尺寸下以最多数量并排显示在单行里。
我已尝试的实现代码
计算网格位置的函数
def calculate_player_grid_positions(num_players, max_y, max_x): grid_height = GRID_HEIGHT grid_width = GRID_WIDTH offset = 10 # Horizontal offset # Calculate the number of rows and columns of grids that can fit in the terminal num_rows = max_y // grid_height num_cols = max_x // grid_width # Calculate the number of players in a single row players_in_single_row = min(num_players, num_cols) # Calculate the width of each player's grid area player_grid_width = (max_x - (players_in_single_row - 1) * offset) // players_in_single_row # Calculate the top-left coordinates for each player's grid player_positions = [] for player_id in range(num_players): row_index = player_id // players_in_single_row col_index = player_id % players_in_single_row # Calculate the vertical offset y_offset = row_index * (grid_height + offset) # Calculate the horizontal offset for each player x_offset = col_index * (player_grid_width + offset) player_positions.append((x_offset, y_offset)) return player_positions
全局初始化变量
GRID_WIDTH = 30 GRID_HEIGHT = 20 # Define the grid offset and border properties GRID_OFFSET_X = 5 GRID_OFFSET_Y = 6 # Moved down by 3 rows GRID_ROWS = 20 GRID_COLS = 40
获取终端尺寸的代码
max_y, max_x = stdscr.getmaxyx()
问题分析与修正方案
核心问题点
- 计算单行可容纳网格数时,仅用
max_x // grid_width,忽略了网格间的offset,导致算出的列数远超实际可容纳数量 - 额外计算
player_grid_width完全多余,因为已经固定了GRID_WIDTH,重新分配宽度会导致实际网格尺寸和分配区域不匹配,进而重叠 - 垂直方向偏移计算未考虑终端高度限制,可能导致多行网格超出终端范围
修正后的代码
def calculate_player_grid_positions(num_players, max_y, max_x): grid_height = GRID_HEIGHT grid_width = GRID_WIDTH offset = 10 # 网格间的水平/垂直间距 # 计算单行最多可容纳的网格数:每个网格占 grid_width + offset 宽度,最后一个网格无需末尾偏移,故加offset后整除 num_cols = (max_x + offset) // (grid_width + offset) players_in_single_row = min(num_players, num_cols) player_positions = [] for player_id in range(num_players): row_index = player_id // players_in_single_row col_index = player_id % players_in_single_row # 垂直偏移:每行占用 grid_height + offset 的高度 y_offset = row_index * (grid_height + offset) # 水平偏移:每个网格占用 grid_width + offset 的宽度 x_offset = col_index * (grid_width + offset) # 可选:检查是否超出终端边界,避免绘制无效内容 if y_offset + grid_height > max_y or x_offset + grid_width > max_x: continue player_positions.append((x_offset, y_offset)) return player_positions
关键修正说明
- 准确计算单行网格数:通过
(max_x + offset) // (grid_width + offset)确保每个网格之间的偏移被计入,得到真实可容纳的数量 - 移除无效的宽度重分配:直接使用固定的
GRID_WIDTH计算位置,避免尺寸不匹配导致的重叠 - 边界检查:新增可选的边界判断,跳过超出终端范围的网格绘制
额外提示
如果网格需要加上全局定义的GRID_OFFSET_X/Y,在绘制时把这些值加到计算出的x_offset和y_offset上即可,比如:
final_x = x_offset + GRID_OFFSET_X final_y = y_offset + GRID_OFFSET_Y
内容的提问来源于stack exchange,提问作者wookieluvr
相关产品推荐
相关产品推荐

