kcunning / Katie-s-Rougish-PyGame

A learning project!
http://therealkatie.net/blog/tags/pygame/
111 stars 36 forks source link

Refactoring ideas #28

Open IanWitham opened 12 years ago

IanWitham commented 12 years ago

Just some thoughts about refactoring the game. I think you should aim to seperate the logic from the presentation as much as possible. Ideally the methods to draw the game screen should be entirely seperated from the methods which update the state of your player, monsters, treasures etc, which in turn should be seperated from the methods to handle player input.

The main game loop should look something like the following. Note that the body of the loop is broken into three sections corresponding to input, processing, and output. Note also that this is basically pseudocode only. The actual implementation if you choose to do this would probably look quite different.

while True:
    # INPUT: Process player keystrokes etc.
    handle_player_input():

    # PROCESSING: update the game entities if the player has taken an action.
    if action_taken:
        player.update()  # move player, get treasure, hit monster etc
        for monster in monsters_on_level:
            monster.update()  # monster might think, move, attack, die etc.

    # OUTPUT: Now, only after all of the game logic has taken place,
    # We can draw the screen in its new state. No 'thinking' should occur.
    # In reality you could place all of the following code into a method
    # called "update_screen" or similar
    background.draw()
    for treasure_chest in treasure_chests_on_level:
        treasure_chest.draw()
    player.draw()
    for monster in monsters_on_level:
        monster.draw()
    info_bar.draw()
IanWitham commented 12 years ago

I've just read this interesting blog post which talks about the the game loop from a theoretical and philisophical perspective. The author closes the loop with "Model" -- which is what is happening in the players head beetween the feedback (display) and the action (input):

The 'game' aspect of this beast we call a computer game always involves 'loops'.

  • The player starts with a mental model that prompts them to...
  • Apply an action to...
  • The game system and in return...
  • Receives feedback that...
  • Updates their mental model and starts the loop all over again. Or kicks off a new loop.