def get_levels(): if(Level.is_empty()): return 'No levels' levels = Level.get_all() text = '' for level in levels: text += 'lvl: ' + str(level['id']) + ' to: ' + str(level['max_xp']) + ' xp' + ' reward: ' + str(level['reward']) + '\n' return text
async def edit_user_role(user_id): level_id = User.get_level(user_id) if level_id > 1: role_prev_id = Level.get_reward(level_id - 1) user_roles = Bot.get_user_roles(user_id) for role in user_roles: if(role.id == role_prev_id): await Bot.delete_user_role(user_id, role.id) role_id = Level.get_reward(level_id) await Bot.apply_user_role(user_id, role_id)
def getLevel(identifier): """Get a level with its questions and their responses""" # Get the connection conn = getConnection() # Get the question question_cursor = executeRequest( """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id FROM Level INNER JOIN Question ON Level.Id = Question.IdLevel INNER JOIN Response ON Question.Id = Response.IdQuestion WHERE Level.Id = """ + identifier + """ ORDER BY Question.Id, Response.Value""", conn) if question_cursor is not None: level = None current_question = None for row in question_cursor.fetchall(): # Title if level is None: level = Level() level.id = row[0] level.title = row[1] # Question if current_question is None or current_question.id != row[1]: current_question = Question() current_question.id = row[2] current_question.question = row[3] current_question.id_level = level.id level.questions.append(current_question) # Responses Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id response = Response() response.value = row[4] response.response = row[5] response.id = row[6] response.id_question = current_question.id current_question.responses.append(response) # Set the result result = getHTTPResponse(200, level) else: # Level does not exist result = getHTTPResponse(500, "This level does not exist", False) conn.close() return result
def place_opponents_close_to_choke_points(self, amount: int, level: Level) -> Level: # Dataframe intended to store randomly a range of opponents # that are randomly assigned to a position. df = pd.DataFrame( columns=['row', 'column', 'opponent_type']).astype(int) # choke_points = self.identify_choke_points( np.array(level.representation)) # Goes as long as the level's desired amount of # opponents has not been reached yet. while len(df) < amount or len(df) == len(choke_points): # Calculates a random position for an opponent belonging # to the type that have been defined above. sample_choke_points = choke_points.sample(1) # Iterates over the random_positions dataframe which may # either contain a single valid position or in case that no # position could have been found, it should be empty. for _, entry in sample_choke_points.iterrows(): # The opponent defined above is added to the current level level.representation[entry['row']][ entry['column']] = entry['opponent_type'] # Adds the randomly chosen opponent to the dataframe # defined above in order to ensure that the while loop # terminates eventually. df = df.append(sample_choke_points) return level
def place_opponents_next_to_each_other(self, amount: int, level: Level) -> Level: # Dataframe intended to store randomly a range of opponents # that are randomly assigned to a position. df = pd.DataFrame( columns=['row', 'column', 'opponent_type']).astype(int) # Goes as long as the level's desired amount of # opponents has not been reached yet. while len(df) < amount: # Selects a walking, jumping or flying opponent randomly. opponent_type: str = random.choice(['J', 'F']) # Calculates a random position for an opponent belonging # to the type that have been defined above. random_positions = self.position_opponents_next_to_each_other( np.array(level.representation), opponent_type) # Iterates over the random_positions dataframe which may # either contain a single valid position or in case that no # position could have been found, it should be empty. for _, entry in random_positions.iterrows(): # The opponent defined above is added to the current level level.representation[entry['row']][ entry['column']] = entry['opponent_type'] # Adds the randomly chosen opponent to the dataframe # defined above in order to ensure that the while loop # terminates eventually. df = df.append(random_positions) return level
def generate_session(self, user_key: str, level: Level, difficulty_score: float) -> str: # Variable intended to store the key # that will be created within the function. session_id: int = 0 # Fetches the ids of all previously played sessions. session_ids: [int] = self.get_session_ids(user_key) # Checks whether at least a single session has been # stored before for a given user. if len(session_ids) > 0: # Sets the id for the session that should be # created next to one higher than previous # session id. session_id = max(session_ids) + 1 # Generates a key that corresponds to the previously # created id like 'session_042' if the session's id # is '42' session_key: str = Helper().generate_key('session', session_id) # Defines a new performance object which values are # initialized with zeros. performance: Performance = Performance(0, 0, 0, 0, 0, 0, 0, difficulty_score) # Creates a new session object based on the previously # defined key and id pair. session: Session = Session(session_key, session_id, 'created', server_timestamp, performance) # Defines a new database reference pointing towards # the place at which the new session sould be stored. ref = db.document(f'users/{user_key}/sessions/{session_key}') # Writes the generated session to Firestore. ref.set(session.to_dict()) # Defines a new database reference at which the session's # performance should be stored. ref = db.document( f'users/{user_key}/sessions/{session_key}/data/performance') # Stores the session's performance. ref.set(performance.to_dict()) # Defines a new database reference pointing to the place at # which the level for the generated session should be stored. ref = db.document( f'users/{user_key}/sessions/{session_key}/data/level') # Stores the session's level at Firestore. ref.set(level.to_dict()) # Returns the key of the generated session. return session_key
def get_level_prototype(self, level_key: str) -> Level: # Retrieves a level prototype from Firestore. dictionary: dict = db.document( f'level_prototypes/{level_key}').get().to_dict() # Returns a level object created return Level.from_dict(dictionary)
def store_level(self, user_key: str, session_key: str, level: Level) -> None: # Defines are reference to a Firebase level document. ref: str = f'users/{user_key}/sessions/{session_key}/data/level' # Stores the level to the level document. db.document(ref).set(level.to_dict())
def is_ready(): try: f = open('AppData/levels.json', 'r') except FileNotFoundError: return False if(Level.is_empty()): return False return True
def getAll(): """Get all levels with their questions and their responses""" # Get the connection conn = getConnection() # Get the question question_cursor = executeRequest( """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id FROM Level INNER JOIN Question ON Level.Id = Question.IdLevel INNER JOIN Response ON Question.Id = Response.IdQuestion ORDER BY Level.Id, Question.Id, Response.Value""", conn) levels = [] current_level = None current_question = None for row in question_cursor.fetchall(): # New level with title if current_level is None or current_level.id != row[0]: current_level = Level() current_level.id = row[0] current_level.title = row[1] levels.append(current_level) # Question if current_question is None or current_question.id != row[2]: current_question = Question() current_question.id = row[2] current_question.id_level = current_level.id current_question.question = row[3] current_level.questions.append(current_question) # Responses response = Response() response.value = row[4] response.response = row[5] response.id = row[6] response.id_question = current_question.id current_question.responses.append(response) # Set the result result = getHTTPResponse(200, levels) conn.close() return result
def get_level(self, user_key: str, session_key: str, level_key: str) -> Level: ref = db.document( f'users/{user_key}/sessions/{session_key}/data/level') dictionary: dict = ref.get().to_dict() return Level.from_dict(dictionary)
async def check_level(user_id): if(User.get_xp(user_id) < User.get_max_xp(user_id)): return if(User.get_level(user_id) < Level.get_max_level_number()): while(User.get_xp(user_id) > User.get_max_xp(user_id)): if(User.get_level(user_id) < Level.get_max_level_number()): await levelup_notification(user_id) await edit_user_role(user_id) User.increment_level(user_id) level_number = User.get_level(user_id) level_max_xp = Level.get_max_xp(level_number) User.set_max_xp(user_id, level_max_xp) elif(User.get_level(user_id) == Level.get_max_level_number()): await levelup_notification(user_id) await edit_user_role(user_id) break elif(User.get_xp(user_id) == User.get_max_xp(user_id)): await levelup_notification(user_id) await edit_user_role(user_id)
def __init__(self, description_factory): self.descriptions = description_factory self.levels = [Level()] self.player = Player.create(self.levels[0], self.levels[0].get_random_walkable()) for n in self.player.pos.neighbors(): if self.levels[0].locate(n) and self.levels[0][n].is_walkable: self.levels[0][n].items = [HealingPotion()] self.messages = deque() self.commands = deque() self.turn = 0
def clean_level(level: Level) -> Level: for i in range(len(level.representation)): for j in range(len(level.representation[i])): if level.representation[i][j] == 'C': level.representation[i][j] = '.' return level
def put(self): payload = request.get_json(force=True) if payload is None: payload = {} new_level = Level(level_number=payload.get('level_number'), category_id=payload.get('category'), points_to_unlock=payload.get('points_need')) db.session.add(new_level) db.session.commit() return {'message': 'Successfully added'}, 200
def put(self): payload = request.get_json(force=True) category_id = payload.get('level') level = payload.get('level') points = payload.get('points') if payload is None: payload = {} new_category_level = Level(level_number=level, points_to_unlock=points, category_id=category_id) db.session.add(new_category_level) db.session.commit() return {'message': 'Level successfully added'}, 200
def place_opponents_randomly(self, amount: int, level: Level) -> Level: # Defines an empty dataframe intended to store a range of # opponents with their type and their position within the given level. df = pd.DataFrame( columns=['row', 'column', 'opponent_type']).astype(int) # Tries to find new potential positions as long as the # specified amount of opponents is not reached yet. while len(df) < amount: # Selects a walking, jumping or flying opponent randomly. opponent_type: str = random.choice(['C', 'J', 'F']) # Calculates a random position for an opponent belonging # to the type that have been defined above. random_positions = self.position_opponent_randomly( np.array(level.representation), opponent_type) # Iterates over the random_positions dataframe which may # either contain a single valid position or in case that no # position could have been found, it should be empty. for _, entry in random_positions.iterrows(): # The opponent defined above is added to the current level level.representation[entry['row']][ entry['column']] = entry['opponent_type'] # Adds the randomly chosen opponent to the dataframe # defined above in order to ensure that the while loop # terminates eventually. df = df.append(random_positions) # Returns the level that has been passed to the function as parameter # and has been extended by a range of randomly selected opponents. return level
def begin(start=0): for i in range(start, len(ranks)): level_score = 0 level_attempts = 0 level_rank = ranks[i] level = Level(level_rank) start = time.time() while (time.time() - start < 60): level.read() key = console.getch() if key == level.key: level_score += 1 level_attempts += 1 level.restart() accuracy = round(level_score / level_attempts, 3) * 100 print("{} {} {}".format("Results for", user.rank, user.name)) print("{} {}".format("Your Score:", str(level_score))) print("{} {}".format("Attempts:", str(level_attempts))) print("{} {} {}".format("Efficiency:", str(accuracy), "%")) if accuracy > 75 and level_attempts > 45: if user.rank == "General": print("You Won!") return user.rank = ranks[i] print("{} {}{}".format("You've been promoted to ", ranks[i + 1], ".")) input('press enter to continue') else: desire = input("retry? Y/N\n") if desire.lower() == "y": begin(i) else: sys.exit()
def initialize_level_prototype(self, level: Level) -> None: # db.document(f'level_prototypes/{level.key}').set(level.to_dict())
def store_initial_level(self, level: Level) -> None: # Creates a new level document at Firestore. db.document(f'levels/{level.key}').set(level.to_dict())
def store_tutorial(self, level: Level) -> None: # Creates a new turorial at Firestore. db.document(f'tutorials/{level.key}').set(level.to_dict())
def store_level_prototype(self, level: Level) -> None: # Creates a new level prototype document at Firestore. db.document(f'level_prototypes/{level.key}').set(level.to_dict())
def add_users(): members = Bot.guild.members for member in members: if not(member.bot): User.add(member.id, member.name, 0, Level.get_max_xp(1), 1)
async def add_level(max_xp, reward): Level.add(max_xp, reward)
def is_levels_empty(): return Level.is_empty()
def clear_levels(): Level.clear()
class Samples: ############### ## Variables ## ############### db: Database = Database() # sample_user: User = User('user_042', 42, 'german') sample_performance_dict = { "defeated_by_gaps": 1, "defeated_by_opponent_type_1": 1, "defeated_by_opponent_type_2": 1, "defeated_by_opponent_type_3": 0, "score": 600, "time": 45, "progress": 15, "difficulty": 80, } sample_performance: Performance = Performance( defeated_by_gaps=1, defeated_by_opponent_type_1=1, defeated_by_opponent_type_2=1, defeated_by_opponent_type_3=0, score=600, time=45, progress=15, difficulty=80, ) sample_session: Session = Session('session_001', 1, 'finished', db.generate_timestamp(), sample_performance) sample_level: Level = Level.from_dict({ 'key': 'level_01', 'id': 1, 'line_00': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.' ], 'line_01': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.' ], 'line_02': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.' ], 'line_03': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.' ], 'line_04': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'B' ], 'line_05': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D' ], 'line_06': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'S', 'S', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D' ], 'line_07': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D' ], 'line_08': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'S', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'C', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D' ], 'line_09': [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'B', 'B', 'B', 'B', '.', '.', '.', '.', '.', '.', '.', '.', 'D', '.', '.', '.', '.', '.', '.', 'D' ], 'line_10': [ '.', '.', 'X', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'C', '.', '.', '.', '.', '.', 'C', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D', 'D', '.', '.', '.', '.', '.', '.', 'D' ], 'line_11': [ '.', '.', 'X', '.', '.', '.', '.', '.', '.', '.', 'B', '.', 'B', 'B', 'B', 'B', 'B', 'B', '.', '.', '.', 'D', 'D', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D', 'D', 'D', '.', '.', '.', '.', '.', '.', 'D' ], 'line_12': [ '.', '.', 'X', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D', 'D', '.', '.', '.', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', '.', '.', 'D', 'D', 'D', 'D', '.', '.', '.', '.', '.', '.', 'D' ], 'line_13': [ '.', '.', 'X', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'D', 'D', '.', '.', '.', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', '.', 'D', 'D', 'D', 'D', 'D', '.', '.', '.', '.', '.', '.', 'D' ], 'line_14': [ 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', '.', '.', '.', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', '.', '.', 'Z', 'Z', 'Z', 'D', 'D' ] }) sample_user_1: User = User('user_001', 1, 'english') sample_user_2: User = User('user_002', 2, 'english') sample_user_3: User = User('user_003', 3, 'english') sample_user_4: User = User('user_004', 4, 'english') sample_session_1: Session = Session( 'session_001', 1, 'finished', db.generate_timestamp(), Performance(0, 1, 0, 2, 1500, 48, 200, 80)) sample_session_2: Session = Session( 'session_002', 2, 'finished', db.generate_timestamp(), Performance(0, 2, 0, 2, 3000, 130, 156, 100)) sample_session_3: Session = Session( 'session_003', 3, 'finished', db.generate_timestamp(), Performance(2, 0, 0, 2, 4500, 38, 137, 110)) sample_session_4: Session = Session( 'session_001', 1, 'finished', db.generate_timestamp(), Performance(1, 0, 0, 1, 4300, 48, 149, 90)) sample_session_5: Session = Session( 'session_002', 2, 'finished', db.generate_timestamp(), Performance(0, 0, 0, 0, 4300, 243, 200, 180)) sample_session_6: Session = Session( 'session_001', 1, 'finished', db.generate_timestamp(), Performance(0, 3, 1, 0, 2200, 38, 113, 65)) sample_session_7: Session = Session( 'session_002', 2, 'finished', db.generate_timestamp(), Performance(0, 2, 2, 0, 1100, 52, 200, 79)) sample_session_8: Session = Session( 'session_001', 1, 'finished', db.generate_timestamp(), Performance(2, 0, 0, 1, 500, 74, 31, 103))
def get_max_level_number(): return Level.get_max_level_number()
def initialize_levels(self): database: Database = Database() evolution: Evolution = Evolution() level_01: Level = Level( 'level_01', '01', TextFileReader().read_text_file('level_01.txt')) level_02: Level = Level( 'level_02', '02', TextFileReader().read_text_file('level_02.txt')) level_03: Level = Level( 'level_03', '03', TextFileReader().read_text_file('level_03.txt')) level_04: Level = Level( 'level_04', '04', TextFileReader().read_text_file('level_04.txt')) level_05: Level = Level( 'level_05', '05', TextFileReader().read_text_file('level_05.txt')) level_06: Level = Level( 'level_06', '06', TextFileReader().read_text_file('level_06.txt')) level_07: Level = Level( 'level_07', '07', TextFileReader().read_text_file('level_07.txt')) level_08: Level = Level( 'level_08', '08', TextFileReader().read_text_file('level_08.txt')) tutorial: Level = Level( 'tutorial', 'tutorial', TextFileReader().read_text_file('tutorial.txt')) level_01 = Helper.clean_level(level_01) level_02 = Helper.clean_level(level_02) level_03 = Helper.clean_level(level_03) level_04 = Helper.clean_level(level_04) level_05 = Helper.clean_level(level_05) level_06 = Helper.clean_level(level_06) level_07 = Helper.clean_level(level_07) level_08 = Helper.clean_level(level_08) database.store_level_prototype(level_01) database.store_level_prototype(level_02) database.store_level_prototype(level_03) database.store_level_prototype(level_04) database.store_level_prototype(level_05) database.store_level_prototype(level_06) database.store_level_prototype(level_07) database.store_tutorial(tutorial) level_01 = evolution.evolve('random_distribution', level_01) level_02 = evolution.evolve('random_distribution', level_02) level_03 = evolution.evolve('random_distribution', level_03) level_04 = evolution.evolve('random_distribution', level_04) level_05 = evolution.evolve('random_distribution', level_05) level_06 = evolution.evolve('random_distribution', level_06) level_07 = evolution.evolve('random_distribution', level_07) level_08 = evolution.evolve('random_distribution', level_08) database.store_initial_level(level_01) database.store_initial_level(level_02) database.store_initial_level(level_03) database.store_initial_level(level_04) database.store_initial_level(level_05) database.store_initial_level(level_06) database.store_initial_level(level_07) database.store_initial_level(level_08)
def get_reward(level): return Level.get_reward(level)