60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
"""Game configuration and settings management."""
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Dict, Any
|
|
|
|
|
|
class GameConfig:
|
|
"""Manages game configuration and user preferences."""
|
|
|
|
def __init__(self):
|
|
self.config_file = Path.home() / '.snake_config.json'
|
|
self.config: Dict[str, Any] = self._get_defaults()
|
|
self.load_config()
|
|
|
|
def _get_defaults(self) -> Dict[str, Any]:
|
|
"""Get default configuration."""
|
|
return {
|
|
'snake_length': 3,
|
|
'snake_speed': 7,
|
|
'enable_effects': True,
|
|
'enable_music': False,
|
|
'head_char': '█',
|
|
'body_char': '▓',
|
|
'food_char': '█',
|
|
}
|
|
|
|
def load_config(self) -> None:
|
|
"""Load configuration from file."""
|
|
if self.config_file.exists():
|
|
try:
|
|
with open(self.config_file, 'r') as f:
|
|
loaded = json.load(f)
|
|
# Merge with defaults to ensure all keys exist
|
|
self.config = {**self._get_defaults(), **loaded}
|
|
except (json.JSONDecodeError, IOError):
|
|
self.save_config()
|
|
else:
|
|
self.save_config()
|
|
|
|
def save_config(self) -> None:
|
|
"""Save configuration to file."""
|
|
try:
|
|
with open(self.config_file, 'w') as f:
|
|
json.dump(self.config, f, indent=2)
|
|
except IOError as e:
|
|
print(f"Warning: Could not save config: {e}")
|
|
|
|
def get(self, key: str, default: Any = None) -> Any:
|
|
"""Get a configuration value."""
|
|
return self.config.get(key, default)
|
|
|
|
def set(self, key: str, value: Any) -> None:
|
|
"""Set a configuration value."""
|
|
self.config[key] = value
|
|
self.save_config()
|
|
|
|
def get_all(self) -> Dict[str, Any]:
|
|
"""Get all configuration."""
|
|
return self.config.copy()
|