Merge pull request #49 from ThomasRubini/python_refactor

Python refactor
This commit is contained in:
Djalim Simaila 2023-01-15 21:58:02 +01:00 committed by GitHub
commit a8fc8b139d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 425 additions and 296 deletions

View File

@ -1,10 +1,10 @@
import os
import random
import truthseeker.logic.data_persistance.tables as tables
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from sqlalchemy import engine as eg
import random
import truthseeker.logic.data_persistance.tables as tables
url_object = eg.URL.create(
"mariadb+pymysql",
@ -17,41 +17,104 @@ url_object = eg.URL.create(
engine = create_engine(url_object)
session = Session(engine)
def get_text_from_lid(lang,lid) -> str:
def get_text_from_lid(lang: str, lid: int) -> str:
"""
Returns the text linked to a language and a locale id
:param lang: the lang to return the text in
:param lid: the locale id the get the text from
:return: the text associated to the lang and lid
"""
return session.query(tables.Locale).filter_by(LANG=lang, TEXT_ID=lid).one().TEXT
def get_random_place() -> tables.Place:
"""
Returns a random place from the database.
:return: a Place object
"""
return random.choice(session.query(tables.Place).all())
def get_random_npc() -> tables.Npc :
"""
Returns a random npc from the database
:return: a Npc object
"""
return random.choice(session.query(tables.Npc).all())
def get_npc_random_trait_id(npc) -> int:
reactions = session.query(tables.Reaction).filter_by(NPC_ID=npc.NPC_ID).all()
def get_npc_random_trait_id(npc_id: int) -> int:
"""
Returns a random reaction for a given npc
:param npc_id: the npc to get the reaction from
:return: a reaction identified by it's trait id
"""
reactions = session.query(tables.Reaction).filter_by(NPC_ID=npc_id.NPC_ID).all()
reaction = random.choice(reactions)
return reaction.TRAIT_ID
def get_npc_random_answer(npc, QA_TYPE) -> tables.Answer :
answers = session.query(tables.Answer).filter_by(QA_TYPE=QA_TYPE,NPC_ID=npc.NPC_ID).all()
def get_npc_random_answer(npc_id:int, qa_type:int) -> tables.Answer :
"""
Returns a random answser from a given npc and question type
:param npc_id: the npc to get the answer from
:param qa_type: the type of the question
:return: an Answer object
"""
answers = session.query(tables.Answer).filter_by(QA_TYPE=qa_type,NPC_ID=npc_id.NPC_ID).all()
return random.choice(answers)
def get_random_question(QA_TYPE) -> tables.Answer :
answers = session.query(tables.Question).filter_by(QUESTION_TYPE=QA_TYPE).all()
def get_random_question(qa_type: int) -> tables.Question :
"""
Returns a random inspector question from a question type
:param qa_type: the type of the question
:return: a Question object
"""
answers = session.query(tables.Question).filter_by(QUESTION_TYPE=qa_type).all()
return random.choice(answers)
def get_trait_from_text(text):
def get_trait_from_text(text: str) -> int:
"""
Returns the trait_id from its text value
:param text: the text representation of the trait in any lang
:return: the trait_id linked to this text
"""
trait_lid = session.query(tables.Locale).filter_by(TEXT=text).one().TEXT_ID
return session.query(tables.Trait).filter_by(NAME_LID=trait_lid).one().TRAIT_ID
def get_trait_from_trait_id(trait_id):
def get_trait_from_trait_id(trait_id: int) -> tables.Trait:
"""
Gets a Trait object from a trait_id
:param trait_id: the id of the trait to search for
:return: a Trait object
"""
trait = session.query(tables.Trait).filter_by(TRAIT_ID=trait_id).one()
return trait
def get_reaction_description(lang,npc_id,trait_id):
def get_reaction_description(lang,npc_id,trait_id) -> str:
"""
Returns the description of the reaction of a given npc in the language specified by the parametter lang
:param lang: the language to return the description in
:param npc_id: the id of the npc to get the reaction description from
:trait_id: the trait associated to the reaction to get the description from
:return: the description in the given language
"""
desc_lid = session.query(tables.Reaction).filter_by(NPC_ID=npc_id,TRAIT_ID=trait_id).one().DESC_LID
return get_text_from_lid(lang,desc_lid)
def get_traits(lang):
def get_traits(lang: str) -> list:
"""
Returns the list of all possible reactions trait in the given language
:param lang: the lang to return the reactions traits in
:return: a list of string reprensentation of the reactions traits
"""
traits = []
for trait in session.query(tables.Trait).all():
traits.append(get_text_from_lid(lang,trait.NAME_LID))

View File

@ -35,42 +35,36 @@ with Session(engine) as session:
session.add(locale)
session.commit()
print("adding places")
for place in PLACES:
print(place)
session.add(place)
session.commit()
print("adding NPCS")
for npc in NPCS:
print(npc)
session.add(npc)
session.commit()
print("adding trait")
for trait in TRAITS:
print(trait)
session.add(trait)
session.commit()
print("adding questions")
for question in QUESTIONS:
print(question)
session.add(question)
session.commit()
print("adding answers")
for answer in ANSWERS:
print(answer)
session.add(answer)
session.commit()
print("adding reactions")
for reaction in REACTIONS:
print(reaction)

View File

@ -4,6 +4,7 @@ from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
class Locale(Base):
__tablename__ = 'T_LOCALE'
TEXT_ID = Column(Integer, primary_key=True)
@ -18,6 +19,7 @@ class Locale(Base):
def __str__(self):
return f"{self.TEXT_ID} {self.LANG} {self.TEXT}"
class Place(Base):
__tablename__ = 'T_PLACE'
PLACE_ID = Column(Integer, primary_key=True)
@ -31,6 +33,7 @@ class Place(Base):
def __str__(self):
return f"{self.PLACE_ID} {self.NAME_LID}"
class Question(Base):
__tablename__ = "T_QUESTION"
QUESTION_ID = Column(Integer, primary_key=True)
@ -46,6 +49,7 @@ class Question(Base):
def __str__(self):
return f"{self.QUESTION_ID} {self.QUESTION_TYPE} {self.TEXT_LID}"
class Answer(Base):
__tablename__ = "T_ANSWER"
ANSWER_ID = Column(Integer, primary_key=True)
@ -64,6 +68,7 @@ class Answer(Base):
def __str__(self):
return f"{self.ANSWER_ID} {self.QA_TYPE} {self.NPC_ID} {self.TEXT_LID}"
class Npc(Base):
__tablename__ = "T_NPC"
NPC_ID = Column(Integer, primary_key=True)
@ -76,6 +81,7 @@ class Npc(Base):
def __str__(self) -> str:
return f"{self.NPC_ID} {self.NAME_LID}"
class Trait(Base):
__tablename__ = "T_TRAIT"
TRAIT_ID = Column(Integer, primary_key=True)
@ -88,6 +94,7 @@ class Trait(Base):
def __str__(self) -> str:
return f"{self.TRAIT_ID} {self.NAME_LID}"
class Reaction(Base):
__tablename__ = "T_REACTION"
REACTION_ID = Column(Integer, primary_key=True)

View File

@ -5,6 +5,7 @@ from typing import Union
from truthseeker.logic.data_persistance.data_access import *
from truthseeker import APP
def random_string(length: int) -> str:
"""
This function create a random string as long as the lint passed as
@ -15,6 +16,7 @@ def random_string(length: int) ->str:
"""
return "".join(random.choice(string.ascii_letters) for _ in range(length))
class Member:
"""
stores information related to the member of a given game
@ -30,21 +32,22 @@ class Member:
self.results = None
def __str__(self) -> str:
return "Member[username={}]".format(self.username)
return f"Member[username={self.username}]"
def __repr__(self) -> str:
return self.__str__()
class Game:
"""
The game info class stores all information linked to a active game
:attr str game_id: str, the game identifier of the game
:attr str game_id: the game identifier of the game
:attr owner Member: the player start created the game. It is also stored in self.members
:attr Member[] members: the members of the game
:attr bool has_started: TODO
:attr TODO gamedata: TODO
:attr TODO reaction_table: TODO
:attr bool has_started: status of the current game
:attr dict gamedata: data of the game (npcs, their text, their reactions and rooms placement)
:attr dict reaction_table: mapping of the npc_ids in the game to their reactions id
"""
def __init__(self):
@ -66,17 +69,19 @@ class Game:
self.members.append(self.owner)
return self.owner
def generate_game_results(self) -> None:
def generate_game_results(self) -> dict:
"""
TODO + TODO RET TYPE
Create the final leaderboard of the game, containing all members score.
:return: a dictionnary representation of the leaderboard
"""
data = {}
npcs = data["npcs"] = {}
for npc_id in self.gamedata["npcs"]:
npcs[npc_id] = {}
npcs[npc_id]["name"] = self.gamedata["npcs"][npc_id]["name"]
traitId = self.reaction_table[npc_id]
trait = get_trait_from_trait_id(traitId)
trait_id = self.reaction_table[npc_id]
trait = get_trait_from_trait_id(trait_id)
npcs[npc_id]["reaction"] = get_text_from_lid("FR", trait.NAME_LID)
npcs[npc_id]["description"] = get_reaction_description("FR", npc_id, trait.TRAIT_ID)
player_results = data["player"] = {}
@ -86,7 +91,7 @@ class Game:
def generate_data(self) -> None:
"""
TODO
Creates and sets the game's data (npcs, their text, their reactions and rooms placement)
"""
# TODO Get language from player
self.gamedata, self.reaction_table = generate_game_data("FR")
@ -97,7 +102,7 @@ class Game:
Get a Member object from a username
:param username: the username of the member to search for
:return the member corresponding to the username, or None if none if found:
:return: the member corresponding to the username, or None if none if found:
"""
for member in self.members:
if member.username == username:
@ -116,18 +121,25 @@ class Game:
self.members.append(member)
return member
def get_npc_reaction(self, npc_id) -> None:
def get_npc_reaction(self, npc_id) -> bytes:
"""
TODO + TODO TYPES
Returns the reaction image of a npc, if found in the reaction table
:param npc_id: the id of the npc, to get the reactions from, must be in the current game
:return: the reaction image as bytes
"""
if npc_id not in self.reaction_table.keys():
if npc_id not in self.reaction_table:
return 0
reaction_id = self.reaction_table[npc_id]
return read_image(f"./truthseeker/static/images/npc/{npc_id}/{reaction_id}.png")
def get_player_results(self, responses: dict) -> None:
def get_player_results(self, responses: dict) -> Union[dict, None]:
"""
TODO + TODO RETTYPE
Checks the player's answers againts the reaction map.
Return None when a npc is not found in the reaction table, meaning an invalid npc was sent
:param responses: the player anwsers, a dictionnary of npc_id to the string representation of the npc's reaction
:return: a dictionnary of npc_id to a boolean, true if they got the correct answer, false if not.
"""
results = {}
try:
@ -138,7 +150,6 @@ class Game:
except:
return False
def has_finished(self) -> bool:
"""
Checks if the game has finished by checking if every Member has submitted answers
@ -146,15 +157,17 @@ class Game:
:return: True if the game has finished, else False
"""
for member in self.members:
if member.results == None : return False
if member.results is None:
return False
return True
def __str__(self) -> str:
return "Game[game_id={}, owner={}, members={}]".format(self.game_id, self.owner, self.members)
return f"Game[game_id={self.game_id}, owner={self.owner}, members={self.members}]"
def __repr__(self) -> str:
return self.__str__()
def create_game(owner: str) -> Game:
"""
This function creates a new game by creating a Game object and stores
@ -169,6 +182,7 @@ def create_game(owner: str) -> Game:
APP.games_list[game.game_id] = game
return game
def get_game(game_id: str) -> Union[Game, None]:
"""
Get a game from its ID
@ -181,6 +195,7 @@ def get_game(game_id: str) -> Union[Game, None]:
else:
return None
def check_username(username: str) -> bool:
"""
Check if a username is valid using a set of rules
@ -200,30 +215,55 @@ def check_username(username: str) -> bool:
return True
def generate_npc_text(npc: tables.Npc, lang: str) -> dict:
"""
Creates the dictionnary of a npc names and dialogs, it searches the npc's pool of answser for both question
types
:param npc: a Npc object
:param lang: the lang to get the text in
:return: a dictionnary object containing the npc's name and both answers
"""
data = {}
data["name"] = get_text_from_lid(lang, npc.NAME_LID)
data["QA_0"] = get_text_from_lid(lang, get_npc_random_answer(npc, 0).TEXT_LID)
data["QA_1"] = get_text_from_lid(lang, get_npc_random_answer(npc, 1).TEXT_LID)
return data
def generate_npc_reactions(npc: tables.Npc) ->list:
return get_npc_random_trait_id(npc)
def generate_place_data(npcs: list, places: list, lang: str) -> dict:
def generate_place_data(npc_list: list, places: list, lang: str) -> dict:
"""
Create the place dictionnary for a game, assigns two npc for each room given in the place_list
except the last one who will be alone :(
:param npcs_list: the list of all npcs in the game
:param place_list: the list of the given rooms
:param lang: the language to seach the name of the room in
:return: a dictionnary of place_id to an array of npc_id and a string of the room name
"""
data = {}
random.shuffle(npcs)
random.shuffle(npc_list)
for place in places:
placedata = data[str(place.PLACE_ID)] = {}
placedata["name"] = get_text_from_lid(lang, place.NAME_LID)
placedata["npcs"] = []
for _ in npcs:
placedata["npcs"].append(npcs.pop().NPC_ID)
if len(placedata["npcs"]) == 2: break
for _ in npc_list:
placedata["npcs"].append(npc_list.pop().NPC_ID)
if len(placedata["npcs"]) == 2:
break
return data
def generate_game_data(LANG):
def generate_game_data(lang: str) -> tuple[dict, dict]:
"""
Create the gamedata of a game for a given language, chooses 5 random npcs, generate their texts and reactions,
chooses 3 random rooms and places the npcs in them and chooses an inspector question for each type of question
availible in the Question Table.
:param lang: the lang to generate all the texts in
:return: two dictionnaries, one containing the game data, the second containing the reaction table
"""
data = {}
data["npcs"] = {}
reactions_table = {}
@ -233,8 +273,8 @@ def generate_game_data(LANG):
if npc not in npcs:
npcs.append(npc)
for npc in npcs:
data["npcs"][str(npc.NPC_ID)] = generate_npc_text(npc,LANG)
reactions_table[str(npc.NPC_ID)] = generate_npc_reactions(npc)
data["npcs"][str(npc.NPC_ID)] = generate_npc_text(npc, lang)
reactions_table[str(npc.NPC_ID)] = get_npc_random_trait_id(npc)
places = []
while len(places) != 3:
@ -242,22 +282,43 @@ def generate_game_data(LANG):
if place not in places:
places.append(place)
data["rooms"] = generate_place_data(npcs,places,LANG)
data["rooms"] = generate_place_data(npcs, places, lang)
data["questions"] = {}
data["questions"]["QA_0"] = get_text_from_lid("FR", get_random_question(0).TEXT_LID)
data["questions"]["QA_1"] = get_text_from_lid("FR", get_random_question(1).TEXT_LID)
data["traits"] = get_traits(LANG)
data["traits"] = get_traits(lang)
return data, reactions_table
def read_image(path:str):
def read_image(path: str) -> bytes:
"""
Returns the byte representation of an image given its path
:param path: the path to the image
:return: the byte representation of the image, none if its not found or not readable
"""
try:
with open(path, "rb") as f:
return f.read()
with open(path, "rb") as file:
return file.read()
except IOError:
return None
def get_trait_id_from_string(trait):
def get_trait_id_from_string(trait: str) -> int:
"""
Returns the trait_id from its text value
:param text: the text representation of the trait in any lang
:return: the trait_id linked to this text
"""
return get_trait_from_text(trait)
def get_npc_image(npc_id):
def get_npc_image(npc_id: int):
"""
Returns the byte representation of the neutral image for an npc
:param npc_id: npc to get the neutral image from
:return: the byte representation of the image, none if its not found or not readable
"""
return read_image(f"./truthseeker/static/images/npc/{npc_id}/0.png")

View File

@ -1,5 +1,4 @@
import json
import flask
from truthseeker import APP
@ -11,7 +10,7 @@ routes_api = flask.Blueprint("api", __name__)
@routes_api.route("/createGame", methods=["GET", "POST"])
def create_game():
username = flask.request.values.get("username")
if username==None:
if username is None:
return {"error": 1, "msg": "username not set"}
if not game_logic.check_username(username):
return {"error": 1, "msg": "invalid username"}
@ -30,11 +29,11 @@ def create_game():
return response
@routes_api.route("/getGameMembers", methods=["GET", "POST"])
def getMembers():
def get_members():
if not flask.session:
return {"error": 1, "msg": "No session"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
response = {"error" : 0}
@ -46,13 +45,13 @@ def getMembers():
def join_game():
game_id = flask.request.values.get("game_id")
username = flask.request.values.get("username")
if game_id==None or username==None:
if game_id is None or username is None:
return {"error": 1, "msg": "username or game id not set"}
if not game_logic.check_username(username):
return {"error": 1, "msg": "invalid username"}
game = game_logic.get_game(game_id)
if game == None:
if game is None:
return {"error": 1, "msg": "game does not exist"}
if not game.add_member(username):
@ -71,7 +70,7 @@ def is_owner():
if not flask.session:
return {"error": 0, "owner": False}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 0, "owner": False}
if not flask.session["is_owner"]:
@ -84,7 +83,7 @@ def has_joined():
if not flask.session:
return {"error": 0, "joined": False}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 0, "joined": False}
return {"error": 0, "joined": True}
@ -95,7 +94,7 @@ def start_game():
if not flask.session["is_owner"]:
return {"error": 1, "msg": "you are not the owner of this game"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
if game.has_started:
return {"error": 1, "msg": "this game is already started"}
@ -109,7 +108,7 @@ def get_data():
if not flask.session:
return {"error": 1, "msg": "No session"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
response = {}
@ -118,7 +117,7 @@ def get_data():
return response
@routes_api.route("/getNpcImage", methods=["GET", "POST"])
def getNpcImage():
def get_npc_image():
npc_id = flask.request.values.get("npcid")
if npc_id is None:
return {"error": 1, "msg": "no npc was given"}
@ -128,16 +127,16 @@ def getNpcImage():
response = flask.make_response(image)
response.headers.set('Content-Type', 'image/png')
response.headers.set(
'Content-Disposition', 'attachment', filename=f'0.png')
'Content-Disposition', 'attachment', filename='0.png')
return response
@routes_api.route("/getNpcReaction", methods=["GET", "POST"])
def getNpcReaction():
def get_npc_reaction():
if not flask.session:
return {"error": 1, "msg": "No session"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
npc_id = flask.request.values.get("npcid")
@ -149,16 +148,17 @@ def getNpcReaction():
response = flask.make_response(image)
response.headers.set('Content-Type', 'image/png')
response.headers.set(
'Content-Disposition', 'attachment', filename=f'reaction.png')
'Content-Disposition', 'attachment', filename='reaction.png')
return response
@routes_api.route("/gameProgress", methods=["GET", "POST"])
def gameProgress():
def game_progress():
if not flask.session:
return {"error": 1, "msg": "No session"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
username = flask.session["username"]
@ -168,35 +168,35 @@ def gameProgress():
return {"error": 0}
@routes_api.route("/submitAnswers", methods=["GET", "POST"])
def checkAnwser():
def check_anwser():
if not flask.session:
return {"error": 1, "msg": "No session"}
game = game_logic.get_game(flask.session["game_id"])
if game == None:
if game is None:
return {"error": 1, "msg": "this game doesn't exist"}
member = game.get_member(flask.session["username"])
if member.results != None:
if member.results is not None:
return {"error": 1, "msg": "answers already submitted for this member"}
playerResponses = flask.request.values.get("responses")
player_responses = flask.request.values.get("responses")
if playerResponses == None:
if player_responses is None:
return {"error": 1, "msg": "no responses were sent"}
results = game.get_player_results(json.loads(playerResponses))
if results == False:
results = game.get_player_results(json.loads(player_responses))
if results is False:
return {"error": 1, "msg": "invalid npc sent"}
member.has_submitted = True
member.results = results
if game.has_finished():
jsonGameResults = game.generate_game_results()
APP.socketio_app.emit("gamefinshed",jsonGameResults,room="game."+game.game_id)
#TODO desctruct game
json_game_results = game.generate_game_results()
APP.socketio_app.emit("gamefinshed", json_game_results, room="game."+game.game_id)
del game
response = {"error": 0}
return response

View File

@ -17,5 +17,3 @@ def connect(auth):
room = join_room("game."+auth["game_id"])
join_room(room)

View File

@ -1,33 +1,39 @@
import flask
routes_ui = flask.Blueprint("ui", __name__)
@routes_ui.route("/")
def index():
return flask.render_template("index.html")
@routes_ui.route("/privacy")
def privacy():
return flask.render_template("privacy.html")
@routes_ui.route("/licenses")
def licenses():
return flask.render_template("licenses.html")
@routes_ui.route("/legal")
def legal():
return flask.render_template("legal.html")
@routes_ui.route("/lobby/<game_id>")
def lobby(game_id):
# rendered by the javascript client-side
return flask.render_template("lobby.html", gameid=game_id)
@routes_ui.route("/solo")
def solo():
return flask.render_template("game.html")
@routes_ui.route("/multi")
def multi():
return flask.render_template("game.html")