-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
437 lines (387 loc) · 15.9 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import sys
sys.path.append('__HOME__/DEMMO')
import sqlite3
import json
import constants
from constants import Database as db_constants
from containers.player import Player
from containers.monster import Monster
from containers.game import Game
class Database:
"""
This class contains class methods for operating on the database directly
"""
@classmethod
def create_game_object_tables(cls, database=db_constants.DATABASE_PATH):
'''
Record table:
num_bosses_defeated: int
Player table:
id: text
row: int
col: int
health: int
power: int
luck: int
gold: int
Monster table:
id: text
row: int
col: int
health: int
power: int
is_boss: (text) -> "False" or "True"
defeated_by: (text) -> "{}" set of ids
'''
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
c.execute(
'''CREATE TABLE IF NOT EXISTS record_table (id text, num_bosses_defeated int);''') # run a CREATE TABLE command
c.execute(
'''CREATE TABLE IF NOT EXISTS player_table (id text, row int, col int, health int, power int, luck int, gold int);''') # run a CREATE TABLE command
c.execute(
'''CREATE TABLE IF NOT EXISTS monster_table (id text, row int, col int, health int, power int, is_boss text, defeated_by text);''') # run a CREATE TABLE command
conn.commit() # commit commands
conn.close() # close connection to database
@classmethod
def create_or_update_player(cls, id, row, col, health, power, luck, gold, num_bosses_defeated, database=db_constants.DATABASE_PATH):
"""
Updates a player entry in the player_table if the player exists or creates a new entry otherwise
:param id: (string) the player id to update or create
:param row: (int) player's row
:param col: (int) player's col
:param health: (int) player's health
:param power: (int) player's power
:param gold: (int) player's gold
:param num_bosses_defeated: (int) player's number of bosses defeated
:return: None
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Determine whether the player exists in the database
player_exists = c.execute(
'''SELECT EXISTS(SELECT 1 FROM player_table WHERE id = ?);''', (id, )).fetchone()[0]
if not player_exists: # Create a new player entry if the player does not exist
c.execute(
'''INSERT into player_table VALUES(?, ?, ?, ?, ?, ?, ?);''',
(id, row, col, health, power, luck, gold))
else: # Update the existing player if the player exists
c.execute(
'''UPDATE player_table SET row = ?, col = ?, health = ?, power = ?, luck = ?, gold = ? WHERE id = ?;''',
(row, col, health, power, luck, gold, id))
# Determine whether a record exists for the player
record_exists = c.execute(
'''SELECT EXISTS(SELECT 1 FROM record_table where id = ?);''', (id, )).fetchone()[0]
if not record_exists: # Create a new record entry if the record does not exist
c.execute(
'''INSERT into record_table VALUES(?, ?);''',
(id, num_bosses_defeated)
)
else: # Update the existing record if the record exists
c.execute(
'''UPDATE record_table SET num_bosses_defeated = ? WHERE id = ?''',
(num_bosses_defeated, id)
)
conn.commit() # commit commands
conn.close() # close connection to database
@classmethod
def create_or_update_monster(cls, id, row, col, health, power, is_boss, defeated_by, database=db_constants.DATABASE_PATH):
"""
Updates a monster entry in the monster_table if the monster exists or creates a new entry otherwise
:param id: (string) the monster id to update or create
:param row: (int) monster's row
:param col: (int) monster's col
:param health: (int) monster's health
:param power: (int) monster's power
:param is_boss: (string) "True" or "False" indicating whether or not the monster is a boss
:param defeated_by: (string) string representation of a set of player ids that have defeated it (strings)
:return: None
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Determine whether the player exists in the database
monster_exists = c.execute(
'''SELECT EXISTS(SELECT 1 FROM monster_table WHERE id = ?);''', (id, )).fetchone()[0]
if not monster_exists: # Create a new player entry if the player does not exist
c.execute(
'''INSERT into monster_table VALUES(?, ?, ?, ?, ?, ?, ?);''',
(id, row, col, health, power, is_boss, defeated_by))
else: # Update the existing player if the player exists
c.execute(
'''UPDATE monster_table SET row = ?, col = ?, health = ?, power = ?, is_boss = ?, defeated_by = ? WHERE id = ?;''',
(row, col, health, power, is_boss, defeated_by, id))
conn.commit() # commit commands
conn.close() # close connection to database
@classmethod
def get_all_players(cls, database=db_constants.DATABASE_PATH):
"""
:return: (list) of all entries from the player database (empty if no players exist)
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Query for all players
players = c.execute('''SELECT * FROM player_table;''').fetchall()
records = c.execute('''SELECT * FROM record_table;''').fetchall()
# Append each player's records to each player
records = {id: (num_bosses_defeated,) for id, num_bosses_defeated in records}
all_players = []
for player in players:
id = player[0]
# convert num bosses defeated to a tuple this to a tuple
num_bosses_defeated = records[id]
all_players.append(player + num_bosses_defeated)
conn.commit() # commit commands
conn.close() # close connection to database
return all_players
@classmethod
def get_all_monsters(cls, database=db_constants.DATABASE_PATH):
"""
:return: (list) of all entries from the monster databsae (empty if no monsters exist)
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Query for all monsters
monsters = c.execute('''SELECT * FROM monster_table;''').fetchall()
conn.commit() # commit commands
conn.close() # close connection to database
return monsters
@classmethod
def get_monsters_within_range(cls, row, col, database=db_constants.DATABASE_PATH):
"""
:param row: the current row
:param col: the current col
:return: (list) of all monsters within range of (row, col)
# TODO (if needed for performance reasons): Implement this
"""
pass
@classmethod
def get_players_within_range(cls, row, col, database=db_constants.DATABASE_PATH):
"""
:param row: the current row
:param col: the current col
:return: (list) of players within range of (row, col)
# TODO (if needed for performance reasons): Implement this
"""
pass
@classmethod
def get_player_info(cls, player_id, database=db_constants.DATABASE_PATH):
"""
Returns a specific player's information
:param player_id: the player id
:return: (tuple) of player info or None if player does not exist in database
player info format = (id, row, col, health, power, gold, num_bosses_defeated)
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Query for player information
player_info = c.execute('''SELECT * FROM player_table WHERE id = ?;''',(player_id,)).fetchone()
record_info = c.execute('''SELECT * FROM record_table WHERE id = ?''',(player_id,)).fetchone()
conn.commit() # commit commands
conn.close() # close connection to database
# record_info[1:] represents num_bosses_defeated
return player_info + record_info[1:]
@classmethod
def get_record_info(cls, player_id, database=db_constants.DATABASE_PATH):
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
record_info = c.execute('''SELECT * FROM record_table WHERE id = ?''',(player_id,)).fetchone()
conn.commit() # commit commands
conn.close() # close connection to database
return record_info
@classmethod
def get_monster_info(cls, monster_id, database=db_constants.DATABASE_PATH):
"""
Returns a specific mosnter's information
:param monster_id: the monster_id
:return: (tuple) of monster info or None if monster does not exist in database
monster info format = (id, row, col, health, power, is_boss, defeated_by)
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Query for monster information
monster_info = c.execute('''SELECT * FROM monster_table WHERE id = ?;''',(monster_id,)).fetchone()
conn.commit() # commit commands
conn.close() # close connection to database
return monster_info
@classmethod
def delete_monster(cls, monster_id, database=db_constants.DATABASE_PATH):
"""
Delete the entry with monster_id in the monster table if the monster exists
:param monster_id: the monster id to delete
:return: None
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Delete monster from monster table with given id
c.execute('''DELETE FROM monster_table WHERE id = ?;''',(monster_id,))
conn.commit() # commit commands
conn.close() # close connection to database
@classmethod
def delete_player(cls, player_id, database=db_constants.DATABASE_PATH):
"""
Delete the entry with player_id in the player table if the player exists
:param player_id: the player id to delete
:return:
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Delete player from player table with given id
c.execute('''DELETE FROM player_table WHERE id = ?;''',(player_id,))
conn.commit() # commit commands
conn.close() # close connection to database
@classmethod
def delete_tables(cls, database=db_constants.DATABASE_PATH):
"""
DANGER AHEAD! Deletes the game database if it exists
:return: None
"""
conn = sqlite3.connect(database) # connect to that database (will create if it doesn't already exist)
c = conn.cursor() # make cursor into database (allows us to execute commands)
# Delete the database
c.execute(
'''DROP TABLE IF EXISTS player_table'''
)
c.execute(
'''DROP TABLE IF EXISTS monster_table'''
)
c.execute(
'''DROP TABLE IF EXISTS record_table'''
)
conn.commit() # commit commands
conn.close() # close connection to database
class Deserialize:
"""
This class contains class methods that deserialize objects from the database
"""
@classmethod
def createPlayerObject(cls, player_info):
"""
Returns a Player object using player_info
:param player_info: (tuple) of (id, row, col, health, power, gold, num_bosses_defeated)
:return: a new Player object
"""
id, row, col, health, power, luck, gold, num_bosses_defeated = player_info
return Player(id, row, col, health, power, luck, gold, num_bosses_defeated)
@classmethod
def createMonsterObject(cls, monster_info):
"""
Returns a Monster object using monster_info
:param monster_info: (tuple) of (id, row, col, health, power, is_boss, defeated_by)
:return: a new Monster object
"""
id, row, col, health, power, is_boss, defeated_by = monster_info
is_boss = eval(is_boss) # is_boss was a string of "True" or "False"
defeated_by = eval(defeated_by) # convert from string to set
return Monster(id, row, col, health, power, is_boss, defeated_by)
@classmethod
def createGameFromDatabase(cls, map_path=db_constants.MAP_PATH, database=db_constants.DATABASE_PATH):
"""
Creates and returns a new Game object that contains all game objects in the database
:return: new Game object populated with all game objects in the database
"""
with open(map_path) as f:
map_data = json.load(f)
rows, columns = map_data['rows'], map_data['columns']
# Get player and monster information
monsters = []
players = []
for monster_info in Database.get_all_monsters(database):
monsters.append(cls.createMonsterObject(monster_info))
for player_info in Database.get_all_players(database):
players.append(cls.createPlayerObject(player_info))
return Game(rows, columns, players, monsters)
@classmethod
def getNumBossesDefeated(cls, player_id, database=db_constants.DATABASE_PATH):
"""
Returns number of bosses the player has defeated
:param player_id: id of the player
:param database: database to look in
:return: number of bosses the player has defeated
"""
record_info = Database.get_record_info(player_id, database)
if not record_info:
return 0
else:
return record_info[1]
@classmethod
def createGameWithinRange(cls, row, col):
"""
Creates and returns a new Game object that only contains game object within range of (row, col)
:param row: (int) current row in the game
:param col: (int) current col in the game
:return: a new Game object populated only with game objects within range
"""
# TODO (if needed for performance reasons): Implement me!
pass
class Serialize:
"""
This class contains class methods to serialize and save objects to the database
"""
@classmethod
def updateMonster(cls, monster, database=db_constants.DATABASE_PATH):
"""
Updates a single monster information in the database
:param monster: (Monster) monster object to be saved
:return: None
:param monster_info: (tuple) of (id, row, col, health, power, is_boss, defeated_by)
"""
id = monster.id
row = monster.row
col = monster.col
health = monster.health
power = monster.power
is_boss = db_constants.FALSE if not monster.is_boss else db_constants.TRUE
defeated_by = repr(monster.defeated_by)
Database.create_or_update_monster(id, row, col, health, power, is_boss, defeated_by, database)
@classmethod
def updatePlayer(cls, player, database=db_constants.DATABASE_PATH):
"""
Updates a single player information in the database
:param Player: (Player) player object to be saved
:return: None
"""
# if the player died, delete the player's entry from the database
if not player.is_alive:
Database.delete_player(player.id, database)
return
# otherwise update the player's information
id = player.id
row = player.row
col = player.col
health = player.health
power = player.power
luck = player.luck
gold = player.gold
num_bosses_defeated = player.num_boss_defeated
Database.create_or_update_player(id, row, col, health, power, luck, gold, num_bosses_defeated, database)
@classmethod
def updateGameObjects(self, game_objects, database=db_constants.DATABASE_PATH):
"""
Updates the provided game_objects in the database
:param game_objects: (list) of game objects that require updating
:return: None
"""
for game_object in game_objects:
if isinstance(game_object, Monster):
self.updateMonster(game_object, database)
elif isinstance(game_object, Player):
self.updatePlayer(game_object, database)
if __name__ == "__main__":
if constants.TESTING:
"""
import reset_game_database
reset_game_database.resetDatabase()
print(Database.get_all_monsters())
players = [
Player("Lucian", 0, 0, 100, 5, 2, 1),
Player("Caitlyn", 1, 1),
Player("Teemo", 2, 4),
Player("Ze", 4, 2, 200, 50, 50, 10)
]
monsters = [
Monster("Crab", 0, 0, 100, 100, False, {"Lucian"}),
]
Serialize.updateGameObjects(players+monsters)
print(Database.get_all_players())
"""
pass