My process for writing terminal/text/cmd based games.
Currently writing a terminal based game and wanted to share the process I use to keep my game design simple.
The game basically does three things:
- Display some information to the player.
- The player enters some input.
- The input is processed.
And the process is repeated from step 1 again. Every scene or screen, will more or less have all these things.
The code below is the base class that is inherited by every scene/screen
class GameState: def __init__(self,game): self.game = game def display(self): return NotImplementedError("Each state must have a display") def handle_input(self,user_input): return NotImplementedError("Each state must have an input")
So a simple screen for lets say interaction screen would inherit from our base class and would look something like this:
class NPC(GameState): def display(self): print("You are approached by a sketchy dude in a hoodie. What do you do?") print(" 1. Run ") print(" 2. Fight ") print(" 3. F around and F out ") def run(self): print("running") # you can write any other function you require here def handle_input(self,user_input): if user_input == 1: self.run() # elif user_input == 2: # self.fight() # elif user_input == 3: # self.fifo()
Now for the main game loop we import our scenes to the main file:
from scenes import NPC class Game: def __init__(self): self.interaction = NPC(self) self.current_scene = self.interaction def change_state(self,new_state) -> None: self.current_state = new_state def run(self): while self.running: self.current_state.display() try: user_input = int(input(">")) self.current_state.handle_input(user_input) except ValueError: print("Invalid input") if __name__ == "__main__": game = Game() game.run()
The change_state() function helps us change between from one scene to another.
Conclusion: And that's it, every time I want to create a new scene or page I just create a new .py file, import the base game state and start writing a new screen. It keeps my code organized. I have also written Pygame games in this state manager.
Icebound Zero
A drug dealing game.
Status | In development |
Author | sesmania |
Genre | Strategy, Simulation |
Tags | cmd, drug-dealing, Management, terminal, Text based |
Leave a comment
Log in with itch.io to leave a comment.