game_setting.dart 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import 'dart:convert';
  2. import 'package:shared_preferences/shared_preferences.dart';
  3. import 'engine_type.dart';
  4. class GameSetting {
  5. static SharedPreferences? storage;
  6. static GameSetting? _instance;
  7. static const cacheKey = 'setting';
  8. EngineType robotType = EngineType.builtIn;
  9. int robotLevel = 10;
  10. bool sound = true;
  11. double soundVolume = 1;
  12. GameSetting({
  13. this.robotType = EngineType.builtIn,
  14. this.robotLevel = 10,
  15. this.sound = true,
  16. this.soundVolume = 1,
  17. });
  18. GameSetting.fromJson(String? jsonStr) {
  19. if (jsonStr == null || jsonStr.isEmpty) return;
  20. Map<String, dynamic> json = jsonDecode(jsonStr);
  21. if (json.containsKey('robotType')) {
  22. robotType = EngineType.fromName(json['robotType']) ?? EngineType.builtIn;
  23. }
  24. if (json.containsKey('robotLevel')) {
  25. robotLevel = json['robotLevel'];
  26. if (robotLevel < 10 || robotLevel > 12) {
  27. robotLevel = 10;
  28. }
  29. }
  30. if (json.containsKey('sound')) {
  31. sound = json['sound'];
  32. }
  33. if (json.containsKey('soundVolume')) {
  34. soundVolume = json['soundVolume'];
  35. }
  36. }
  37. static Future<GameSetting> getInstance() async {
  38. _instance ??= await GameSetting.init();
  39. return _instance!;
  40. }
  41. static Future<GameSetting> init() async {
  42. storage ??= await SharedPreferences.getInstance();
  43. String? json = storage!.getString(cacheKey);
  44. return GameSetting.fromJson(json);
  45. }
  46. Future<bool> save() async {
  47. storage ??= await SharedPreferences.getInstance();
  48. storage!.setString(cacheKey, toString());
  49. return true;
  50. }
  51. @override
  52. String toString() => jsonEncode({
  53. 'robotType': robotType.name,
  54. 'robotLevel': robotLevel,
  55. 'sound': sound,
  56. 'soundVolume': soundVolume,
  57. });
  58. }