def run(self):
        tournament_data = []
        validator = TournamentDataValidator()
        prompt = (('Nom (max. 50 caractères): ', validator.is_name_ok),
                  ('Description (max. 50 caractères): ',
                   validator.is_description_ok),
                  ('Lieu (max. 50 caractères): ', validator.is_place_ok),
                  ('Date de début (jj/mm/aaaa): ',
                   validator.is_start_date_ok), ('Date de fin (jj/mm/aaaa): ',
                                                 validator.is_end_date_ok),
                  ('Nombre de rounds:  (entier positif, par défaut: 4): ',
                   validator.is_number_of_rounds_ok),
                  ('Contrôle du temps (blitz / bullet / coup rapide): ',
                   validator.is_time_control_ok))
        for message, check_function in prompt:
            user_input = ViewPrompt(message).show()
            while not check_function(user_input):
                ViewText("Erreur de saisie, veuillez recommencer.").show()
                user_input = ViewPrompt(message).show()
            tournament_data.append(user_input)
        tournament = Tournament(*tournament_data)

        if tournament not in self.tournament_database:
            tournament.players = ControllerChoosePlayer(
                self.player_database).run()
            self.tournament_database.append(tournament)
            ViewText("Création du tournoi terminée avec succès.").show()
            ControllerSaveTournament(tournament).run()
        else:
            ViewText(
                "Erreur: le tournoi existe déjà (même nom, dates, contrôle du temps."
            ).show()
 def resume_tournament(self):
     """
     request the name of the tournament
     :return:name of tournmaent (string)
     """
     cls()
     icon()
     self.list_tournament_not_over = list()
     for self.tournament_name in search_all_tournament():
         self.tournament = Tournament()
         self.tournament.read_in_db(self.tournament_name)
         if not self.tournament.tournament_over:
             self.list_tournament_not_over.append(self.tournament)
     print('Vous souhaitez reprendre un Tournoi, si la liste est vide, '
           'taper Entrée pour revenir au menu principal\n')
     print(("=" * 113).center(width_calculated()))
     print(f'| {"Nom du Tournoi".center(35)} |'
           f'{"Ville".center(35)} |'
           f'{"Date".center(35)} |'.center(width_calculated())
           )
     for self.tournament in self.list_tournament_not_over:
         print(("-" * 113).center(width_calculated()))
         print(f'| {self.tournament.name.center(35)} |'
               f'{self.tournament.location.center(35)} |'
               f'{self.tournament.date.center(35)} |'.center(width_calculated())
               )
     print(("-" * 113).center(width_calculated()))
     self.name_tournament = " "
     while not (self.name_tournament in search_all_tournament() or self.name_tournament == ""):
         self.name_tournament = input('Tapez le nom du Tournoi : ').capitalize()
     return self.name_tournament
Example #3
0
    def edit_player(self):
        self._model = Tournament({})
        all_players = self._model.get_players()
        self._view.show_items(all_players)
        ids = [item['id'] for item in all_players]
        player = self._view.get_user_choice(config.SELECT_PLAYER, ids)
        player_data = self._model.get_player(player)
        new_player_data = {}
        for item in config.NEW_PLAYER:
            if item == 'ranking':
                new_data = int(
                    self._view.get_user_input(
                        f'{config.NEW_PLAYER[item]} (current data: {player_data[item]}, press enter to keep as is)'
                    ))
            else:
                new_data = self._view.get_user_input(
                    f'{config.NEW_PLAYER[item]} (current data: {player_data[item]}, '
                    f'press enter to keep as is)')
            if new_data:
                new_player_data[item] = new_data
            else:
                new_player_data[item] = player_data[item]
        new_player_data['id'] = player_data['id']
        self._model.edit_player(new_player_data)
        self._view.confirm('player')

        self.player_menu()
    def load(self):
        """Load a tournament"""
        report = Reports(players_db, tournaments_db)
        self.screen.clear()
        self.screen.info_users(report.tournaments_list())
        self.screen.on_screen()
        tournament_id = input_menu_verification(
            max_id(tournaments_db), "Saisissez le numéro du tournoi à charger")

        valid_tournament = search_db(tournament_id, tournaments_db)

        if valid_tournament is False:
            self.screen.warning(
                "Le tournoi {} n'existe pas.".format(tournament_id))
            sleep(1)
            self.load()
        else:
            tournament_on_load = Tournament(valid_tournament)
            tournament_on_load.deserialized()
            self.tournament = tournament_on_load
        self.players_on_load = []
        for player in self.tournament.players_list:
            self.players_on_load.append(player.player_id)

        while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB:
            self.add_player_on_tournament()

        self.play()
Example #5
0
    def tournament_rounds_reports(self):
        """Show rounds for a single tournament"""
        tournament_id = self.select_tournament()
        self._model = Tournament({'id': tournament_id})
        self._view.report(self._model.get_rounds())

        self.tournament_menu()
Example #6
0
class TournamentManager:
    """ Class of a tournament manager

    This class contains methods to create, search or save tournaments. It contains 4 methods:
    create_tournament: create a tournament from the params and puts it in the tournaments dict with
                    the tournament id as the key.
    find_tournament_by_id: verifies if the id is in the tournaments dict and returns the matching tournament.
    save_tournament_in_db: serialize the tournament and saves it in the database under the 'tournaments' table.
    load_tournament_from_db: creates a tournament for each item in the 'tournaments' table.

    """
    def __init__(self):
        self.tournaments = {}
        self.tournament = None

    def create_tournament(self, params):
        self.tournament = Tournament(**params)
        self.tournaments[self.tournament.identifier] = self.tournament.params

    def find_tournament_by_id(self, id_tournament: str) -> str:
        for key, value in self.tournaments.items():
            if key == id_tournament:
                return self.tournaments[key]

    def save_tournament_in_db(self):
        db = TinyDB('database.json')
        table = db.table('tournaments')
        self.tournament.serialize()
        table.insert(self.tournament.params)

    def load_tournament_from_db(self):
        db = TinyDB('database.json')
        table = db.table('tournaments')
        for item in table:
            self.create_tournament(item)
Example #7
0
 def tournament_report(self, needs_selection=False):
     """Show all tournaments in DB"""
     if not self._model:
         self._model = Tournament({})
     self._view.report(self._model.get_tournaments())
     if needs_selection:
         return self._model.get_tournaments()
     else:
         self.tournament_menu()
 def setUp(self):
     super(TestScoreEntered, self).setUp()
     self.injector.inject(self.tourn_1, num_players=5)
     tourn = Tournament(self.tourn_1)
     tourn.update({
         'rounds': 2,
         'missions': ['foo_mission_1', 'foo_mission_2']
     })
     tourn.make_draws()
Example #9
0
    def create_tournament(self):
        """Create tournament instance with user informations."""
        tournament_infos = self.tournois_view.get_tournament_info()
        tournament_infos['id'] = str(uuid1())
        tournois_obj = Tournament()
        tournois_obj.add_tournament(tournament_infos)

        self.add_multiple_players(int(tournois_obj.number_of_players), tournois_obj)

        self.generate_first_round(tournois_obj)
Example #10
0
    def add_player(self):
        player = {}
        for item in config.NEW_PLAYER:
            player[item] = self._view.get_user_input(config.NEW_PLAYER[item])
        if not player['ranking']:
            player['ranking'] = 9999
        self._model = Tournament({})
        self._model.create_player(player)
        self._view.confirm('player')

        self.player_menu()
Example #11
0
 def report_index(self):
     ViewMain.report_menu()
     choice = input()
     if choice == '0':  # back last Menu
         return self.index()
     if choice == '1':
         players = Player.get_all_by_alpha()
         self.report(players)
     if choice == '2':
         players = Player.get_all_by_rank()
         self.report(players)
     if choice == '3':
         tournament_id = TournamentController().select_tournament()
         if tournament_id is not None:
             tournament = Tournament.get_tournament(tournament_id)
             tournament_players = tournament.get_players_by_alpha()
             players = [
                 Player.get_player(player) for player in tournament_players
             ]
             self.report(players)
     if choice == '4':
         tournament_id = TournamentController().select_tournament()
         if tournament_id is not None:
             tournament = Tournament.get_tournament(tournament_id)
             tournament_players = tournament.get_players_by_rank()
             players = [
                 Player.get_player(player) for player in tournament_players
             ]
             self.report(players)
     if choice == '5':
         tournaments = Tournament.TOURNAMENT
         if len(tournaments) > 0:
             self.report(tournaments)
     if choice == '6':
         tournament_id = TournamentController().select_tournament()
         if tournament_id is not None:
             tournament = Tournament.get_tournament(tournament_id)
             rounds = tournament.rounds
             self.report(rounds)
     if choice == '7':
         tournament_id = TournamentController().select_tournament()
         if tournament_id is not None:
             tournament = Tournament.get_tournament(tournament_id)
             matches = []
             for rnd in tournament.rounds:
                 for match in rnd.matches:
                     matches.append(match)
                     # matches.append(match.result_to_string())
             self.report(matches)
     input('Press ENTER to continue')
     return self.report_index()
 def __init__(self):
     """
     Create the main tournament menu
     """
     cls()
     icon()
     self.list_all_tournament_name = search_all_tournament()
     self.list_tournaments = []
     for self.tournament_name in self.list_all_tournament_name:
         self.tournament = Tournament()
         self.tournament.read_in_db(self.tournament_name)
         self.list_tournaments.append(self.tournament)
     print("Menu des stats Tournoi \n\n"
           "1. Voir la liste de tous les Tournois\n"
           "2. Voir les tours d'un Tournoi avec son nom\n"
           "3. Voir les matchs d'un Tournoi avec son nom\n"
           "4. Voir les Joueurs d'un Tournoi avec son nom\n"
           "5. Retour")
     self.choice_menu = 0
     while not 5 >= int(self.choice_menu) >= 1:
         self.choice_menu = input(
             "Faites votre choix en tapant le numéro de menu (ex. 1, 2, 3, 4, ne tapez qu'un seul choix) : "
         )
         if not self.choice_menu.isdigit():
             self.choice_menu = 0
     if int(self.choice_menu) == 1:
         self.show_list_all_tournament()
         input()
     elif int(self.choice_menu) == 2:
         if self.show_one_tournament():
             self.show_tour()
             input()
         else:
             print("Ce tournoi n'existe pas")
             input()
     elif int(self.choice_menu) == 3:
         if self.show_one_tournament():
             self.show_match()
             input()
         else:
             print("Ce tournoi n'existe pas")
             input()
     elif int(self.choice_menu) == 4:
         if self.show_one_tournament():
             self.show_player()
             input()
         else:
             print("Ce tournoi n'existe pas")
             input()
     elif int(self.choice_menu) == 5:
         pass
    def test_tournament_round_deletion(self):
        """Check that the rounds get deleted when rounds are reduced"""
        name = 'test_tournament_round_deletion'
        self.injector.inject(name)

        tourn = Tournament(name)
        tourn.update({'rounds': 6})
        compare(
            len(TournamentRound.query.filter_by(tournament_name=name).all()),
            6)

        tourn.update({'rounds': 2})
        compare(
            len(TournamentRound.query.filter_by(tournament_name=name).all()),
            2)
    def test_get_round(self):
        """Test the round getter"""
        name = 'test_get_round'
        self.injector.inject(name)

        tourn = Tournament(name)
        tourn.update({'rounds': 2})

        self.assertTrue(tourn.get_round(1).get_dao().ordering == 1)
        self.assertTrue(tourn.get_round(2).get_dao().ordering == 2)

        self.assertRaises(ValueError, tourn.get_round, 3)
        self.assertRaises(ValueError, tourn.get_round, -1)
        self.assertRaises(ValueError, tourn.get_round, 'a')
        self.assertRaises(ValueError, tourn.get_round, 0)
def add_tournament():
    # pylint: disable=undefined-variable

    """
    POST to add a tournament
    Expects:
        - inputTournamentName - Tournament name. Must be unique.
        - inputTournamentDate - Tournament Date. YYYY-MM-DD
    """
    opt_args = request.get_json() if request.get_json() is not None else {}
    tourn = Tournament(inputTournamentName)
    tourn.new(date=inputTournamentDate,
              to_username=request.authorization.username,
              **opt_args)
    return tourn.details()
def tournaments_scrape():
  tour_champ_end = datetime.datetime(year=2014, month=9, day=16) #shitty way of dates
  url = 'http://www.pgatour.com/tournaments/schedule.html'
  r = requests.get(url)
  soup = BeautifulSoup(r.text)
  table = soup.find_all('table', id='tableFirst')
  asdf = r.text.find("initLb")
  for row in table[0].tbody:
    try:
      info = row.find_all('td')
      tdate = info[0].string.split()
      #date is now a list. we need to get the dates from the strings. Odd error here:
      #some times the dates come back in different forms, so we try all just to make
      #sure
      year = '2014' #this can be changed later
      tourney_name = info[1].a.string.strip()
      try:
        begin_date = datetime.datetime.strptime(tdate[1]+tdate[2]+tdate[5],'%b%d%Y')
        end_date = datetime.datetime.strptime(tdate[8]+tdate[9]+tdate[12],'%b%d%Y')
      except IndexError:
        begin_date = datetime.datetime.strptime(tdate[0]+tdate[1]+year,'%b%d%Y')
        try:
          end_date = datetime.datetime.strptime(tdate[0]+tdate[3]+year,'%b%d%Y')
        except ValueError:
          end_date = datetime.datetime.strptime(tdate[3]+tdate[4]+year,'%b%d%Y')
      try:
        tourney_link = info[1].a['href'][0]
      except TypeError:
        print "no link for " + tourney_name
        continue
      if tourney_link == '/':
        tourney_url = 'http://www.pgatour.com'+info[1].a['href']
      else:
        tourney_url = info[1].a['href']
      #we need to get the tid... stupidest way to do this........
      tourney_pga_id = _get_tourney_id(tourney_url)
      tourney_leaderboard_json_url = 'http://www.pgatour.com/data/r/' + tourney_pga_id + '/leaderboard.json'
      print tourney_name
      if end_date < tour_champ_end:
        try:
          tourney = Tournament.objects.get(pga_id=tourney_pga_id)
        except me.queryset.DoesNotExist:
          tourney = Tournament(pga_id=tourney_pga_id, begin_date=begin_date,end_date=end_date,name=tourney_name,main_page_url=tourney_url,leaderboard_json_url=tourney_leaderboard_json_url)
          tourney.field_url = tournament.main_page_url[0:-5]+'/field.html'
          tourney.quarter = 1
          tourney.save()
    except AttributeError: # incase it's just a string
      pass
    def load_tournament(self, tournament_json):
        tournament = Tournament(
            tournament_json['name'], tournament_json['description'],
            tournament_json['place'], tournament_json['start_date'],
            tournament_json['end_date'], tournament_json['number_of_rounds'],
            tournament_json['time_control'])

        for player_data in tournament_json['players']:
            tournament.players.append(Player(**player_data))

        for round_ in tournament_json['rounds']:
            new_round = Round(tournament)
            new_round.start_time = datetime(
                round_['start']['y'],
                round_['start']['mo'],
                round_['start']['d'],
                round_['start']['h'],
                round_['start']['mi'],
            )
            new_round.end_time = datetime(
                round_['end']['y'],
                round_['end']['mo'],
                round_['end']['d'],
                round_['end']['h'],
                round_['end']['mi'],
            )
            new_round.end_confirmation = round_['end_confirmation']
            for game_data in round_['games']:
                new_game = Game(Player(**game_data['player1']),
                                Player(**game_data['player2']))
                new_game.update_result(game_data['result'])
                new_round.games.append(new_game)
            tournament.rounds.append(new_round)

        return tournament
Example #18
0
 def add_tournament(self):
     data = {}
     for item in config.NEW_TOURNAMENT:
         data[item] = self._view.get_user_input(config.NEW_TOURNAMENT[item])
     if not data['date']:
         data['date'] = date.today().strftime('%d/%m/%Y')
     data['players'] = []
     self._model = Tournament({})
     for i in range(0, self._model.nb_players):
         self._view.show_items(self._model.get_players())
         data['players'].append(
             int(self._view.get_user_input(config.SELECT_PLAYER)))
     self._model = Tournament(self._model.create_tournament(data))
     self._view.confirm('tournament')
     self._view.show_items(self._model.show_latest_pairs())
     self._view.confirm('pairs')
     self.tournament_menu()
Example #19
0
    def new(self):
        c = main.MainController()
        name = c.input_with_options('Tournament name : ')
        place = c.input_with_options('Tournament place : ')

        date_regex = re.compile(r'^(0[1-9]|[1-2][0-9]|3[0-1])/'
                                r'(0[1-9]|1[0-2])/[0-9]{4}$')
        date_start = c.input_with_options('Tournament start date : ',
                                          date_regex,
                                          'Date format should be: dd/mm/yyyy',
                                          loop=True)
        date_end_regex = re.compile(r'^(0[1-9]|[1-2][0-9]|3[0-1])/'
                                    r'(0[1-9]|1[0-2])/[0-9]{4}$|^$')
        date_end = c.input_with_options(
            'End date ? (Empty if it\'s a 1-day tournament) : ',
            date_end_regex,
            'Date format should be: dd/mm/yyyy',
            loop=True)
        date = date_start
        if date_end != "":
            date += ' to ' + date_end

        round_number = c.input_with_options('Number of rounds : ',
                                            re.compile('^[0-9]+$'),
                                            'Please enter a positive number',
                                            loop=True)

        description = c.input_with_options('description : ')

        time_control_list = ['Bullet', 'Blitz', 'Rapid']
        text = 'Time control [{}] : \n'
        for i in range(len(time_control_list)):
            text += '    ' + str(i + 1) + ') ' + time_control_list[i] + '\n'
        time_control = c.input_with_options(text,
                                            re.compile(r'^[1-3]+$|^$'),
                                            'Please enter 1, 2 or 3',
                                            loop=True)
        if time_control in ['1', '2', '3']:
            time_control = time_control_list[int(time_control) - 1]

        tournament = Tournament(name, place, date, time_control, description,
                                round_number)

        Tournament.add_tournament(tournament)
        return tournament
Example #20
0
class TournamentTestCase(unittest.TestCase):
    tournament = Tournament()

    def test_create_match(self):
        match_number = 1
        self.assertEqual(self.tournament.match_count, 0)
        self.tournament.create_match(match_number, "Player A", "Player B")
        self.assertEqual(self.tournament.match_count, 1)
        self.assertTrue(self.tournament.get_match(match_number))
class TestTournament(unittest.TestCase):
    def setUp(self):
        self.tournament = Tournament()
        self.teams = self.tournament.teams

    def test_get_group_winners(self):
        winners = self.tournament.get_group_winners('A')
        self.assertEqual(winners[0].country, 'Brazil')
        self.assertEqual(winners[1].country, 'Mexico')
Example #22
0
    def score(self, tournament: Tournament, round: Round, match: Match):
        ViewTournament.result_menu(match)
        choice = input()
        if choice == '0':  # back last Menu
            return self.match_index(tournament, round)
        if choice == '1':
            match.set_result(1, 0)
        elif choice == '2':
            match.set_result(0, 1)
        elif choice == '3':
            match.set_result(0.5, 0.5)
        elif choice == '4':
            match.set_result(0, 0)
        else:
            return self.score(tournament, round, match)

        tournament.update_players_score()
        return self.match_index(tournament, round)
def create_game():
    game_id_name = request.form['game_number']
    winner_name = request.form['winner']
    loser_name = request.form['loser']
    game_id = game_repository.select(game_id_name)
    winner = player_repository.select(winner_name)
    loser = player_repository.select(loser_name)
    tournament = Tournament(game_id, winner, loser)
    tournament_repository.save(tournament)
    return redirect('/tournaments')
Example #24
0
    def DEMO_import_auto_tournament(self):
        """Create random info for a tournament
        """
        tournament_infos = {'tournament_name': f"tournament_name {random.randint(0, 1000)}",
                            'location': "Strasbourg",
                            'tour_number': '4',
                            'start_date': (
                                f'''{random.randint(10, 20)}/{random.randint(10, 12)}/'''
                                f'''{random.randint(1990, 2000)}'''
                                ),
                            'time_controller': random.randint(1, 3),
                            'number_of_players': '8',
                            'description': 'Description du tournois',
                            'id': str(uuid1())}
        tournament_infos['end_date'] = tournament_infos['start_date']
        tournament_obj = Tournament()
        tournament_obj.add_tournament(tournament_infos)
        self.add_multiple_players(int(tournament_obj.number_of_players), tournament_obj)

        self.generate_first_round(tournament_obj)
Example #25
0
    def set_match_results(self):
        # Get user to select tournament and match
        is_entering_score = True
        tournament_id = self.select_tournament()
        self._model = Tournament({'id': tournament_id})

        while is_entering_score:
            matches = self._model.get_matches(last_round=True)
            self._view.show_items(matches)
            match = self._view.get_user_choice(config.SELECT_MATCH,
                                               [*range(1,
                                                       len(matches) + 1)]) - 1
            final_scores = []
            count = 1
            # Get user to enter new scores
            for item in config.SET_SCORES:
                player = f'Player {count}'
                final_scores.append(
                    float(
                        self._view.get_user_input(
                            f"{config.SET_SCORES[item]} ({matches[match][player]})"
                        )))
                count += 1
            # Manage new scores entry
            self._model.set_match_results(match, final_scores)
            # Check if round matches scores are full
            if self._model.is_round_over():
                self._model.set_round_end()
                if len(self._model.rounds) < len(self._model.players) / 2:
                    self._model.create_new_round()
                    self._model.show_latest_pairs()
                else:
                    self._view.rounds_done()
                    is_entering_score = False
            else:
                # Ask for new entry
                new_entry = int(
                    self._view.get_user_choice(config.ADD_ANOTHER, [0, 1]))
                if not new_entry:
                    is_entering_score = False
        self.tournament_menu()
Example #26
0
    def get_tournaments_html(column):
        tournaments = []

        for link in column.find_all('li', recursive=False):
            item = link.find('a')
            if item:
                tournament_id = link.find('a').attrs.get('href').replace(
                    '/sport/tournament.aspx?id=', '')
                name = link.find('h4').a.span.text
                tournaments.append(Tournament(tournament_id, name))

        return tournaments
Example #27
0
 def load_tournament_list(self):
     my_list = Tournament.load_all()
     for tournament in my_list:
         player_list = [
             Participant(participant['id'], participant['score'], set(participant['old_matchs']))
             for participant in tournament['players']
         ]
         round_list = self.round_controller.load_round(tournament['round_list'])
         tournoi = Tournament(
             tournament.doc_id,
             tournament['name'],
             tournament['start_date'],
             tournament['end_date'],
             tournament['location'],
             player_list,
             tournament['time_control'],
             tournament['max_turn']
         )
         tournoi.round_list = round_list
         tournoi.actual_turn = tournament['actual_turn']
         self.tournament_list.append(tournoi)
Example #28
0
    def manage(self, tournament: Tournament):
        ViewTournament.menu(tournament)
        choice = input()
        if choice == '9':  #
            self.leaderboard(tournament)

        if choice == '0':  # back last Menu
            return self.index()
        if choice == '1':
            self.edit(tournament)
        if tournament.player_count < 2 * tournament.rounds_total:
            if choice == '2':  # load a player
                c = PlayerController()
                player_id = c.select_player()
                if player_id is not None:
                    tournament.add_player(player_id)
        elif not tournament.rounds or tournament.rounds[-1].is_closed():
            if choice == '3':  # generate matches
                tournament.generate_matches()
        else:
            if choice == '4':  # score match of current round
                return self.match_index(tournament, tournament.rounds[-1])
            cumulated_score = tournament.rounds[-1].total_scores()
            if (choice == '5' and cumulated_score
                    == tournament.rounds_total):  # close current round
                tournament.close_last_round()

        return self.manage(tournament)
Example #29
0
    def create(self):
        """Create a new tournmanent"""
        self.screen.info_users(
            ["               CREATION DE TOURNOI             \n\n\n"])
        self.screen.clear()
        self.screen.on_screen()
        tournament_infos = {}
        tournament_infos['id'] = max_id(tournaments_db) + 1
        tournament_infos['name'] = input("Nom du Tournoi : ")
        tournament_infos['location'] = input("Lieu du tournoi : ")
        tournament_infos['date_start'] = strftime("%A %d %B %Y %H:%M:%S")
        tournament_infos['date_end'] = "on_course"
        tournament_infos['total_round'] = ROUNDS_NB
        self.screen.info_users([
            "Choix du controleur de temps :\n", "           [1] Blitz \n",
            "           [2] Bullet \n", "           [3] Coup Rapide \n"
        ])
        self.screen.on_screen()

        controler_saisie = input_menu_verification(
            3, "Veuillez saisir le numéro correspondant à votre choix")

        if controler_saisie == 1:
            tournament_infos['time_controler'] = "Blitz"
        elif controler_saisie == 2:
            tournament_infos['time_controler'] = "Bullet"
        elif controler_saisie == 3:
            tournament_infos['time_controler'] = "Coup rapide"

        tournament_infos['description'] = input("Description : ")
        tournament_infos['players_list'] = []
        tournament_infos['rounds_list'] = []

        self.tournament = Tournament(tournament_infos)
        self.tournament.save(tournaments_db)
        self.players_on_load = []
        while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB:
            self.add_player_on_tournament()
            self.tournament.save(tournaments_db)
        self.play()
    def test_enter_score(self):
        """
        Enter a score for an entry
        """
        entry = TournamentEntry.query.filter_by(
            player_id=self.player, tournament_id=self.tourn_1).first()
        tourn = Tournament(self.tourn_1)

        # a one-off score
        Score(category=self.cat_1.name, tournament=tourn, entry_id=entry.id,
              score=0).write()
        scores = TournamentScore.query.\
            filter_by(entry_id=entry.id, tournament_id=tourn.get_dao().id).all()
        compare(len(scores), 1)
        compare(scores[0].score.value, 0)

        # a per_round score
        tourn.make_draws()

        round_id = TournamentRound.query.\
            filter_by(tournament_name=self.tourn_1, ordering=2).first().id
        game_id = TournamentGame.query.join(GameEntrant).\
            filter(and_(GameEntrant.entrant_id == entry.id,
                        TournamentGame.tournament_round_id == round_id)).\
                first().id
        Score(category=self.category_2.name, tournament=tourn, game_id=game_id,
              entry_id=entry.id, score=17).write()
        scores = GameScore.query.\
            filter_by(entry_id=entry.id, game_id=game_id).all()
        compare(len(scores), 1)
        compare(scores[0].score.value, 17)

        # score already entered
        score = Score(tournament=tourn, entry_id=entry.id, score=100,
                      category=self.cat_1.name)
        self.assertRaises(ValueError, score.write)

        score = Score(tournament=tourn, entry_id=entry.id, score=100,
                      category=self.category_2.name, game_id=game_id)
        self.assertRaises(ValueError, score.write)
Example #31
0
 def load_tournaments(self):
     """Load tournament from database
         - Get tournaments info from database
         - Create tournaments instances.
     """
     tournaments: list[dict] = self.database.get_all_tournaments()
     for tournament in tournaments:
         # We only create a new instance if we don't already have it
         if tournament['id'] not in (
                 tournament.id
                 for tournament in Tournament.TOURNAMENT_LIST):
             # create tournament object with attributs
             tournament_obj = Tournament()
             tournament_dict = {
                 'id': tournament['id'],
                 'tournament_name': tournament['tournament_name'],
                 'location': tournament['location'],
                 'start_date': tournament['start_date'],
                 'end_date': tournament['end_date'],
                 'tour_number': tournament['tour_number'],
                 'time_controller': tournament['time_controller'],
                 'number_of_players': tournament['number_of_players'],
                 'description': tournament['description']
             }
             tournament_obj.add_tournament(tournament_dict)
             # load round for this tournament
             self.load_rounds(tournament_obj)
             # bind player with this tournament
             tournament_player = []
             for player_id in tournament['players_list']:
                 tournament_player.append(
                     Player.get_player_by_id(player_id))
             tournament_obj.bind_multiple_players(tournament_player)
         else:
             pass
    def test_set_rounds(self):
        """change the number of rounds in a tournament"""
        name = 'test_set_rounds'
        self.injector.inject(name)

        tourn = Tournament(name)
        tourn._set_rounds(6)
        self.assertTrue(tourn.details()['rounds'] == 6)

        tourn._set_rounds(2)
        self.assertTrue(tourn.details()['rounds'] == 2)
    def setUp(self):
        super(ScoreCategoryTests, self).setUp()

        self.injector.inject(self.tourn_1)
        self.db.session.flush()
        self.db.session.commit()

        # Some default categories
        self.cat_1 = cat('painting', 10, False, 1, 20)
        self.cat_2 = cat('cat_battle', 80, True, 1, 20)
        self.cat_3 = cat('cat_sports', 10, True, 1, 5)

        self.tournament = Tournament(self.tourn_1)
def select_all():
    tournaments = []

    sql = "SELECT * FROM tournaments"
    results = run_sql(sql)

    for row in results:
        game = game_repository.select(row['game_id'])
        winner = player_repository.select(row['winner'])
        loser = player_repository.select(row['loser'])
        tournament = Tournament(game, winner, loser, row['id'])
        tournaments.append(tournament)
    return tournaments
    def setUp(self):
        super(EnterScore, self).setUp()
        self.injector.inject(self.tourn_1, num_players=5)
        tourn = Tournament(self.tourn_1)
        tourn.update({
            'rounds': 2,
            'missions': ['foo_mission_1', 'foo_mission_2']
        })
        self.injector.add_player(self.tourn_1, self.player)
        score_args = cat('per_tournament', 50, True, 0, 100)

        # per tournament category
        self.cat_1 = ScoreCategory(tournament_id=self.tourn_1, **score_args)
        self.db.session.add(self.cat_1)

        # per round category
        score_args['name'] = 'per_round'
        score_args['per_tournament'] = False
        self.category_2 = ScoreCategory(tournament_id=self.tourn_1,
                                        **score_args)
        self.db.session.add(self.category_2)
        self.db.session.commit()
    def setUp(self):
        super(TournamentInProgress, self).setUp()

        self.name = 'test_in_progress'
        self.player_1 = 'p1'

        self.injector.inject(self.name, num_players=0)
        self.injector.add_player(self.name, self.player_1)
        self.tournament = Tournament(self.name)
        self.tournament.update({
            'rounds': 1,
            'missions': ['mission01'],
            'score_categories': [score_cat_args('cat', 100, True, 1, 1, False)]
        })
Example #37
0
 def create_new_tournament(self):
     while True:
         (
             t_name,
             t_location,
             t_start_date,
             t_end_date,
             t_max_turn,
             t_player_cnt,
             t_play_style
         ) = self.view.new_tournament()
         tournament_validator = TournamentForm(
             t_name, t_location,
             t_start_date, t_end_date,
             t_max_turn, t_player_cnt, t_play_style
         )
         if tournament_validator.is_valid():
             break
     tournoi = Tournament(
         len(self.tournament_list),
         t_name,
         t_start_date,
         t_end_date,
         t_location,
         [],
         t_play_style,
         int(t_max_turn)
     )
     while len(tournoi.players) < int(t_player_cnt):
         player = self.player_controller.get_player()
         if not tournoi.check_by_id(player.id):
             tournoi.players.append(Participant(player.id))
         else:
             print('Ce joueur est déja présent dans le tournoi')
     self.tournament_list.append(tournoi)
     return tournoi
Example #38
0
 def index(self):
     c = main.MainController()
     ViewTournament.launch()
     choice = input()
     if choice == '0':  # back last Menu
         return c.index()
     if choice == '1':  # Create Tournament
         tournament = self.new()
         return self.manage(tournament)
     elif choice == '2':  # Retrieve Tournament
         tournament_id = self.select_tournament()
         if tournament_id is not None:
             tournament = Tournament.get_tournament(tournament_id)
             return self.manage(tournament)
     return self.index()
Example #39
0
 def create_tournament(self):
     """
     Method for initiating a new tournament
     """
     Player.initialise_players_data()
     super().__init__(
         Tournament(identity=None,
                    name=Tournament.NAME,
                    location=Tournament.LOCATION,
                    description=Tournament.DESCRIPTION,
                    timer=Tournament.TIMER,
                    max_rounds_number=Tournament.NB_ROUND))
     self.tournament.add_round()
     self.round = self.tournament.rounds[-1]
     self.launch_menu_round()
Example #40
0
    def get_all_tournaments_objs(self) -> list:
        """Summary of get_all_tournaments_objs.

        Returns:
            list: Description of return value
        """
        items = self.get_all_tournaments()
        objs = []
        for item in items:
            objs.append(
                Tournament(item['name'], item['place'], item['date'],
                           item['players'], item['time_control'],
                           item['description'], item['rounds'],
                           item['round_count']))
        return objs
Example #41
0
    def get_command(self):
        """Create a new tournament."""
        name = Input.for_string("Please enter tournament's name : ")
        location = Input.for_string("Please enter tournament's location : ")
        date = datetime.date.today().strftime("%d/%m/%Y")
        mode = Input.for_string("How would you like to play ? bullet / blitz / fast : ")
        nb_rounds = 4
        rounds = []
        serialized_rounds = []
        description = input("Please enter tournament's description : ")
        # CHOOSE BETWEEN AUTO or MANUAL list of players :
        players = self.create_auto_players()
        # players = self.create_list_players()

        tournament = Tournament(
            name, location, date, mode, nb_rounds, rounds, description, players
        )
        tournament.save()
        print(tournament)
        first_round = self.progress_first_round(
            tournament,
            players,
            serialized_rounds,
        )
        if first_round == "main menu":
            return "main menu"
        nb_rounds = tournament.nb_rounds
        next_round = self.progress_next_rounds(
            tournament,
            players,
            serialized_rounds,
            nb_rounds,
        )
        if next_round == "main menu":
            return "main menu"
        return "main menu"
    def test_get_missions(self):
        """get missions for the rounds"""
        name = 'test_get_missions'
        self.injector.inject(name)
        tourn = Tournament(name)
        tourn.update({
            'rounds': 3,
            'missions': ['mission_1', 'mission_2', 'mission_3']
        })


        tourn.update({'rounds': 4})
        compare(tourn.get_round(1).get_dao().mission, 'mission_1')
        compare(tourn.get_round(4).get_dao().mission, None)

        compare(Tournament(name).get_missions(),
                ['mission_1', 'mission_2', 'mission_3', 'TBA'])
class TournamentMissionsTests(AppSimulatingTest):

    tourn_1 = 'test_missions'

    def setUp(self):
        super(TournamentMissionsTests, self).setUp()

        self.injector.inject(self.tourn_1)
        self.tourn = Tournament(self.tourn_1)
        self.tourn.update({'rounds': 2})

    # pylint: disable=protected-access
    def test_add_missions(self):
        self.tourn.update({'missions': ['foo', 'bar']})

        self.assertRaises(ValueError, self.tourn._set_missions, [])
        self.assertRaises(ValueError, self.tourn.update, {'missions': []})
        self.assertRaises(ValueError, self.tourn._set_missions, ['1'])
        self.assertRaises(ValueError, self.tourn.update, {'missions': ['1']})
        self.assertRaises(ValueError, self.tourn._set_missions, ['1', '2', '3'])
        self.assertRaises(ValueError, self.tourn.update,
                          {'missions': ['1', '2', '3']})

    def test_get_missions(self):
        compare(self.tourn.get_missions(), ['TBA', 'TBA'])

        self.tourn.update({'missions': ['foo', 'bar']})
        compare(self.tourn.get_missions(), ['foo', 'bar'])

    def test_round_change(self):
        self.tourn.update({'rounds': 0})
        self.tourn.update({'rounds': 1})

        compare(self.tourn.get_round(1).get_dao().get_mission(), 'TBA')
class TournamentInProgress(AppSimulatingTest):

    def setUp(self):
        super(TournamentInProgress, self).setUp()

        self.name = 'test_in_progress'
        self.player_1 = 'p1'

        self.injector.inject(self.name, num_players=0)
        self.injector.add_player(self.name, self.player_1)
        self.tournament = Tournament(self.name)
        self.tournament.update({
            'rounds': 1,
            'missions': ['mission01'],
            'score_categories': [score_cat_args('cat', 100, True, 1, 1, False)]
        })

    def test_default_state(self):
        self.assertFalse(self.tournament.get_dao().in_progress)

    def test_no_categories(self):
        self.tournament.update({'score_categories': []})
        self.assertRaises(ValueError, self.tournament.set_in_progress)

    def test_no_entries(self):
        self.tournament.update({'rounds': 0})
        dao = self.tournament.get_dao()
        Reg.query.filter_by(tournament_id=dao.id).delete()
        TournamentEntry.query.filter_by(tournament_id=dao.name).delete()
        self.assertRaises(ValueError, self.tournament.set_in_progress)

    def test_no_missions(self):
        self.tournament.update({'rounds': 0})
        self.tournament.update({'rounds': 1})
        self.assertRaises(ValueError, self.tournament.set_in_progress)

    def test_no_rounds(self):
        self.tournament.update({'rounds': 0})
        self.assertRaises(ValueError, self.tournament.set_in_progress)

    def test_set_in_progress(self):
        self.tournament.set_in_progress()
        self.assertTrue(self.tournament.get_dao().in_progress)

    def test_non_finalised_only_actions(self):
        self.tournament.set_in_progress()

        args = score_cat_args('disallowed_cat', 100, True, 1, 1)
        self.assertRaises(ValueError, self.tournament.update,
                          {'score_categories': [args]})
        self.assertRaises(ValueError, self.tournament.update, {'rounds': 5})

        rego = Reg(self.player_1, self.name)
        rego.add_to_db()
        self.assertRaises(ValueError, self.tournament.confirm_entries)
 def setUp(self):
     self.tournament = Tournament()
     self.teams = self.tournament.teams
class ScoreCategoryTests(AppSimulatingTest):

    tourn_1 = 'test_score_categories'

    def setUp(self):
        super(ScoreCategoryTests, self).setUp()

        self.injector.inject(self.tourn_1)
        self.db.session.flush()
        self.db.session.commit()

        # Some default categories
        self.cat_1 = cat('painting', 10, False, 1, 20)
        self.cat_2 = cat('cat_battle', 80, True, 1, 20)
        self.cat_3 = cat('cat_sports', 10, True, 1, 5)

        self.tournament = Tournament(self.tourn_1)

    def test_categories_created(self):
        # Enter a cat
        self.tournament.update({'score_categories': [self.cat_1]})
        c_1 = ScoreCategory.query.\
            filter_by(name=self.cat_1['name']).first()
        compare(c_1.percentage, self.cat_1['percentage'])
        compare(c_1.per_tournament, self.cat_1['per_tournament'])
        compare(c_1.min_val, self.cat_1['min_val'])
        compare(c_1.max_val, self.cat_1['max_val'])

        # Enter multiple cats
        self.tournament.update({'score_categories': [self.cat_2, self.cat_3]})
        c_2 = ScoreCategory.query.\
            filter_by(name=self.cat_2['name']).first()
        compare(c_2.percentage, self.cat_2['percentage'])
        compare(c_2.per_tournament, self.cat_2['per_tournament'])
        compare(c_2.min_val, self.cat_2['min_val'])
        compare(c_2.max_val, self.cat_2['max_val'])

        c_3 = ScoreCategory.query.\
            filter_by(name=self.cat_3['name']).first()
        compare(c_3.percentage, self.cat_3['percentage'])
        compare(c_3.per_tournament, self.cat_3['per_tournament'])
        compare(c_3.min_val, self.cat_3['min_val'])
        compare(c_3.max_val, self.cat_3['max_val'])

    def test_old_categories_deleted(self):
        self.tournament.update({'score_categories': [self.cat_1]})
        self.tournament.update({'score_categories': [self.cat_2, self.cat_3]})

        # Double check cat 1 is deleted.
        compare(0, ScoreCategory.query.filter_by(name=self.cat_1['name']).\
            count())


    # pylint: disable=unused-variable
    def test_broken_min_max(self):
        neg_min = cat('painting', 10, False, -1, 20)
        neg_max = cat('painting', 10, False, 1, -1)
        zero_max = cat('painting', 10, False, 0, 0)
        min_high = cat('painting', 10, False, 10, 9)
        zero_min = cat('painting', 10, False, 0, 20)
        equal = cat('painting', 10, False, 1, 1)
        no_min = cat('painting', '10', False, '', 20)
        no_max = cat('painting', '10', False, 1, '')
        none_min = cat('painting', '1', False, None, 1)
        none_max = cat('painting', '1', False, 1, None)
        char_min = cat('painting', '1', False, 'a', 1)
        char_max = cat('painting', '1', False, 1, 'a')

        func = self.tournament.update
        self.assertRaises(ValueError, func, {'score_categories': [neg_min]})
        self.assertRaises(ValueError, func, {'score_categories': [neg_max]})
        self.assertRaises(ValueError, func, {'score_categories': [zero_max]})
        self.assertRaises(ValueError, func, {'score_categories': [min_high]})
        self.assertRaises(ValueError, func, {'score_categories': [no_min]})
        self.assertRaises(ValueError, func, {'score_categories': [no_max]})
        self.assertRaises(ValueError, func, {'score_categories': [none_min]})
        self.assertRaises(ValueError, func, {'score_categories': [none_max]})
        self.assertRaises(ValueError, func, {'score_categories': [char_min]})
        self.assertRaises(ValueError, func, {'score_categories': [char_max]})


    def test_broken_categories(self):
        # cat should perform input validation only
        fifty_one = cat('painting', 51, False, 1, 20)
        neg_pct = cat('painting', -1, False, 1, 20)
        zero_pct = cat('painting', 0, False, 1, 20)
        lge_pct = cat('painting', 101, False, 1, 20)
        char_pct = cat('painting', 'a', False, 1, 20)
        no_name = cat('', 10, False, 1, 20)
        none_name = cat(None, 10, False, 1, 20)

        func = self.tournament.update
        self.assertRaises(ValueError, func, {'score_categories': [neg_pct]})
        self.assertRaises(ValueError, func, {'score_categories': [zero_pct]})
        self.assertRaises(ValueError, func, {'score_categories': [lge_pct]})
        self.assertRaises(ValueError, func, {'score_categories': [char_pct]})
        self.assertRaises(ValueError, func, {'score_categories': [no_name]})
        self.assertRaises(ValueError, func, {'score_categories': [none_name]})
        self.assertRaises(ValueError, func,
                          {'score_categories': [fifty_one, fifty_one]})
    def setUp(self):
        super(TournamentMissionsTests, self).setUp()

        self.injector.inject(self.tourn_1)
        self.tourn = Tournament(self.tourn_1)
        self.tourn.update({'rounds': 2})