OLD | NEW |
| (Empty) |
1 part of pop_pop_win.html; | |
2 | |
3 class GameStorage { | |
4 static const _gameCountKey = 'gameCount'; | |
5 final EventHandle _bestTimeUpdated = new EventHandle(); | |
6 final Map<String, String> _cache = new Map<String, String>(); | |
7 | |
8 Future<int> get gameCount => _getIntValue(_gameCountKey); | |
9 | |
10 Stream get bestTimeUpdated => _bestTimeUpdated.stream; | |
11 | |
12 void recordState(GameState state) { | |
13 assert(state != null); | |
14 _incrementIntValue(state.name); | |
15 } | |
16 | |
17 Future<bool> updateBestTime(Game game) { | |
18 assert(game != null); | |
19 assert(game.state == GameState.won); | |
20 | |
21 final w = game.field.width; | |
22 final h = game.field.height; | |
23 final m = game.field.bombCount; | |
24 final duration = game.duration.inMilliseconds; | |
25 | |
26 final key = _getKey(w, h, m); | |
27 | |
28 return _getIntValue(key, null) | |
29 .then((int currentScore) { | |
30 if(currentScore == null || currentScore > duration) { | |
31 _setIntValue(key, duration); | |
32 _bestTimeUpdated.add(null); | |
33 return true; | |
34 } else { | |
35 return false; | |
36 } | |
37 }); | |
38 } | |
39 | |
40 Future<int> getBestTimeMilliseconds(int width, int height, int bombCount) { | |
41 final key = _getKey(width, height, bombCount); | |
42 return _getIntValue(key, null); | |
43 } | |
44 | |
45 Future reset() { | |
46 _cache.clear(); | |
47 return targetPlatform.clearValues(); | |
48 } | |
49 | |
50 Future<int> _getIntValue(String key, [int defaultValue = 0]) { | |
51 assert(key != null); | |
52 if (_cache.containsKey(key)) { | |
53 return new Future.value(_parseValue(_cache[key], defaultValue)); | |
54 } | |
55 | |
56 return targetPlatform.getValue(key) | |
57 .then((String strValue) { | |
58 _cache[key] = strValue; | |
59 return _parseValue(strValue, defaultValue); | |
60 }); | |
61 } | |
62 | |
63 Future _setIntValue(String key, int value) { | |
64 assert(key != null); | |
65 _cache.remove(key); | |
66 String val = (value == null) ? null : value.toString(); | |
67 return targetPlatform.setValue(key, val); | |
68 } | |
69 | |
70 Future _incrementIntValue(String key) { | |
71 return _getIntValue(key) | |
72 .then((int val) { | |
73 return _setIntValue(key, val + 1); | |
74 }); | |
75 } | |
76 | |
77 static String _getKey(int w, int h, int m) => "w$w-h$h-m$m"; | |
78 | |
79 static int _parseValue(String value, int defaultValue) { | |
80 if(value == null) { | |
81 return defaultValue; | |
82 } else { | |
83 return int.parse(value); | |
84 } | |
85 } | |
86 | |
87 } | |
OLD | NEW |