-
Notifications
You must be signed in to change notification settings - Fork 8
/
stats.py
116 lines (96 loc) · 3.15 KB
/
stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# -*- coding: utf-8 -*-
# Screaming Strike statistics manager
# Copyright (C) 2019 Yukio Nozawa <personal@nyanchangames.com>
# License: GPL V2.0 (See copying.txt for details)
"""This module contains StatsStorage class, which can store high scores and other statisticks about the game."""
import pickle
import gameModes
class StatsStorage(object):
"""This object stores the game's statistics."""
def __init__(self):
self.items = {}
def initialize(self, filename):
"""Initializes the storage with the given filename. If this method fails to load the specified file, everything is reset to zero.
:param filename, File name to load.
"""
try:
f = open(filename, "rb")
except IOError:
self.resetAll()
return
# end except
try:
self.items = pickle.load(f)
except (pickle.PickleError, EOFError):
self.resetAll()
return
# end except
# end initialize
def resetAll(self):
"""Resets everything in this storage.
"""
self.items = {}
# end resetAll
def resetHighscores(self):
"""Resets highscores only."""
for mode in gameModes.ALL_MODES_STR:
self.items["hs_" + mode] = 0
# end for
# end resetHighscores
def get(self, key):
"""Retrieves the specified value.
:param key: Key to retrieve.
:type key: str
:rtype: int
"""
try:
r = self.items[key]
except KeyError:
r = 0
# end except
return r
def set(self, key, value):
"""Sets/updates the specified value.
:param key: Key to set.
:type key: str
:param value: New value.
:type value: int
"""
self.items[key] = value
# end set
def increment(self, key, unit=1):
"""increments the specified value by unit. If the key doesn't exist, create one.
:param unit: Unit. Default is 1.
:type unit: int
"""
self.checkKey(key)
self.items[key] = self.items[key] + unit
# end increment
def decrement(self, key, unit=1):
"""decrements the specified value by unit. If the key doesn't exist, does nothing.
:param unit: Unit. Default is 1.
:type unit: int
"""
self.keyCheck(key)
self.items[key] = self.items[key] - unit
# end increment
def checkKey(self, key):
"""Checks the specified key. If it doesn't exist, create a new one with 0.
:param key: Key to check.
:type key: str
"""
if key not in self.items:
self.items[key] = 0
def save(self, filename):
"""Saves the storage to a file. If IO error occurs, saving is skipped.
:param filename: File name to save.
:type filename: str
"""
try:
f = open(filename, "wb")
except IOError:
return
# end except
pickle.dump(self.items, f)
f.close()
# end save