Python文本RPG游戏分屏显示及历史记录自动清理方案咨询
实现文本类RPG的分屏显示与历史记录管理
方案1:使用curses库(原生终端控制)
curses是Python内置的终端UI工具,能直接控制终端区域划分,适合开发纯文本界面的游戏。
核心实现逻辑
- 初始化终端窗口,将界面拆分为左右两个独立面板:左侧展示当前操作,右侧展示历史记录。
- 维护一个历史记录列表,每次新增记录后检查右侧面板的可显示行数,超出上限时自动删除最早的条目。
- 实时刷新两个面板的内容,保证操作与历史同步更新。
示例代码
import curses import time def main(stdscr): # 隐藏光标 curses.curs_set(0) # 获取终端尺寸 height, width = stdscr.getmaxyx() # 划分面板:左侧占2/3宽度,右侧占1/3 panel_width = width // 3 current_panel = curses.newwin(height, width - panel_width, 0, 0) history_panel = curses.newwin(height, panel_width, 0, width - panel_width) history_log = [] # 历史面板可显示的最大行数(减去边框占用的2行) max_history_lines = height - 2 while True: # 模拟玩家操作(实际开发中替换为真实游戏逻辑) current_action = "正在耕种:收获了5个小麦" # 更新当前操作面板 current_panel.clear() current_panel.addstr(0, 0, "=== 当前操作 ===") current_panel.addstr(2, 1, current_action) current_panel.border() current_panel.refresh() # 更新历史记录 history_log.append(f"[{time.strftime('%H:%M:%S')}] {current_action}") # 超出上限时删除最早记录 if len(history_log) > max_history_lines: history_log.pop(0) # 更新历史面板 history_panel.clear() history_panel.addstr(0, 0, "=== 操作历史 ===") for idx, line in enumerate(history_log, start=1): # 避免内容超出面板宽度 truncated_line = line[:panel_width - 2] history_panel.addstr(idx, 1, truncated_line) history_panel.border() history_panel.refresh() # 按q键退出程序 key = stdscr.getch() if key == ord('q'): break if __name__ == "__main__": curses.wrapper(main)
方案2:使用rich库(简洁易上手的文本UI)
rich是第三方库,提供了更友好的语法和丰富的组件,适合快速搭建文本界面。
核心实现逻辑
- 先安装库:
pip install rich - 用
Layout组件创建左右分栏布局,分别绑定当前操作和历史记录面板。 - 同样通过列表维护历史记录,超出显示行数时截断最早条目,再通过
Live组件实时刷新界面。
示例代码
from rich.layout import Layout from rich.live import Live from rich.panel import Panel import time import shutil def make_layout() -> Layout: layout = Layout() # 设置左右栏比例为2:1 layout.split( Layout(name="current", ratio=2), Layout(name="history", ratio=1) ) return layout def main(): layout = make_layout() history_log = [] # 获取终端高度,计算历史栏可显示的最大行数(减去面板标题和边框) terminal_height = shutil.get_terminal_size().lines max_history_lines = terminal_height - 4 with Live(layout, refresh_per_second=4): while True: # 模拟玩家操作 current_action = "正在战斗:击败了森林狼,获得10金币" # 更新当前操作面板 layout["current"].update(Panel(current_action, title="当前操作")) # 更新历史记录 history_log.append(f"[{time.strftime('%H:%M:%S')}] {current_action}") if len(history_log) > max_history_lines: history_log.pop(0) # 将历史列表转为字符串 history_text = "\n".join(history_log) layout["history"].update(Panel(history_text, title="操作历史")) # 按Ctrl+C退出 try: time.sleep(2) except KeyboardInterrupt: break if __name__ == "__main__": main()
关键注意事项
- 分屏逻辑:
curses通过坐标直接划分终端区域,rich通过布局组件实现分栏,两种方式都能保证左右区域独立显示。 - 历史记录截断:核心是维护一个固定长度的列表,新增记录时通过
pop(0)删除最早条目,确保历史区域始终适配屏幕尺寸。 - 实时刷新:
curses用refresh()方法手动刷新面板,rich用Live组件自动管理刷新,都能实现操作与历史的同步展示。
内容的提问来源于stack exchange,提问作者최승규
相关产品推荐
相关产品推荐

