Python文本RPG游戏库存格式化显示:每行显示4个物品
文本RPG库存系统换行显示问题解决方案
问题描述
我是Python新手,正在制作一款文本RPG游戏的库存系统。现有代码中用for循环显示玩家库存时,每个物品会单独换行,希望修改为每行显示4个物品,且不想通过逐个索引打印物品来实现。
现有代码
class PlayerAttributes: inventory = [] def __init__(self, name, inventory): self.name = name self.inventory = inventory # LIST class Item: def __init__(self, item_name, damage): self.item_name = item_name self.damage = damage class Weapons(Item): weapon_1 = Item("Me Sword", 100) Player_1 = PlayerAttributes("Bob", []) def get_name(): Player_1.name = input("Enter name here: ").capitalize() commands() def stats(): print("Name = " + str(Player_1.name), "\n", "Inventory: ") for x in Player_1.inventory: print(str(x.item_name)) def commands(): prompt = None prompt_choices = {"stats", "quit", "give"} while prompt not in prompt_choices: prompt = input("Enter Command: ").lower() if prompt == "stats": stats() commands() elif prompt == "quit": quit() elif prompt == "give": Player_1.inventory.append(Weapons.weapon_1) commands() get_name()
当前输出(执行3次give后输入stats)
Enter name here: Test Enter Command: give Enter Command: give Enter Command: give Enter Command: stats Name = Test Inventory: Me Sword Me Sword Me Sword
期望输出(执行8次give后输入stats)
Enter name here: Test Enter Command: give Enter Command: give Enter Command: give Enter Command: give Enter Command: give Enter Command: give Enter Command: give Enter Command: give Enter Command: stats Name = Test Inventory: Me Sword, Me Sword, Me Sword, Me Sword Me Sword, Me Sword, Me Sword, Me Sword
解决方案
方法1:切片分组遍历
把库存列表按每4个一组拆分,每组用, 连接后打印,第二行及以后添加缩进对齐。修改后的stats函数如下:
def stats(): print(f"Name = {Player_1.name}\n Inventory: ", end="") # 提取所有物品名称到列表 item_names = [x.item_name for x in Player_1.inventory] # 按每4个元素为一组遍历 for i in range(0, len(item_names), 4): group = item_names[i:i+4] # 第一行直接打印,后续行加缩进对齐 if i == 0: print(", ".join(group)) else: print(" " + ", ".join(group))
方法2:计数器控制换行
遍历物品时用计数器判断是否到达每组的末尾,达到时换行并添加缩进。修改后的stats函数如下:
def stats(): print(f"Name = {Player_1.name}\n Inventory: ", end="") # 从1开始计数,方便判断每组第4个元素 for idx, item in enumerate(Player_1.inventory, 1): # 非组尾元素后面加逗号空格,组尾元素不加 print(item.item_name, end=", " if idx % 4 != 0 else "") # 每4个元素换行并添加缩进,最后一组末尾不额外换行 if idx % 4 == 0 and idx != len(Player_1.inventory): print("\n ", end="") print() # 最后补一个换行收尾
方法3:迭代器批量取元素
借助itertools.islice每次从迭代器中取4个元素,适合处理较大的库存列表。需要先导入itertools,再修改stats函数:
import itertools def stats(): print(f"Name = {Player_1.name}\n Inventory: ", end="") inventory_iter = iter(Player_1.inventory) first_group = True while True: # 每次从迭代器中取4个元素 group = list(itertools.islice(inventory_iter, 4)) if not group: break group_names = [item.item_name for item in group] # 第一行直接打印,后续行加缩进 if first_group: print(", ".join(group_names)) first_group = False else: print(" " + ", ".join(group_names))
内容的提问来源于stack exchange,提问作者HardlySalty
相关产品推荐
相关产品推荐

