def run(self, context: typings.Context, args: list): tournament_model = context["models"]["Tournament"] tournament_view = context["views"]["tournament"] tournament_id = self.pop_arg(args) key = self.pop_arg(args) value = self.pop_arg(args) if not tournament_id: raise errors.GenericError("Tournament id is required") blacklist = ["doc_id", "id", "round_instances", "players"] if key in blacklist: raise errors.GenericError(f"Can't edit {key}") if not value: raise errors.GenericError("Input not valid") tournament = tournament_model.find_one(tournament_id) if not tournament: raise errors.GenericError( "Can't find tournament with the given ID") sanitize_type = type(getattr(tournament, key)) setattr(tournament, key, sanitize_type(value)) tournament = tournament.save() tournament_view.render_single(tournament, title="Updated Tournament")
def run(self, context: typings.Context, args: list): player_model = context["models"]["Player"] player_view = context["views"]["player"] player_id = self.pop_arg(args) key = self.pop_arg(args) value = self.pop_arg(args) if not player_id: raise errors.GenericError("Player id is required") blacklist = ["doc_id", "id"] if key in blacklist: raise errors.GenericError(f"Can't edit {key}") if not value: raise errors.GenericError("Missing value") player = player_model.find_one(player_id) if not player: raise errors.GenericError("Can't find Player with the given ID") sanitize_type = type(getattr(player, key)) setattr(player, key, sanitize_type(value)) player = player.save() player_view.render_single(player, title="Updated Players")
def find_one(cls, id): """Find one item in the database""" instance_name = cls.__name__ if not id: raise errors.GenericError(f"Missing {instance_name}_id") elif not id.isdigit(): raise errors.GenericError(f"{instance_name}_id must be a number") id = int(id) has_id: bool = cls.database.contains(doc_id=id) return cls.resolve(cls.database.get(doc_id=id)) if has_id else has_id
def run(self): main_view = self.views["main"] all_tournaments = lambda: self.models["Tournament"].find_many() all_commands = self.commands.cache.values() main_view.render_main_page(all_commands, all_tournaments()) try: while self.is_running: try: input_content = input("-> : ").strip() args = input_content.split(" ") command_name = args.pop(0) self.commands.execute(command_name, args=args, context=self.context) except Exception as e: if not hasattr(e, "custom"): errors.GenericError(e) main_view.render_main_page(all_commands, all_tournaments()) except KeyboardInterrupt: main_view.application_quit()
def run(self, context: typings.Context, args: list): context = context.copy() # i don't want to modify the 'main' context self.commands.cache["quit"] = self.__quit() tournament_view = context["views"]["tournament"] tournament_model = context["models"]["Tournament"] tournament_id = self.pop_arg(args) tournament = tournament_model.find_one(tournament_id) if not tournament: raise errors.GenericError( f"Tournament with the id [{tournament_id}] doesn't exist") tournament = self._check_rounds(tournament) commands = self.commands.cache.values() self._check_commands(tournament) tournament_view.render_selected_tournament(tournament, commands) while self.is_running: try: input_content = input("-> : ").strip() args = input_content.split(" ") command_name = args.pop(0) self.commands.execute(command_name, args=args, context=context, tournament=tournament) tournament = tournament.save() except Exception as e: if not hasattr(e, "custom"): errors.GenericError(e) if not self.is_running: # Its not an error, but its a way out raise errors.GenericError("Tournament Mode has been closed", title="Note") tournament = self._check_rounds(tournament) self._check_commands(tournament) tournament_view.render_selected_tournament(tournament, commands)
def run(self, context: typings.Context, args: list): player_model = context["models"]["Player"] player_view = context["views"]["player"] player_count = self.pop_arg(args) if player_count and player_count.isdigit(): total_created = self.create_multiples(player_count, player_model) return player_view.render_multiples(total_created, title="Created Players") questions = { "first_name": text( message="Enter the first name of the player:", validate=validators.TextValidator(), default=f'{self._generate_fake("first_name")}', ), "last_name": text( message="Enter the last name of the player:", validate=validators.TextValidator(), default=f'{self._generate_fake("last_name")}', ), "birthday": text( message="Enter the birthday of the player:", validate=validators.DateValidator(), default=f'{self._generate_fake("birthday")}', ), "sexe": select( message="Enter the sexe of the player:", choices=["Male", "Female"], default=f'{self._generate_fake("sexe")}', ), "rank": text( message="Enter the rank of the player:", validate=validators.DigitValidator(), default=f'{self._generate_fake("rank")}', ), } result = {} for key, value in questions.items(): sanitize_value = type(getattr(player_model(), key)) try: result[key] = sanitize_value(value.execute()) except KeyboardInterrupt: raise errors.GenericError("Canceld the creation of the player", title="Note") new_player = player_model(**result) new_player = new_player.save() player_view.render_single(new_player, title="Created Player")
def run(self, context: typings.Context, tournament: database.Tournament, args: list): round: other.Round = tournament.round_instances[ tournament.state.current_round] tournament_view = context["views"]["tournament"] match_id = self.pop_arg(args) if not match_id: raise errors.GenericError("No <Match ID> given") if not match_id.isdigit(): raise errors.GenericError("<Match ID> must be a number") try: match = round.get_match(int(match_id) - 1) except IndexError: raise errors.GenericError("Match ID doesn't exist") while True: tournament_view.render_match(match) whitelist = ["a", "b", "c", "d"] input_content = input("-> : ").strip() args = input_content.split(" ") command_name = args.pop(0) if command_name in whitelist: if command_name == "a": match.settle_score(match.player1) match.player1.points = 1 match.player2.points = 0 elif command_name == "b": match.settle_score(match.player2) match.player2.points = 1 match.player1.points = 0 elif command_name == "c": match.player1.points = 0.5 match.player2.points = 0.5 match.settle_score("TIE") break # i don"t need to add the command D else: continue
def run(self, context: typings.Context, args: list): player_model = context["models"]["Player"] player_view = context["views"]["player"] key = self.pop_arg(args) value = self.pop_arg(args) if key and not value: raise errors.GenericError(f"Missing value for {key}") if key and key not in vars(player_model()): raise errors.GenericError(f"The key <{key}> doesn't exist in player") found_players = player_model.find_many(key, value) if not found_players: raise errors.GenericError("No players found") player_view.render_multiples(found_players, title="Found Players")
def run(self, tournament: database.Tournament, *args, **kwargs): if not tournament.state.is_ongoing: raise errors.GenericError("Tournament is already marked as done") round = tournament.round_instances[tournament.state.current_round] if None in [x.winner for x in round.matches]: raise errors.GenericError( "Cannot end the tournament, some matches are not completed") if not round.end_date: round.end_round() tournament.state.is_ongoing = False raise errors.GenericError( "Tournament has been marked as finished, you can now quit the tournament mode", title="Note", )
def run(self, tournament: database.Tournament, *args, **kwargs): if tournament.state.current_round + 1 == tournament.rounds: return round = tournament.round_instances[tournament.state.current_round] # Can't go to the next round if the matches aren't completed if None in [x.winner for x in round.matches]: raise errors.GenericError("Can't go to the next round, some matches need to be completed first") if not round.end_date: round.end_round() tournament.state.current_round += 1 # Testing if we can generate a new round if not len(tournament.generate_round().get_players()): tournament.state.is_ongoing = False tournament.state.current_round -= 1 raise errors.GenericError("Cannot generate a new round, everyone played agaist each other !")
def run(self, context: typings.Context, args: list): tournament_model = context["models"]["Tournament"] tournament_view = context["views"]["tournament"] key = self.pop_arg(args) value = self.pop_arg(args) if key and not value: raise errors.GenericError(f"Missing value for {key}") if key and key not in vars(tournament_model()): raise errors.GenericError( f"The key <{key}> doesn't exist in tournament") found_tournaments = tournament_model.find_many(key, value) if not found_tournaments: raise errors.GenericError("No tournaments found") tournament_view.render_multiples(found_tournaments, title="Found tournaments")
def run(self, tournament: database.Tournament, *args, **kwargs): if tournament.state.commit: raise errors.GenericError( "This tournament has been already commited") sortby_id = lambda _interable: sorted(_interable, key=lambda x: x.id) base_players = sortby_id(tournament.players) for round in tournament.round_instances: players = sortby_id(round.get_players()) for base_player, new_player in zip(base_players, players): base_player.rank += new_player.points tournament.state.commit = True
def find_many(cls, key=None, value=None): """Find many items in the database""" if not key or not value: return [cls.resolve(x) for x in cls.database.all()] query = getattr(Query(), key) key_type = type(getattr(cls(), key)) search_criteria = query == value if key_type == str: search_criteria = query.matches(value, re.IGNORECASE) if key_type == int: if value.isdigit(): search_criteria = query == int(value) else: raise errors.GenericError(f"value must be a number") return [cls.resolve(x) for x in cls.database.search(search_criteria)]
def execute(self, command_name: str, *args, **kwargs): if not command_name and not self.parent_command: raise errors.GenericError("Missing Command") if not command_name and self.parent_command: raise errors.AvailableCommands(commands=self.cache.values()) command = self.cache.get(command_name) if not command: raise errors.CommandNotFound(command_name, parent_command=self.parent_command, commands=self.cache.values()) if command.reload: command = self.reload(command_name, command.__module__) if not command.is_disabled: command.run(*args, **kwargs)
def run(self, tournament: database.Tournament, context: typings.Context, args: list): tournament_view = context["views"]["tournament"] sort_by = self.pop_arg(args) or "points" order = self.pop_arg(args) or "ascending" if order not in ["ascending", "descending"]: errors.GenericError( f"Can't set the order to {order}, use ascending or descending." ) sortby_id = lambda _interable: sorted(_interable, key=lambda x: x.id) base_players = deepcopy(sortby_id(tournament.players)) for round in tournament.round_instances: players = sortby_id(round.get_players()) for base_player, new_player in zip(base_players, players): base_player.points += new_player.points tournament_view.render_report(base_players, sort_by, order)
def run(self, context: typings.Context, args: list): tournament_model = context["models"]["Tournament"] tournament_view = context["views"]["tournament"] players = context["models"]["Player"].find_many() has_min_players = lambda players: len(players) >= 8 if not has_min_players(players): raise errors.GenericError( "Cannot create a tournament without at least 8 players created !" ) questions = { "name": text( message="Enter the name of the tournament:", validate=validators.TextValidator(), default=f'{self._generate_fake("name")}', ), "location": text( message="Enter the location of the tournament:", validate=lambda text: len(text) > 0, default=f'{self._generate_fake("location")}', ), "date": text( message="Enter date of the tournament:", validate=validators.DateValidator(), default=f'{self._generate_fake("date")}', ), "rounds": text( message="Enter the rounds of the tournament:", validate=validators.DigitValidator(), default="4", ), "players": select( message="Select the participants:", choices=[{ "name": f"{p.full_name}", "value": p } for p in players], instruction= "> use Spacebar to select, and Enter to exit the selection", validate=lambda players: has_min_players(players) and len( players) % 2 == 0 and len(players), invalid_message= "Cannot select less than 8 players OR odd players", multiselect=True, transformer=lambda result: "%s player%s selected" % (len(result), "s" if len(result) > 1 else ""), ), "time_control": select( message="Time control of the Tournament:", choices=["blitz", "bullet"], default="blitz", ), "desc": text( message="Description:", default="None", ), } result = {} for key, value in questions.items(): sanitize_value = type(getattr(tournament_model(), key)) try: result[key] = sanitize_value(value.execute()) except KeyboardInterrupt: raise errors.GenericError( "Canceld the creation of the tournament", title="Note") new_tournament = tournament_model(**result) new_tournament = new_tournament.save() tournament_view.render_single(new_tournament, title="Created Tournament", hint=True)