Refactoring a Terminal Text RPG in Python
Code review notes on a beginner's Python RPG: when a folder split is too much, how a dataclass replaces the hero dict, and what to test first.

A beginner's terminal RPG on Code Review had the usual first-project shape: a character stored as a dict, a debug menu that grew one elif at a time, and a folder layout the author wasn't sure about. The question asked four things. Is a data/, systems/, utils/ split premature? Where should save/load live? How do you remove the same try/except int-parsing block that appears three times in hacks()? Is this the point to move from dicts to classes?
The two answers disagree on little and together cover most of what a Python project at this stage needs. This article works through those answers against the posted code. It is aimed at anyone about to refactor a script that has outgrown a single file.
The code is in Portuguese (heroi, mochila, armas), which doesn't affect any of the structural points below.
The layout being reviewed
The project is split like this:
rpg/
app.py
data/
armas.py
itens.py
systems/
personagem.py
inventario.py
utils/
interface.pyapp.py imports heroi from systems.personagem and mochila from systems.inventario, then holds every screen as a function: personagem(), hacks(), novo_jogo(), jogar_novo(), plus the stubs tutorial() and continue_game(). The helpers in utils/interface.py are escolher, confirmar, limpar_tela, efeito_digitacao and efeito_drama.
The point that matters is that heroi and mochila are module-level objects imported by name. Everything else in the review follows from how those two are shared and mutated.
Is the split premature?
The accepted-in-spirit answer is that it is fine if it helps the author. The reviewer's objection was narrower: it is odd to have whole modules whose only content is a single assignment of heroi or mochila.
Their rubric is cheap to apply. Write a one-sentence docstring at the top of each module saying what it is responsible for. When you add a function, ask whether it fits that sentence. If it does, it goes in. If not, either broaden the sentence or create a new module whose docstring fits. If two tiny modules only ever serve each other, merge them.
For a project this size, the rubric argues for fewer files, not more. data/ holding item dictionaries is defensible because it is data. A systems/ module that is one line long is not a system yet.
One helper instead of three try/except loops
In hacks(), the HP, gold and strength branches each contain the same loop: prompt, int(), catch ValueError, print 'Digite apenas números!', retry. The reviewer's reframing is useful: this isn't int parsing, it is re-prompting a user who makes typos. So write one function that guarantees an int comes back.
def ask_int(prompt):
'''Prompt until the user enters an integer, then return it.'''
while True:
try:
return int(input(prompt))
except ValueError:
print('Digite apenas números!')Each branch then shrinks to heroi['hp'] = ask_int('Qual quantidade de vida deseja agora? '). Once that exists, the three branches differ only in the dict key and the prompt text, so a small table of label: (key, prompt) can replace all three. The helper still calls input() and print() directly, which is fine at the edge of the program and is the subject of a later section.
Branching on menu labels
hacks() compares escolha against literal strings such as '1- vida' and '4- adicionar item a mochila'. The label is both what the user sees and what the code branches on. Rename a label in the list passed to escolher and forget the matching elif, and that menu entry silently does nothing.
The second answer suggests a match statement to cut the repetition. That needs Python 3.10 or later, so check your target version first. A dict mapping label to handler function removes the repetition on any 3.x version and keeps the label defined in one place. The same answer also points to pyinputplus for input validation. It is a third-party dependency, so for a single integer prompt the ten-line helper above is arguably the better trade. For a game with many prompt types it may earn its place.
One more thing to verify in the add-item screen: the menu prints each item's nome field, but the membership check is against the dict keys. If those ever differ, the player is told an item 'não existe nesse universo' while it is on screen.
Dicts to a dataclass
On whether to move to classes now, the reviewer's answer is @dataclass, which fits a record of four fields with no behaviour yet.
from dataclasses import dataclass
@dataclass
class Hero:
nome: str
forca: int
hp: int
ouro: intThe immediate gain is that a typo like heroi['ouo'] raises a KeyError at runtime in whichever screen hits it, while hero.ouo is flagged by an editor or linter before you run anything. The migration is also mechanical. Replace heroi['hp'] with hero.hp everywhere, then move behaviour (taking damage, spending gold) onto the class when you actually need it.
There is a Python-specific trap in the current design. from systems.personagem import heroi binds a name to one dict object. Mutating that dict is visible everywhere. Rebinding the name inside another module, for example after loading a save, is not. With a dataclass, create the instance in one place and pass it into functions as an argument.
Where persistence goes
The reviewer's view is that functions in utils/ that encode and decode dicts to JSON would work, but the more typical setup is one class per domain noun, such as Player, responsible for serializing itself. Both options are better than the current state, where nothing owns the shape of the data.
With the dataclass above, the standard library already does most of it:
import json
from dataclasses import asdict
def save(hero, path):
'''Write the hero to path as JSON.'''
with open(path, 'w', encoding='utf-8') as f:
json.dump(asdict(hero), f, ensure_ascii=False)
def load(path):
'''Read a hero back from a JSON file.'''
with open(path, encoding='utf-8') as f:
return Hero(**json.load(f))I would use explicit functions like these rather than __repr__, which the answer mentions as a place to describe serialization. __repr__ is conventionally for debugging output, and mixing it with a file format makes both harder to change. Pass ensure_ascii=False and an explicit encoding when the text is Portuguese, or accented characters will be written as escapes. The mochila list belongs in the same saved structure, which is another argument for it living on the hero object.
Tests, and keeping I/O at the edges
The reviewer's point is that the project has no unit tests, and that tests are what make the dict-to-class refactor safe: run green, make one small edit, and if it goes red you know which edit did it. The obstacle is that most functions here print or call input() directly, which is awkward to test.
The advice is to ask whether a helper could take and return plain values instead. The status screen in personagem() is a clear candidate: build the lines in one function, print them in another.
def status_lines(hero):
'''Return the lines of the character sheet.'''
return [f'nome: {hero.nome}', f'força: {hero.forca}',
f'hp: {hero.hp}', f'ouro: {hero.ouro}']
def test_status_lines():
hero = Hero('Ana', 5, 20, 0)
assert 'hp: 20' in status_lines(hero)ask_int can be tested the same way by replacing input with a stub, but start with the pure functions. They need no setup at all.
Linter findings and small cleanups
The second answer ran ruff on the code and it reported F841 Local variable remover_item is assigned to but never used. In hacks(), remover_item is set to False at the top and to True after a removal, and nothing ever reads it. Dead flags like that usually mean a feature was half-planned, so delete it or finish it.
The same answer notes that pass after limpar_tela() in the stub tutorial() is redundant, since the body already has a statement. Both answers ask for docstrings. PEP 8 recommends them, and the one-sentence habit also doubles as the module rubric from earlier. Expect to rewrite some of them as the function changes, because a docstring that no longer matches the code is the useful signal.
Where this advice does not fit
- If the game stays a short linear script, a dataclass, a persistence module and tests may cost more than they return. The reviewer's own position on the folder split was conditional on it helping the author.
matchrequires Python 3.10 or later, andpyinputplusis an extra install. Neither is worth it if the project needs to run on older interpreters or with no dependencies.- The save/load sketch handles flat data only. Once inventory entries are objects with their own fields, you need a decision about versioning the save format, which none of the answers address.
- Pure-function extraction helps testability but does not make interactive flows such as
jogar_novo(), with its nested 'press enter' checks, any easier to read. That function needs a different fix, such as a list of story lines iterated in a loop.
This article draws on Terminal-based text RPG in Python and answers to it (1, 2), on the Stack Exchange network, licensed under CC BY-SA 4.0.
- #Python
- #code review
- #dataclass
- #python-3.x
- #refactoring
- #text rpg


Comments