Store configuration in user configuration directory

This commit is contained in:
Yohann D'ANELLO 2020-11-19 03:13:01 +01:00
parent 00f843754a
commit 0fbbf4925d
3 changed files with 18 additions and 6 deletions

View File

@ -136,13 +136,14 @@ class Game:
""" """
Loads the game from a file Loads the game from a file
""" """
if os.path.isfile("save.json"): file_path = ResourceManager.get_config_path("save.json")
with open("save.json", "r") as f: if os.path.isfile(file_path):
with open(file_path, "r") as f:
self.load_state(json.loads(f.read())) self.load_state(json.loads(f.read()))
def save_game(self) -> None: def save_game(self) -> None:
""" """
Saves the game to a file Saves the game to a file
""" """
with open("save.json", "w") as f: with open(ResourceManager.get_config_path("save.json"), "w") as f:
f.write(json.dumps(self.save_state())) f.write(json.dumps(self.save_state()))

View File

@ -7,7 +7,15 @@ class ResourceManager:
and stores files in config directory. and stores files in config directory.
""" """
BASE_DIR = Path(__file__).resolve().parent / 'assets' BASE_DIR = Path(__file__).resolve().parent / 'assets'
# FIXME This might not work on not-UNIX based systems.
CONFIG_DIR = Path.home() / '.config' / 'squirrel-battle'
@classmethod @classmethod
def get_asset_path(cls, filename: str) -> str: def get_asset_path(cls, filename: str) -> str:
return str(cls.BASE_DIR / filename) return str(cls.BASE_DIR / filename)
@classmethod
def get_config_path(cls, filename: str) -> str:
cls.CONFIG_DIR.mkdir(parents=True) if not cls.CONFIG_DIR.is_dir() \
else None
return str(cls.CONFIG_DIR / filename)

View File

@ -2,6 +2,8 @@ import json
import os import os
from typing import Any, Generator from typing import Any, Generator
from .resources import ResourceManager
class Settings: class Settings:
""" """
@ -81,13 +83,14 @@ class Settings:
""" """
Loads the settings from a file Loads the settings from a file
""" """
if os.path.isfile("settings.json"): file_path = ResourceManager.get_config_path("settings.json")
with open("settings.json", "r") as f: if os.path.isfile(file_path):
with open(file_path, "r") as f:
self.loads_from_string(f.read()) self.loads_from_string(f.read())
def write_settings(self) -> None: def write_settings(self) -> None:
""" """
Dumps the settings into a file Dumps the settings into a file
""" """
with open("settings.json", "w") as f: with open(ResourceManager.get_config_path("settings.json"), "w") as f:
f.write(self.dumps_to_string()) f.write(self.dumps_to_string())