forked from yncat/screamingstrike
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats.py
113 lines (95 loc) · 2.59 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
# -*- coding: utf-8 -*-
# Screaming Strike statisticks 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 inclement(self,key, unit=1):
"""Inclements 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 inclement
def declement(self,key, unit=1):
"""Declements 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 inclement
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 not key 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