-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
841 lines (636 loc) · 23.6 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
import pymongo, os, json, re
from shutil import rmtree
from bson.json_util import dumps
import engine as eng
# setup saves path
savesPath = "./save-states"
if not os.path.exists(savesPath):
os.makedirs(savesPath)
# Setup database connection
client = pymongo.MongoClient("mongodb://root:kjZbFF5jMQL2sPS4vyRYgbW#CEt#2cDA@172.200.0.121:27017/")
# define empty variables
equippedInstrument = None
equippedHead = None
addedFX = None
# define function to remove a save slot
def deleteSave(n, rm):
# try to delete the db
try:
client.drop_database(n)
# if the drop failed, return False
except:
return False
# otherwise setup the dblist
dbList = list(client.list_database_names())
# check if the database is still there or not, and raise an exception if it is
if n in dbList:
raise Exception("MongoDB Error: '{0}' didn't get dropped.".format(n))
# if the local folders should be removed, do it
if rm == True:
path = "{0}/{1}".format(savesPath, n)
if os.path.exists(path):
rmtree(path)
# return true if all is successful
return True
# function to set a new location
def setLocation(n):
# define globals
global locationInfo
global ROOM
global SECTOR
global PLANET
# set the new location in payer's db
player.update_one( { "SECTION": "location" }, { "$set": { "ROOM": n } } )
# if the new location is a sector, load the space location
if n.endswith("Sector"):
locationInfo = locations.find_one( { "NAME": "Space" } )
# otherwise just load the location
else:
locationInfo = locations.find_one( { "NAME": n } )
# set easy to reference vars
ROOM = locationInfo["NAME"]
if ROOM == "Space":
SECTOR = locationInfo["SECTOR"]
else:
PLANET = locationInfo["PLANET"]
SECTOR = planets.find_one( { "PLANET": PLANET } )["SECTOR"]
# update the player's db
player.update_one( { "SECTION": "location" }, { "$set": { "PLANET": PLANET } } )
player.update_one( { "SECTION": "location" }, { "$set": { "SECTOR": SECTOR } } )
# function to define a new location in Space
def setSpaceLocation(sector):
# define globals
global locationInfo
global ROOM
global SECTOR
global PLANET
# first set the player's new location
player.update_one( { "SECTION": "location" }, { "$set": { "ROOM": "Space" } } )
player.update_one( { "SECTION": "location" }, { "$set": { "SECTOR": sector } } )
locations.update_one( { "NAME": "Space" }, { "$set": { "SECTOR": sector } } )
# store the new data
locationInfo = locations.find_one( { "NAME": "Space" } )
# setup easy to reference vars from new info
ROOM = locationInfo["NAME"]
if ROOM == "Space":
SECTOR = locationInfo["SECTOR"]
else:
PLANET = locationInfo["PLANET"]
SECTOR = planets.find_one( { "PLANET": PLANET } )["SECTOR"]
# get latest info for current location
def updateLocation():
# define globals
global locationInfo
# get the location from player's db
locationInfo = locations.find_one( { "NAME": ROOM } )
# function to load a new location into memory
def loadLocation(n):
# define globals
global locationInfo
global ROOM
global SECTOR
global PLANET
# get the location from player's db
locationInfo = locations.find_one( { "NAME": n } )
# setup easy to reference vars from the new info
ROOM = locationInfo["NAME"]
if ROOM == "Space":
SECTOR = locationInfo["SECTOR"]
else:
PLANET = locationInfo["PLANET"]
SECTOR = planets.find_one( { "PLANET": PLANET } )["SECTOR"]
# equip a new instrument
def setInstrument(n):
# define globals
global equippedInstrument
global instrumentInfo
# if the current value is empty, set it to Fists
if equippedInstrument is None:
equippedInstrument = "Fists"
# if the current value isn't Fists, then remove the new item from equipped and add to reg inventory
if equippedInstrument != "Fists":
player.update_one( { "SECTION": "inventory" }, { "$pull": { "EQUIPPED": equippedInstrument } } )
player.update_one( { "SECTION": "inventory" }, { "$push": { "ITEMS": equippedInstrument } } )
# setup new item as equipped
player.update_one( { "SECTION": "equipped" }, { "$set": { "INSTRUMENT": n } } )
# if the new value isn't Fists, then add the new item to equipped and remove from reg inventory
if n != "Fists":
player.update_one( { "SECTION": "inventory" }, { "$push": { "EQUIPPED": n } } )
player.update_one( { "SECTION": "inventory" }, { "$pull": { "ITEMS": n } } )
# setup global vars with new info
equippedInstrument = player.find_one( { "SECTION": "equipped" } )["INSTRUMENT"]
instrumentInfo = items.find_one( {"NAME": equippedInstrument } )
# equip a new head piece
def setHead(n):
# define globals
global equippedHead
global headInfo
# if the current value is empty, set noFX
if equippedHead is None:
equippedHead = "Hair"
# if the current value is not noFX, pull the old item from the player's equipped section and put it in reg inventory
if equippedHead != "Hair":
player.update_one( { "SECTION": "inventory" }, { "$pull": { "EQUIPPED": equippedHead } } )
player.update_one( { "SECTION": "inventory" }, { "$push": { "ITEMS": equippedHead } } )
# add the new item to the player's equipped section
player.update_one( { "SECTION": "equipped" }, { "$set": { "HEAD": n } } )
# if the new item isn't noFX, then add it to the equipped section and remove from reg inventory
if n != "Hair":
player.update_one( { "SECTION": "inventory" }, { "$push": { "EQUIPPED": n } } )
player.update_one( { "SECTION": "inventory" }, { "$pull": { "ITEMS": n } } )
# set global vars with new info
equippedHead = player.find_one( { "SECTION": "equipped" } )["HEAD"]
headInfo = items.find_one( {"NAME": equippedHead } )
# equip a new FX pedal
def setFX(n):
# define globals
global addedFX
global fxInfo
# if the current value is empty, set noFX
if addedFX is None:
addedFX = "noFX"
# if the current value is not noFX, pull the old item from the player's equipped section and put it in reg inventory
if addedFX != "noFX":
player.update_one( { "SECTION": "inventory" }, { "$pull": { "EQUIPPED": addedFX } } )
player.update_one( { "SECTION": "inventory" }, { "$push": { "ITEMS": addedFX } } )
# add the new item to the player's equipped section
player.update_one( { "SECTION": "equipped" }, { "$set": { "FX": n } } )
# if the new item isn't noFX, then add it to the equipped section and remove from reg inventory
if n != "noFX":
player.update_one( { "SECTION": "inventory" }, { "$push": { "EQUIPPED": n } } )
player.update_one( { "SECTION": "inventory" }, { "$pull": { "ITEMS": n } } )
# set gobal vars with new info
addedFX = player.find_one( { "SECTION": "equipped" } )["FX"]
fxInfo = items.find_one( {"NAME": addedFX } )
# function to store current inventory in memory
def getInventory():
global playerInv
global playerEquip
playerInv = player.find_one( { "SECTION": "inventory" } )
playerEquip = player.find_one( { "SECTION": "equipped" } )
# function to store latest player info to memory
def getStats():
# define globals
global playerStats
global levelStats
# setup vars
playerStats = player.find_one( { "SECTION": "stats" } )
levelStats = levels.find_one( { "LEVEL": playerStats["LVL"] } )
# function to store the enemy's info into memory
def getEnemyInfo(name):
# define globals
global enemyInfo
global challengeRatingStats
# setup vars
enemyInfo = enemies.find_one( { "NAME": name } )
challengeRatingStats = challenge_ratings.find_one( { "RATING": enemyInfo["CR"] } )
# function to get a dict from the player's stats
def getPlayerDict():
# refresh player info
getStats()
getInventory()
# setup the player dict
calcs = {
"HP": {
"MAX": 0,
"CUR": 0
},
"MP": {
"MAX": 0,
"CUR": 0
},
"ATK": {
"BASE": 0,
"BONUS": 0
},
"DEF": {
"BASE": 0,
"BONUS": 0
},
"MOJO": {
"BASE": 0,
"BONUS": 0
},
"LUK": {
"BASE": 0,
"BONUS": 0
},
"ACC": {
"BASE": 0,
"BONUS": 0
}
}
# set current HP/MP and maxes
for s in [ "HP", "MP" ]:
smax = "{0}MAX".format(s)
calcs[s]["MAX"] = playerStats[smax]
calcs[s]["CUR"] = playerStats[s]
# run through each stat
for s in eng.STATS:
# get the base value
val = playerStats[s]
# add all equipment bonuses together
bonuses = instrumentInfo["BONUS"][s] + fxInfo["BONUS"][s] + headInfo["BONUS"][s]
# add the values to the dict
calcs[s]["BASE"] = val
calcs[s]["BONUS"] = bonuses
# return the dict object
return calcs
# function to get a dict from the enemy's stats
def getEnemyDict():
# run through each stat, setup dict for later
calcs = {
"HP": {
"MAX": 0,
"CUR": 0
},
"MP": {
"MAX": 0,
"CUR": 0
},
"ATK": 0,
"DEF": 0,
"MOJO": 0,
"LUK": 0,
"ACC": 0
}
# set HP/MP
for s in [ "HP", "MP" ]:
calcs[s]["MAX"] = enemyInfo[s]
calcs[s]["CUR"] = enemyInfo[s]
# set other stats
for s in eng.STATS:
# if the stat has a bonus value in the enemy's document, add it
if s in enemyInfo:
c = challengeRatingStats[s] + enemyInfo[s]
# otherwise just set the base CR stat
else:
c = challengeRatingStats[s]
# add the calc to the list
calcs[s] = c
# return the dict object
return calcs
# function to update ground items in a room
def updateGround(item, action):
# check if we're in the winnie or not
if ROOM.lower() in [ "winnibego", "space" ] or ROOM.endswith("Sector"):
space = True
else:
space = False
# if asked to delete, remove item from ground
if action == "del":
# set the groundList
if space is True:
groundList = list(playerInv["WINNIE"])
else:
groundList = list(locations.find_one( { "NAME": ROOM } )["GROUND"])
# if the item is in the ground list, remove it
if item in groundList:
groundList.remove(item)
# set the update list as the new value
if space is True:
player.update_one( { "SECTION": "inventory" }, { "$set": { "WINNIE": groundList } } )
else:
locations.update_one( { "NAME": ROOM }, { "$set": { "GROUND": groundList } } )
# if asked to add, add the item to the ground
elif action == "add":
# set a temp ground list and add the item
if space is True:
groundList = list(playerInv["WINNIE"])
else:
groundList = list(locationInfo["GROUND"])
groundList.append(item)
# set the new value as the list
if space is True:
player.update_one( { "SECTION": "inventory" }, { "$set": { "WINNIE": groundList } } )
else:
locations.update_one( { "NAME": ROOM }, { "$set": { "GROUND": groundList } } )
# set a new list from the database
if space is True:
groundList = list(player.find_one( { "SECTION": "inventory" } )["WINNIE"])
else:
groundList = list(locations.find_one( { "NAME": ROOM } )["GROUND"])
# if the item doesn't exist for some reason, raise an exception
if item not in groundList:
raise Exception("'{0}' doesn't exist on the ground.".format(item))
return
# otherwise let the player know I messed up somewhere when calling this function
else:
raise Exception("FUNCTION CALL BUG: Someone forgot to specify an action for updateGround()")
# run a function to rewrite the room
setLocation(ROOM)
# function to update the player's inventory
def updateInv(item, action):
# define globals
global playerInv
# refresh inventory info
getInventory()
# if asked to delete
if action == "del":
# setup temp inventory lists
i = list(playerInv["ITEMS"])
k = list(playerInv["KEY_ITEMS"])
e = list(playerInv["EQUIPPED"])
# if the item is in the regular list
if item in i:
# remove the item
i.remove(item)
# update the db
player.update_one( { "SECTION": "inventory" }, { "$set": { "ITEMS": i } } )
# if the item is in the key item list
elif item in k:
# remove the item
k.remove(item)
# update the db
player.update_one( { "SECTION": "inventory" }, { "$set": { "KEY_ITEMS": k } } )
# if the item is in the equipped slot
elif item in e:
# remove the item
e.remove(item)
# update the db
player.update_one( { "SECTION": "inventory" }, { "$set": { "EQUIPPED": e } } )
# otherwise, let the player know I messed something up when calling this function
else:
raise NameError("Cannot find item in any list.")
# refresh inventory info again
getInventory()
# if asked to add
elif action == "add":
# if the item is a key item
if items.find_one( { "NAME": item } )["TYPE"] == "key":
# add it to the key item list in player db
player.update_one( { "SECTION": "inventory" }, { "$push": { "KEY_ITEMS": item } } )
# refresh inventory info
getInventory()
# if for some reason the item doesn't appear in the key list in player db, raise an exception
if item not in list(playerInv["KEY_ITEMS"]):
raise Exception("'{0}' is not in Ted's inventory.".format(item))
# otherwise just add the item to the regular inventory list
else:
player.update_one( { "SECTION": "inventory" }, { "$push": { "ITEMS": item } } )
# refresh inventory info
getInventory()
# if for some reason the item doesn't appear in the key list in player db, raise an exception
if item not in list(playerInv["ITEMS"]):
raise Exception("'{0}' is not in Ted's inventory.".format(item))
# otherwise let the player know I forgot to specify an action
else:
raise Exception("FUNCTION CALL BUG: Someone forgot to specify an action for updateInv()")
# function to update a player's stat
def updateStat(stat, num, action):
# define globals
global playerStats
# refresh stat info
getStats()
# set a temp var of the current stat value
temp = int(playerStats[stat])
# if asked to increase
if action == "inc":
# increase the stat
temp += int(num)
# set the new value
player.update_one( { "SECTION": "stats" }, { "$set": { stat : temp } } )
# if asked to decrease
elif action == "dec":
# decrease the stat
temp -= int(num)
# set the new value
player.update_one( { "SECTION": "stats" }, { "$set": { stat : temp } } )
# if asked to set
elif action == "set":
# set the new value with no calculation
player.update_one( { "SECTION": "stats" }, { "$set": { stat : num } } )
# otherwise let the player know I forgot to define an action
else:
raise Exception("FUNCTION CALL BUG: Someone forgot to specify an action for updateStat()")
# refresh stat info
getStats()
# function specifically for money transactions
def floydsTransaction(num, action):
# define globals
global playerStats
# refresh stat info
getStats()
# set the current amount of floyds
floyds = int(playerStats["FLOYDS"])
# if asked to increase, add the new value
if action == "inc":
floyds += num
# if asked to decrease
elif action == "dec":
# and the player has enough floyds, decrease the stat
if floyds >= num:
floyds -= num
# and the player doesn't have enough floyds, return False
elif floyds < num:
return False
# if asked to set
elif action == "set":
# set the new value
floyds = num
# update the player db
player.update_one( { "SECTION": "stats" }, { "$set": { "FLOYDS": floyds } } )
# refresh stat info
getStats()
# return True if all is successful
return True
# function to set paths and collections
def define(n):
# define globals
global db
global abilities
global challenge_ratings
global enemies
global items
global locations
global player
global levels
global planets
global playerPath
global playerInv
# setup new save directory
playerPath = "{0}/{1}".format(savesPath, n)
if not os.path.exists(playerPath):
os.makedirs(playerPath)
else:
pass
# define collections
db = client[n]
abilities = db['abilities']
challenge_ratings = db['challenge_ratings']
enemies = db['enemies']
items = db['items']
locations = db['locations']
player = db['player']
levels = db["levels"]
planets = db["planets"]
# set SLOT_NAME variable
eng.SLOT_NAME = n
# save current game state to the database
def saveGame():
# iterate through collections to dump the current db state
# get and store the collection list
collections = []
for o in os.listdir(playerPath):
f = o.replace(".json", "")
collections.append(f)
# try to run the save function
try:
# for each collection found
for n in collections:
# set the collection up
col = db[n]
# define the new file, and remove if it already exists
newFile = "{0}/{1}.json".format(playerPath, n)
if os.path.exists(newFile):
os.remove(newFile)
else:
pass
# get all docs in the collection
cursor = col.find({})
# wait for the file operation to finish
with open(newFile, 'w') as f:
# dump all the docs to file
json.dump(json.loads(dumps(cursor)), f)
f.close()
# reset the variable in case it was set already
content_new = ""
# wait for file to operation to finish
with open(newFile, 'r') as f:
# get the current contents
content = f.read()
# regex to replace the mongo $oid method in the dumped json to just their IDs so mongo will be able to import this later
content_new = re.sub('(\{"\$oid": )("[A-Za-z0-9]{24}")(\})', r'\2', content, flags = re.M)
f.close()
# empty the current file
with open(newFile, 'w') as f:
f.close()
# write the new edited text to the file
with open(newFile, 'w') as f:
f.write(content_new)
f.close()
# set a success message for the player
message = [ "Game data was saved!", "GREEN" ]
# if anything goes wrong, set a failure message for the player
except:
message = [ "Something went wrong when trying to save.", "RED" ]
# return the message
return message
# function to load game state from database
def loadGame(name):
# define globals
global equipment
global playerInv
# remove old save db if it exists
client.drop_database(name)
# setup new save data
define(name)
# get and store the collection list
collections = []
for o in os.listdir(playerPath):
f = o.replace(".json", "")
collections.append(f)
# for each collection found
for n in collections:
# define the collection
col = db[n]
# set the file path
initFile = "{0}/{1}.json".format(playerPath, n)
# wait on file operations to finish
with open(initFile) as f:
# load the file
file_data = json.load(f)
f.close()
# use _many or _one based on amount of docs in the json
if isinstance(file_data, list):
col.insert_many(file_data)
else:
col.insert_one(file_data)
# load inv into memory
getInventory()
# load player's equipment to memory
equipment = player.find_one( { "SECTION": "equipped" } )
setInstrument(equipment["INSTRUMENT"])
setFX(equipment["FX"])
setHead(equipment["HEAD"])
# load player's location to memory
locationName = player.find_one( { "SECTION": "location" } )["ROOM"]
loadLocation(locationName)
# function to create new database and set initial values
def newGame(name):
# define globals
global equipment
# remove old save data
deleteSave(name, True)
# setup new save data
define(name)
# get and store the new collection names
collections = []
for o in os.listdir("./json"):
# ignore the README
if o.endswith("README.md"):
pass
else:
f = o.replace(".json", "")
collections.append(f)
# for each json file found
for n in collections:
# if the name is a location, we need to consolidate the docs into one collection called locations
if n.startswith("locations_"):
col = db['locations']
newName = "locations"
# otherwise use the filename as the collection name
else:
col = db[n]
newName = n
# set the init files' path
initFile = "./json/{0}.json".format(n)
# wait for file operations to complete
with open(initFile) as f:
# load the json file
file_data = json.load(f)
f.close()
# use _many or _one based on number of docs in the json
if isinstance(file_data, list):
col.insert_many(file_data)
else:
col.insert_one(file_data)
# define new player filepath
newFile = "{0}/{1}.json".format(playerPath, newName)
if os.path.exists(newFile):
os.remove(newFile)
else:
pass
# get a list of all the docs in the new collection
cursor = col.find({})
# wait for file operations to complete
with open(newFile, 'w') as f:
# dump the new collection into the player's file
json.dump(json.loads(dumps(cursor)), f)
f.close()
# reset the variable in case it was already set
content_new = ""
# wait for file operations to complete
with open(newFile, 'r') as f:
# load the current content into memory
content = f.read()
# replace mongo's $oid method with just the _id so mongo can load this later
content_new = re.sub('(\{"\$oid": )("[A-Za-z0-9]{24}")(\})', r'\2', content, flags = re.M)
f.close()
# empty the file
with open(newFile, 'w') as f:
f.close()
# write the edited text to the file
with open(newFile, 'w') as f:
f.write(content_new)
f.close()
# set player's inventory
getInventory()
# set player's equipment
equipment = player.find_one( { "SECTION": "equipped" } )
setInstrument(equipment["INSTRUMENT"])
setFX(equipment["FX"])
setHead(equipment["HEAD"])
# set player's location
locationName = player.find_one( { "SECTION": "location" } )["ROOM"]
loadLocation(locationName)