-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
95 lines (74 loc) · 2.28 KB
/
database.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
import sqlite3
from config import DATABASE_FILEPATH
class DataBase:
"""A class for providing database functionalities to the game and ui
Attributes:
connection: The connection to the database. This allows executing
SQL on the database.
"""
def __init__(self):
"""Inits DataBase"""
self.connection = self._create_connection()
try:
self._create_table()
except sqlite3.OperationalError:
pass
def _create_connection(self):
"""Creates the database and sets up a connection to it.
Returns:
The connection to the database
"""
connection = sqlite3.connect(DATABASE_FILEPATH)
connection.isolation_level = None
return connection
def _create_table(self):
"""Creates a table for storing data about game runs"""
self.connection.execute(
"""
CREATE TABLE GameRuns (
id INTEGER PRIMARY KEY,
level INTEGER
);
"""
)
def store_result(self, result: int):
"""Stores a numeric result to the database
Args:
result: the highest level the player beats during a single game run
"""
self.connection.execute(
"""
INSERT INTO GameRuns (level) VALUES (?)
""",
[result]
)
def query_highscore(self):
"""Queries the database for the highest result
Returns:
The highest value in the level field of the GameRuns table
"""
return self.connection.execute(
"""
SELECT MAX(level)
FROM GameRuns
"""
).fetchone()[0]
def query_number_of_runs(self):
"""Queries the database for the total number of game runs
Returns:
The count of rows in the GameRuns table
"""
return self.connection.execute(
"""
SELECT COUNT(DISTINCT(id))
FROM GameRuns
"""
).fetchone()[0]
def reset_database(self):
"""Resets the database to a empty state"""
self.connection.execute(
"""
DROP TABLE IF EXISTS GameRuns
"""
)
self._create_table()