Difference between revisions of "Talk:Complete Roguelike Tutorial, using python+libtcod, part 10"

From RogueBasin
Jump to navigation Jump to search
(Blanked the page)
(→‎Saving and loading: new section)
Line 1: Line 1:
== Saving and loading ==


I didn't want to make a major change to the tutorial without checking, but the method given to deal with the duplication of 'player' seems unnecessarily complicated.  pickle (which shelve uses internally) knows how to deal with duplicate object references as long as you pickle them in one go.  So you can save 'objects' and 'player' correctly like this:
<syntaxhighlight lang="python">
    file['objects_and_player'] = objects, player
</syntaxhighlight>
then load them using:
<syntaxhighlight lang="python">
    objects, player = file['objects_and_player]
</syntaxhighlight>
Personally, I find it easier to put all the objects you want to save into a single dict or list, and just save the whole thing using pickle.dump.  For example:
<syntaxhighlight lang="python">
    def save_game():
        with open('savegame', 'wb') as file:
            pickle.dump([map, objects, player, inventory, game_msgs, game_state], file)
    def load_game():
        global map, objects, player, inventory, game_msgs, game_state
        with open('savegame', 'rb') as file:
            map, objects, player, inventory, game_msgs, game_state = pickle.load(file)
</syntaxhighlight>
Though maybe there is some advantage to using shelve that I'm not aware of. [[User:James|James]] ([[User talk:James|talk]]) 21:09, 5 July 2014 (CEST)

Revision as of 19:09, 5 July 2014

Saving and loading

I didn't want to make a major change to the tutorial without checking, but the method given to deal with the duplication of 'player' seems unnecessarily complicated. pickle (which shelve uses internally) knows how to deal with duplicate object references as long as you pickle them in one go. So you can save 'objects' and 'player' correctly like this:

    file['objects_and_player'] = objects, player

then load them using:

    objects, player = file['objects_and_player]

Personally, I find it easier to put all the objects you want to save into a single dict or list, and just save the whole thing using pickle.dump. For example:

    def save_game():
        with open('savegame', 'wb') as file:
            pickle.dump([map, objects, player, inventory, game_msgs, game_state], file)

    def load_game():
        global map, objects, player, inventory, game_msgs, game_state
        with open('savegame', 'rb') as file:
            map, objects, player, inventory, game_msgs, game_state = pickle.load(file)

Though maybe there is some advantage to using shelve that I'm not aware of. James (talk) 21:09, 5 July 2014 (CEST)