game_setting.dart 1.9 KB

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