Skip to content

Commit

Permalink
Merge pull request #142 from GDcheeriosYT/fix-everything
Browse files Browse the repository at this point in the history
fixed gentry's quest db
  • Loading branch information
GDcheeriosYT authored Oct 27, 2024
2 parents 248dc28 + c58239b commit f24febf
Show file tree
Hide file tree
Showing 9 changed files with 330 additions and 109 deletions.
5 changes: 0 additions & 5 deletions crap/Initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ def verify_file(file_name: str):
file.write("{}")
file.close()

verify_dir("matches")
verify_dir("extras")
verify_dir("match_history")
verify_file("player_data.json")


def retrieve_initialized_objects():
pass
Expand Down
152 changes: 134 additions & 18 deletions crap/gentrys_quest_crap/GQManager.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,151 @@
import json

from GPSystem.GPmain import GPSystem
from crap.PSQLConnection import PSQLConnection as DB
from crap.gentrys_quest_crap.Item import Item


def ranking(func):
def wrapper(*args, **kwargs):
item: Item = func(*args, **kwargs)
if not item.deleted:
item.rank_item()

if item.is_classic:
result = GQManager.update_user_rating(item.owner, True)
else:
result = GQManager.update_user_rating(item.owner, False)

details = {
'item': item.jsonify(),
'user': result
}

return details

return wrapper


class GQManager:
@staticmethod
def load_rankings():
version = GPSystem.version
print("Loading rankings")
print("#1 Rating items")
rater = GPSystem.rater
items = DB.get_group("SELECT id, type, owner, metadata, version FROM gentrys_quest_items;")
for item in items:
if item[4] != version: # check the version
if item[4] != GPSystem.version: # check the version
if item[1] == "character":
rating = rater.get_character_rating(item[3])
rating = GPSystem.rater.get_character_rating(item[3])
elif item[1] == "artifact":
rating = rater.get_artifact_rating(item[3])
rating = GPSystem.rater.get_artifact_rating(item[3])
else:
rating = rater.get_weapon_rating(item[3])
rating = GPSystem.rater.get_weapon_rating(item[3])

DB.do(f"UPDATE gentrys_quest_items SET rating = {rating}, version = \'{version}\' where id = {item[0]}")
DB.do(
f"UPDATE gentrys_quest_items SET rating = {rating}, version = \'{GPSystem.version}\' where id = {item[0]}")

print("#2 Ranking users (classic)")
for id in DB.get_group("SELECT distinct owner FROM gentrys_quest_items where is_classic = true;"):
id = id[0]
GQManager.update_rating(id, True)
GQManager.update_user_rating(id, True)

print("#2 Ranking users (current)")
for id in DB.get_group("SELECT distinct owner FROM gentrys_quest_items where is_classic = false;"):
id = id[0]
GQManager.update_rating(id, False)
GQManager.update_user_rating(id, False)

@staticmethod
def update_rating(id, classic: bool) -> None:
def update_user_rating(id, classic: bool) -> dict:
# weighting
weighted = (GQManager.get_weighted_rating(id, "character", classic) +
GQManager.get_weighted_rating(id, "artifact", classic) +
GQManager.get_weighted_rating(id, "weapon", classic))
DB.do(f"UPDATE rankings SET {'c_weighted' if classic else 'weighted'} = %s WHERE id = %s;",
params=(weighted, id)) # weighted

DB.do(
f"UPDATE rankings SET {'c_unweighted' if classic else 'unweighted'} = (SELECT SUM(rating) FROM gentrys_quest_items WHERE owner = %s) WHERE id = %s;",
params=(id, id)) # unweighted
"""
INSERT INTO rankings (id, weighted, unweighted, c_weighted, c_unweighted)
VALUES (%s, %s, (SELECT SUM(rating) FROM gentrys_quest_items WHERE owner = %s), 0, 0)
ON CONFLICT (id) DO UPDATE
SET
weighted = EXCLUDED.weighted,
c_weighted = CASE
WHEN EXCLUDED.id IS NOT NULL AND %s THEN EXCLUDED.weighted
ELSE rankings.c_weighted
END,
unweighted = (SELECT SUM(rating) FROM gentrys_quest_items WHERE owner = EXCLUDED.id);
""",
params=(id, weighted, id, classic)
)

return GQManager.get_ranking(id, classic)

@staticmethod
@ranking
def update_item(id: int, data):
return Item.update_to_init(id, data)

@staticmethod
@ranking
def add_item(item_type: str, data, is_classic: bool, owner: int):
return Item.create_item(item_type, data, is_classic, owner)

@staticmethod
@ranking
def remove_item(id: int):
return Item.remove(id)

@staticmethod
def remove_items(id_list: list):
for id in id_list:
GQManager.remove_item(id)

@staticmethod
def submit_classic_data(id: int, start_amount: int, money: int):
DB.do("""
INSERT INTO gentrys_quest_classic_data (id, startup_amount, money)
VALUES (%s, %s, %s)
ON CONFLICT (id)
DO UPDATE SET startup_amount = EXCLUDED.startup_amount, money = EXCLUDED.money
""", params=(id, start_amount, money))

return ":thumbs_up:"

# <editor-fold desc="getters">

@staticmethod
def get_rating(id):
raise NotImplementedError

# </editor-fold>
@staticmethod
def get_item(id) -> Item:
return Item(id)

@staticmethod
def get_data(id, is_classic: bool) -> dict:
data = {}
items = DB.get_group(
"""
SELECT id, type, metadata
FROM gentrys_quest_items WHERE owner = %s AND is_classic = %s
""",
params=(id, is_classic)
)

startup_amount = 0
money = 0

if is_classic:
selection = DB.get("SELECT startup_amount, money FROM gentrys_quest_classic_data WHERE id = %s",
params=(id,))
if selection:
startup_amount = selection[0]
money = selection[1]

data["startup amount"] = startup_amount
data["money"] = money
data["items"] = items

return data

@staticmethod
def get_weighted_rating(id, object_type: str, classic: bool) -> int:
Expand All @@ -67,11 +163,31 @@ def get_weighted_rating(id, object_type: str, classic: bool) -> int:
def get_leaderboard(classic: bool, start: int = 0, amount: int = 50) -> list:
mode = 'c_weighted' if classic else 'weighted'
query = f"""
SELECT rankings.id, accounts.username, rankings.{mode}
FROM rankings
INNER JOIN accounts ON rankings.id = accounts.id
SELECT rankings.id, accounts.username, rankings.{mode}
FROM rankings
INNER JOIN accounts ON rankings.id = accounts.id
ORDER BY {mode} desc
LIMIT %s OFFSET %s;
"""

return DB.get_group(query, params=(amount, start))

@staticmethod
def get_ranking(id: int, classic: bool) -> dict:
mode = 'c_weighted' if classic else 'weighted'
result = DB.get(f"SELECT id, weighted, rank "
"FROM (SELECT id, weighted, RANK() OVER (ORDER BY weighted DESC) AS rank "
"FROM rankings"
") subquery where id = %s", params=(id,))
if result:
return {
'rank': result[2],
'score': result[1]
}

return {
'rank': 0,
'score': 0
}

# </editor-fold>
81 changes: 81 additions & 0 deletions crap/gentrys_quest_crap/Item.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import json

from GPSystem.GPmain import GPSystem
from crap.PSQLConnection import PSQLConnection as DB


class Item:
id = None
type = None
rating = None
is_classic = None
version = None
owner = None
metadata = None

def __init__(self, id: int, deleted: bool = False):
print(f"loading item {id}")
item_result = DB.get("SELECT id, type, rating, is_classic, version, owner, metadata FROM gentrys_quest_items WHERE id = %s", params=(id,))
if not item_result:
print(f"couldn't find item {id}")
return

self.id = id
self.type = item_result[1]
self.rating = item_result[2]
self.is_classic = item_result[3]
self.version = item_result[4]
self.owner = item_result[5]
self.metadata = item_result[6]

self.deleted = deleted

@staticmethod
def update_to_init(id: int, data):
"""
update item then return
"""

new_item = Item(id)
new_item.update(data)
return new_item

@staticmethod
def create_item(item_type: str, data, is_classic: bool, owner: int):
new_item = Item(DB.get("INSERT INTO gentrys_quest_items "
"(type, metadata, is_classic, version, owner) "
"VALUES (%s, %s, %s, %s, %s) "
"RETURNING id",
params=(item_type, data, is_classic, 0, owner))[0])
return new_item

@staticmethod
def remove(id):
new_item = Item(id, True)
DB.do(f"DELETE FROM gentrys_quest_items WHERE ID = %s", params=(id,))
return new_item

def update(self, data):
DB.do("UPDATE gentrys_quest_items SET metadata = %s WHERE id = %s", params=(json.dumps(data), self.id))

def rank_item(self):
if self.type == "character":
rating = GPSystem.rater.get_character_rating(self.metadata)
elif self.type == "artifact":
rating = GPSystem.rater.get_artifact_rating(self.metadata)
else:
rating = GPSystem.rater.get_weapon_rating(self.metadata)

DB.do(
f"UPDATE gentrys_quest_items SET rating = {rating}, version = \'{GPSystem.version}\' where id = {self.id}")

def jsonify(self):
return {
'id': self.id,
'type': self.type,
'rating': self.rating,
'is classic': self.is_classic,
'version': self.version,
'owner': self.owner,
'metadata': self.metadata
}
22 changes: 1 addition & 21 deletions crap/osu_crap/Match.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,24 +50,4 @@ def get_playcount(self, player: Player) -> int:
if self.ended:
return self.final_playcount[pos] - self.initial_playcount[pos]
else:
return player.play_count - self.initial_playcount[pos]

def jsonify(self) -> dict:
team_metadata = {}
nicknames = {}

for team in self.team_data:
team_metadata[team.team_name] = team.jsonify()

for nickname in self.nicknames:
nicknames[nickname.id] = nickname.name

return {
"users": [str(player.id) for player in self.players],
"match name": self.name,
"initial score": self.initial_score,
"initial playcount": self.initial_playcount,
"mode": self.mode,
"team metadata": team_metadata,
"nicknames": nicknames
}
return player.play_count - self.initial_playcount[pos]
21 changes: 0 additions & 21 deletions crap/osu_crap/MatchHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,6 @@ def __init__(self):
self.matches = []
self.old_matches = []

def load(self) -> None:
print("\nLoading osu matches\n")

for file in os.listdir("matches"):
with open(f"matches/{file}", "r") as f:
match_data = json.loads(f.read())
self.matches.append(Match(match_data, False))

for file in os.listdir("match_history"):
with open(f"match_history/{file}", "r") as f:
match_data = json.loads(f.read())
self.old_matches.append(Match(match_data, True))

def unload(self) -> None:
def write_to_file(json_object, file):
json.dump(json_object, file, indent=4)

for match in self.matches:
write_to_file(match.jsonify(), open(f"matches/{match.name}.json", "w"))

def get_match(self, match_name) -> Match:
for match in self.matches:
if match.name == match_name:
Expand All @@ -47,4 +27,3 @@ def end_match(self, match_name: str) -> None:
match.has_ended = True
self.old_matches.append(match)
self.matches.remove(match)
json.dump(match.jsonify(), open(f"match_history/{match.name}.json", "w+"), indent=4)
Loading

0 comments on commit f24febf

Please sign in to comment.