0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pygameを使って RPGを作る(22.Save&Load)

Last updated at Posted at 2025-01-22

概要

・セーブ、ロード機能を追加

GameDataクラス

このクラスでセーブロードの機能を実装した。
但し、保存するデータについては現在1つのみで、ゲーム終了時にPlayerの位置のみを記録するものです

import os, pickle, time

class GameData:
    def __init__(self, save_info=None):
        self.route_path = '../game_data'
        self.save_info = save_info

    # 保存ファイル名を確保(最大10ファイル格納可能)
    def get_new_file(self):
        file = ''
        for count in range(100, 111):
            save_file = f'game_data_{count:03}.pickle'
            full_path = os.path.join(self.route_path, save_file)
            if not os.path.exists(full_path):
                file = full_path
                break
            # 暫定的
            else:
                file = full_path
                break
        return file
    
    def save(self):
        save_file = self.get_new_file()
        with open(save_file,'wb') as f:
            pickle.dump(self.save_info,f)
            print('SUCCESSLY TO SAVE.')

    def load_files(self):
        file = 'game_data_100.pickle'
        save_file = os.path.join(self.route_path, file)
        with open(save_file, 'rb') as f:
            self.save_info = pickle.load(f)
            print(self.save_info)
            print('SUCCESSLY TO LOAD.')

        return self.save_info

StartMenuクラス

    def load(self):
        print('load')
        game_data = GameData()
        save_info = game_data.load_files()
        self.parent.reset_game_state(save_info)

Mapクラス
こちらはリセットする時に、EnemyがPlayerと衝突しないようにしている。

    def reset(self, save_info):
        
        # BlockとPlayerの配置
        for i, row in enumerate(self.current_map):
            for j, column in enumerate(row):
                x = j * TILE_SIZE
                y = i * TILE_SIZE

                if column == 'B':
                    self.block = Block((x,y), self.block_images['B'], self.collision_sprites, self.all_sprites)
        print(type(save_info))
        x = save_info["x"] * TILE_SIZE
        y = save_info["y"] * TILE_SIZE
        # playerの配置
        self.player = Player(self.parent, (x,y), self.collision_sprites, self.enemy_sprites, self.all_sprites)

        return self.player, self.current_map

課題

・キャラクター名、LevelやMap名も保存するのが残課題
・ロードする時に、データを選べるようにしたい

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?