def main(): ''' Main function permits to launch a match of Quarto It permits also to modify game configuration (mainly players attributes) ''' hostname = None if len(argv) == 2: hostname = argv[1] configuration = { 'name_player1': 'Mr. R', 'name_player2': 'Mr. N', 'intelligence_player1': Minimax(3), 'intelligence_player2': Minimax(4), 'hostname': hostname } choice = None while choice != "q": ui.showMenu() try: choice = ui.askChoice(("p", "t", "c", "q")).lower() except EOFError: choice = "q" if choice == "p": match = Match(configuration) match.run() elif choice == "t": try: tournament = Tournament(configuration) tournament.run() except Exception, e: print e elif choice == "c": configuration = change_configuration()
def create_tournament(): """Création d'un tournois, instanciation de la class puis sauvegarde en tan que tournois actif. :return: """ name = input("Nom du Tournois: ") place = input("Emplacement du Tournois: ") date = input("Date du Tournois: ") rounds = input("Nombre de tours: ") number_of_players = input("Nombre de joueurs: ") time_control = input("Contrôle du temps: ") comment = input("Commentaire: ") rounds = convert_to_integer(rounds) number_of_players = convert_to_integer(number_of_players) if not rounds or rounds < 1: print("Le nombre de tours dois être un entier positif.") return if not number_of_players or number_of_players < 2: print("Il faut que le nombre de joueurs soit égal ou supérieur à 2") return tournament = Tournament({ "name": name, "place": place, "date": date, "rounds": rounds, "time_control": time_control, "comment": comment, }) # Add players... for _ in range(number_of_players): print(f"Ajout du joueur {_ + 1} sur {number_of_players}") add_player(tournament) tournament.save()
def main(): print("Welcome to this game") # Getting inputs from the user for player 1 player1_name = input("Player 1, enter your name!: ") player1_type = input("Player 1, enter your type!: ") player1_class = TYPE_TO_CLASS_MAP[player1_type.lower()] # Checks if player 1 is the type, Historian. # Since Historian have an extra input. if player1_type == 'hist': player1_remember = int(input("Player 1, enter remember value!: ")) player1 = player1_class(player1_name, player1_remember) else: player1 = player1_class(player1_name) player2_name = input("Player 2, enter your name!: ") player2_type = input("Player 2, enter your type!: ") player2_class = TYPE_TO_CLASS_MAP[player2_type.lower()] if player2_type == 'hist': player2_remember = int(input("Player 2, enter remember value!: ")) player2 = player2_class(player2_name, player2_remember) else: player2 = player2_class(player2_name) num_games = int(input("Enter number of games to be played: ")) tourny = Tournament(player1, player2, num_games) tourny.arrange_tournament()
def load_tournaments(season: Season): """Loads all tournaments progress for a season from file. :param season: The season to load the tournaments progress for. :return: The newly loaded tournaments. """ tournaments = HashTable() with open('%s/%s/progress.csv' % (OUTPUT, season.name)) as the_file: for line in the_file: # Parse the seasons name and whether it's complete. csv = parse_csv_line(line) name = csv[0] complete = parse_bool(csv[1]) men_round = int(csv[2]) women_round = int(csv[3]) tournament_type = season.circuit.tournament_types.find(name) # Find the previous seasons tournament, if there is any. previous = None if season.previous is not None: previous = season.previous.tournaments.find(name) # Create and load the tournament. tournament = Tournament(season, tournament_type, previous, complete) tournament.men_track = load_track(tournament, 'men', men_round) tournament.women_track = load_track(tournament, 'women', women_round) # Add newly created tournament to this season. tournaments.insert(tournament.type.name, tournament) return tournaments
def display_leader_board(tournament: Tournament): tournament.sort_challengers_by_score() reset_display() title = "Classement" left = (WIDTH - 3 * FONT_SIZE * len(title) // 8) / 2 display_text(pos_x=left, pos_y=HEIGHT // 6, content=title, surface=objectiveSurface, font_size=FONT_SIZE + 16) left_start = WIDTH // 5 left_points = WIDTH // 5 + 3 * 30 * FONT_SIZE // 8 left_games = WIDTH // 5 + 3 * 20 * FONT_SIZE // 8 for i, challenger in enumerate(tournament.challengers_pool): if i % 2 == 0: challenger_color = (255, 241, 0) points_color = (255, 50, 0) games_color = (0, 255, 50) else: challenger_color = (150, 255, 0) points_color = (250, 150, 0) games_color = (0, 255, 150) duels_nb = len(tournament.seen_duels[challenger] ) if challenger in tournament.seen_duels.keys() else 0 challenger_info = str(i + 1) + " - " + challenger.name points_info = " Points : " + str(challenger.points) game_info = " Parties : " + str(duels_nb) top = 2 * HEIGHT / 6 + (i + 1) * FONT_SIZE objective_rubber = pygame.Surface( (len(challenger_info) * FONT_SIZE, FONT_SIZE)) objective_rubber.fill((0, 0, 0)) display_text(left_start, top, challenger_info, objectiveSurface, objective_rubber, text_color=challenger_color) points_rubber = pygame.Surface( (len(challenger_info) * FONT_SIZE, FONT_SIZE)) points_rubber.fill((0, 0, 0)) display_text(left_games, top, game_info, objectiveSurface, points_rubber, text_color=games_color) display_text(left_points, top, points_info, objectiveSurface, points_rubber, text_color=points_color)
def start_tournament(self): #print("starting tournament") run_tournament = Tournament(self.tournament, self.players, self.default_player_path) participating_players = run_tournament.get_participating_players() for p in participating_players: self.close_connection(p) run_tournament.print_results()
def active_tournament_info(): tournament = Tournament({}) tournament.restore() print("Tournois actif:\n" "---------------\n" f"Nom: {tournament.name}\n" f"Date: {tournament.date}\n" f"Tour actif: {tournament.active_tour + 1}")
def test_minimax(lookahead_limit): mms = NnMiniMaxStrategy(NetworkBEnsemble('N'), lookahead_limit, ['N', 'X']) p1 = Player('N', mms) p2 = Player('X', MctsStrategy(1000)) tournament = Tournament(100, [p2, p1]) result = tournament.run(False, lambda r: print('.', end='', flush=True)) print(' ') print(lookahead_limit, result, mms.average_move_time(), flush=True)
def tournament_score(): tournament = Tournament({}) tournament.restore() for _ in tournament.players: print( f"Joueur: {_.surname} {_.forename} - " f"{tournament.score_player(_)} point(s)." )
def run(self): logging.basicConfig( format=_red + "[%(levelname)s][%(asctime)s][%(name)s] %(message)s" + _normal, datefmt="%m/%d/%Y %H:%M:%S", level=logging.WARN) genome = self.create_genome() population = NEAT.Population(genome, self.neat_parameters, True, 1.0, 0) previous_best_genomes = None current_best_genomes = None difference = 0 self.LOGGER.warn("Population size: {}".format(population.NumGenomes())) self.LOGGER.warn( "{:>14s} {:>14s} {:>14s} {:>14s} {:>14s} {:>14s}".format( "n_species", "stagnation", "mpc", "search_mode", "compat_thresh", "improvement")) # run for 100 generations for generation in range(200): tournament = Tournament(population, self.table_size, self.money_vector_size, self.buy_in, self.min_denomination, self.tournament_rounds) tournament.play() if current_best_genomes: previous_best_genomes = current_best_genomes current_best_genomes = self.get_best_n_genomes( population, self.table_size // 2) if previous_best_genomes: playoff = PlayOff(current_best_genomes, previous_best_genomes, self.table_size, self.money_vector_size, self.buy_in, self.min_denomination, self.tournament_rounds) difference += playoff.play() for index in range(population.NumGenomes()): genome = population.AccessGenomeByIndex(index) genome.SetFitness(genome.GetFitness() + difference) self.LOGGER.warn( "{:14d} {:14d} {:14.2f} {:>14s} {:14.3f} {:14.2f}".format( len(population.Species), population.GetStagnation(), population.GetCurrentMPC(), population.GetSearchMode().name, population.Parameters.CompatTreshold, difference)) population.Epoch() self.LOGGER.warn("Training complete") return self.get_best_n_genomes(population, self.table_size)
def test_minimax(lookahead_limit): mms = NnMiniMaxStrategy(NetworkBEnsemble('N'), lookahead_limit, 'N', 'X', alpha_beta_pruning) p1 = Player('N', mms) p2 = Player('X', MctsStrategy(1000)) tournament = Tournament(100, [p2, p1]) result = tournament.run(False) print(' ') print(lookahead_limit, result, mms.average_move_time(), flush=True)
class test_Tournament(unittest.TestCase): def setUp(self): self.t = Tournament("MEconflicts.csv") self.t.create() def test_participants(self): self.assertEqual(len(self.t.participants), 24) def test_poolMax(self): self.assertEqual(self.t.poolMax, 6) def test_poolCount(self): self.assertEqual(self.t.poolCount, 4) def test_poolsLen(self): self.assertEqual(len(self.t.pools), 4) def test_poolContEqpoolsLen(self): self.assertEqual(len(self.t.pools), self.t.poolCount) def test_schoolPoolMax(self): self.assertEqual(self.t.schoolPoolMax['EBFG'], 2) self.assertEqual(self.t.schoolPoolMax['NO FEAR'], 2) self.assertEqual(self.t.schoolPoolMax['LOUISVLLE F.C.'], 1) self.assertEqual(self.t.schoolPoolMax['MEDEO F.C.'], 1) self.assertEqual(self.t.schoolPoolMax['OLYMPIANFC / USMPENT'], 1) self.assertEqual(self.t.schoolPoolMax['METRO TACOMA'], 1) self.assertEqual(self.t.schoolPoolMax['FISHKILL / CANDLE'], 1) self.assertEqual(self.t.schoolPoolMax['unafilliated'], 5) def test_pools(self): for i in self.t.pools: self.assertIn(i.poolSize, [5, 6]) for key in i.schools: self.assertLessEqual(i.schools[key], self.t.schoolPoolMax[key]) def test__calculatePoolSize(self): self.t.participants = [x for x in range(12)] self.t._calculatePoolSize() self.assertEqual(self.t.poolCount, 2) self.assertEqual(self.t.poolMax, 6) self.t.participants = [x for x in range(13)] self.t._calculatePoolSize() self.assertEqual(self.t.poolCount, 2) self.assertEqual(self.t.poolMax, 7) self.t.participants = [x for x in range(16)] self.t._calculatePoolSize() self.assertEqual(self.t.poolCount, 2) self.assertEqual(self.t.poolMax, 8) self.t.participants = [x for x in range(17)] self.t._calculatePoolSize() self.assertEqual(self.t.poolCount, 3) self.assertEqual(self.t.poolMax, 6)
def sorted_by_rank(): tournament = Tournament({}) tournament.restore() print("\nAffichage des joueurs par rang:\n" "-------------------------------\n") ranked_players = tournament.list_players_by_rank() rank = 0 for _ in ranked_players: rank += 1 print(f"{rank} - {_.rank} {_.surname}" f" {_.forename}")
async def new(ctx, *args): if len(args) < 2: await ctx.send( "``Usage: ~~new_tournament <name> <player1> <player2> ... ``") name = args[0] players = args[1:] print(players) new_tournament = Tournament(name, players) new_tournament.save() await ctx.send("``Tournament Added:\n" + name + "``")
def test_sm_import_and_export(): test_sm_export_filepath = Path(__file__).parent / 'poznan/poznan.re' tour = Tournament('Poznań 2018', 'GW', 'Poznań') tour.read_from_scrabble_manager(test_sm_export_filepath) with TemporaryDirectory() as tmpdir: tour.export_t(Path(tmpdir) / 'test_a.t') new_tour = Tournament('Poznań 2018', 'GW', 'Poznań') new_tour.read_from_t(Path(tmpdir) / 'test_a.t') new_tour.export_re(Path(tmpdir) / 'test_re.re') assert cmp(test_sm_export_filepath, Path(tmpdir) / 'test_re.re')
def sorted_by_names(): tournament = Tournament({}) tournament.restore() print("\nAffichage des joueurs par ordre alphabétique:\n" "---------------------------------------------\n") ranked_players = tournament.list_players_by_names() rank = 0 for _ in ranked_players: rank += 1 print(f"{rank} - {_.surname} {_.forename}")
def test_record_past_rounds(): tourney = Tournament(['a', 'b', 'c', 'd', 'e'], DummyRoundGenerator()) tourney.startNextRound() tourney.startNextRound() past_rounds = tourney.pastRounds() # expects 2 nonempty past rounds with all unique game ids return len(past_rounds) == 2 \ and len(past_rounds[0]) > 0\ and len(past_rounds[1]) > 0 \ and len(set(past_rounds[0]) & set(past_rounds[1])) == 0
def create_rounds(tournament_list): """ Use the tournament_list object list, that was returned from the create_tournaments function, which contains 15 Tournament objects with the following instance variables: tourn_id, tourn_name, golf_course_id, start_date, num_rounds, num_golfers, golfers... Create num_rounds Round objects from every Tournament object element in tournament_list: Add in the following as instance variables values round_id, tourn_id, day A list is returned, where each element is a Round object """ print("\nThe Round object list\n") rounds_list = [] round_id = 1 for tourn in tournament_list: number_rounds = Tournament.get_num_rounds(tourn) tourn_id = Tournament.get_tourn_id(tourn) num_rounds = number_rounds for item in range(number_rounds): if num_rounds == 4: day = "Thu" elif num_rounds == 3: day = "Fri" elif num_rounds == 2: day = "Sat" elif num_rounds == 1: day = "Sun" num_rounds = num_rounds - 1 round = Round(round_id, tourn_id, day) rounds_list.append(round) round_id = round_id + 1 for round_info in rounds_list: print(round_info) return rounds_list
def create_tournament_from_lobby(lobby_id): if request.method == 'POST': # verify that TO is attempting to access lobby uid = g.user.id uname = g.user.username try: lobby = LobbyModel.query.filter_by(id=lobby_id).first_or_404() if uid != lobby.to_id: key = 'Unauthorized' val = \ f'{g.user.username} cannot create a tournament ' + \ 'using this lobby' content = {key: val} return content, status.HTTP_401_UNAUTHORIZED except NotFound as e: key = str(e).split(':')[0] val = f'lobby {lobby_id} does not exist' content = {key: val} return content, status.HTTP_404_NOT_FOUND # get all competitors in the lobby lobby_entrants = LobbySeed.query.filter_by(lobby_id=lobby_id).all() # construct a list of user_id, seed pairs tuple_list = [(e.user.username, e.seed) for e in lobby_entrants] bracket_type = BracketTypes.DOUBLE_ELIMINATION tournament_name = lobby.tournament_name # contruct a tournament object t = Tournament(tuple_list, bracket_type) t_id = t.post_to_db(tournament_name, uname) # set this lobby's tournament_id lobby.tournament_id = t_id for r in t.bracket.rounds: for m in r.matches: m.post_self_refs() # delete the lobby LobbyModel.query.filter_by(id=lobby_id).delete() LobbySeed.query.filter_by(lobby_id=lobby_id).delete() db.session.commit() content = { 'Success': 'Tournament created', 'tournament_id': t_id, 'tournament_name': tournament_name } return content, status.HTTP_200_OK
def main(): args = tournament_args() logger = tournament_logger(verbose=args.verbose, log_file=args.log_file) players = [Player(invocation) for invocation in args.players] tournament = Tournament(players, args.num_games, args.size, args.time_limit, logger) tournament.play_tournament() for p in players: p.exit()
def main(): f = Field('30x50 yards ', 'grass') all_players = Roster() r = all_players.roster tourney = Tournament() divided_teams = tourney.make_teams(r) # # print(test) winner = tourney.compute_winner() print("These are the teams:\n") for t in range(len(divided_teams)): print("{}\n".format(divided_teams[t])) print("The winner is: \033[1;32m{}\033[0m".format(winner))
def __init__(self, name, meta): """Initialize a tournament and fill it with decks, based on the given metagame.""" Tournament.__init__(self, name=name, numPlayers=meta.total) self.meta = meta self.byes = set() self.players = [] p = 1 for main in meta.archetypes: for sub in meta.archetypes[main]: for i in range(meta.archetypes[main][sub]): deck = Deck(player=str(p), tournament=self, points=0, archetype=main, subarchetype=sub) self.players.append(deck) p += 1
class TestTournamentMultipleTournaments(TestTournament): """ Repeat all tests with additional tournaments int he database. """ def setUp(self): self.t = Tournament() self.t2 = Tournament() self.t3 = Tournament() self.t.deleteMatches() self.t.deletePlayers() def testMultiTournamets(self): self.assertNotEqual(self.t.tournId, self.t2.tournId, "Tournament IDs should be different for different tournaments.")
def main(stdscr): tourny = None if len(sys.argv) > 1: tourny = Tournament.fromFile(sys.argv[1]) interface = Interface(stdscr, tourny) interface.run()
def test_pickle(): tourney = Tournament(['a', 'b'], SingleEliminationGenerator()) tourney.setScore(0, (1, 0), 0) tourney.saveToFile('test.pkl') tourney2 = Tournament.fromFile('test.pkl') return set(tourney.getTeams()) == set(tourney2.getTeams()) \ and tourney2.roundCompleted()
class test_Tournament(unittest.TestCase): def setUp(self): self.t = Tournament("MEconflicts.csv") self.t.create() def test_participants(self): self.assertEqual(len(self.t.participants) ,24) def test_poolMax(self): self.assertEqual(self.t.poolMax, 6) def test_poolCount(self): self.assertEqual(self.t.poolCount, 4) def test_poolsLen(self): self.assertEqual(len(self.t.pools), 4) def test_poolContEqpoolsLen(self): self.assertEqual(len(self.t.pools), self.t.poolCount) def test_schoolPoolMax(self): self.assertEqual(self.t.schoolPoolMax['EBFG'],2) self.assertEqual(self.t.schoolPoolMax['NO FEAR'], 2) self.assertEqual(self.t.schoolPoolMax['LOUISVLLE F.C.'], 1) self.assertEqual(self.t.schoolPoolMax['MEDEO F.C.'], 1) self.assertEqual(self.t.schoolPoolMax['OLYMPIANFC / USMPENT'], 1) self.assertEqual(self.t.schoolPoolMax['METRO TACOMA'], 1) self.assertEqual(self.t.schoolPoolMax['FISHKILL / CANDLE'], 1) self.assertEqual(self.t.schoolPoolMax['unafilliated'], 5) def test_pools(self): for i in self.t.pools: self.assertIn(i.poolSize,[5,6]) for key in i.schools: self.assertLessEqual(i.schools[key], self.t.schoolPoolMax[key]) def test__calculatePoolSize(self): subtests = [(12,2,6),(13,2,7),(16,2,8),(17,3,6)] for totalEntries, poolCount, poolMax in subtests: with self.subTest(totalEntries): self.t.totalEntries = totalEntries self.t._calculatePoolSize() self.assertEqual(self.t.poolCount,poolCount) self.assertEqual(self.t.poolMax, poolMax)
def main(): """Main predict method""" if len(sys.argv) != 2: print __doc__ sys.exit(1) else: tournament = Tournament.from_json(sys.argv[1], WebPredictor()) print tournament.calculate_prediction()
def self_play_group(count): global tournament networks = [NetworkB(i + 1) for i in range(count)] strategies = [NnStrategy(n, get_exploration_factor) for n in networks] players = [Player('B' + str(i), s) for i, s in enumerate(strategies)] for round in range(1, training_rounds): print('Benchmarking before round', round) for benchmark in [MctsStrategy(1000)]: for network in networks: ns = NnStrategy(network) p1 = Player('N', ns) p2 = Player('B', benchmark) tournament = Tournament(benchmark_batch_size, [p1, p2]) results = tournament.run(False) print('Results for {} vs {}: {}'.format( benchmark.get_name(), ns.get_name(), results)) log('{},{}:{},{}:{}'.format((round - 1) * self_play_batch_size, ns.get_name(), results.get('N', 0), benchmark.get_name(), results.get('B', 0))) for p1, p2 in itertools.combinations(players, 2): print('Self-play training {} vs {}'.format(p1.id, p2.id), end='', flush=True) tournament = Tournament(self_play_batch_size, [p1, p2]) tournament.run(True, lambda r: print('.', end='', flush=True)) print('') print('- - - - - - - - - -')
def test_everyone_plays(self, player_count=24): test_tournament = Tournament() test_tournament.gen_sim_players(player_count) rounds = num_rounds(player_count) rounds_played = 0 while rounds > 0: test_tournament.almafi_pairing(rounds) test_tournament.sim_round() rounds_played += 1 for sim_player in test_tournament.rank_players(): with self.subTest(): self.assertEqual(len(sim_player.opp_list), rounds_played * 2) rounds -= 1
def main(): parser = ArgumentParser() parser.add_argument("--year", help="The year tournament took place.") parser.add_argument("--players", help="Amount of players competing, powers of 2 only excluding 1") args = parser.parse_args() if args.year: if args.players: tournament = Tournament(players=int(args.players), year=args.year) else: tournament = Tournament(year=args.year) else: if args.players: tournament = Tournament(players=int(args.players)) else: tournament = Tournament() tournament.simulate()
def main(): start_time = time.time() mode, path = argv[1], argv[2] use_db = len(argv) > 3 and argv[3] == 'write' full_stats = len(argv) > 4 and argv[4] == 'full' tournaments = {} if mode == 'f': tournaments = dict(tournaments, **parse_file(path)) elif mode == 'd': for filename in listdir(path): if filename.endswith('txt') and filename != 'requirements.txt': parsed_tournaments = parse_file(path + '//' + filename) for k, v in parsed_tournaments.items(): if k not in tournaments: tournaments[k] = v else: for hand_id in v.keys(): if hand_id not in tournaments[k]: tournaments[k][hand_id] = v[hand_id] tournobjs = [] for k, v in tournaments.items(): tournament_id, buyin_cents, rake_cents = k tournament = Tournament(tournament_id, buyin_cents, rake_cents, list(v.values())) tournament.finalize() tournobjs.append(tournament) tournobjs.sort(key=lambda t: t.start_time) elapsed = '%.2f' % (time.time() - start_time) print(f'Found {len(tournobjs)} tournaments in {elapsed} seconds.') if tournobjs: handle_stats(tournobjs, full_stats) if use_db: update_database(tournobjs) plot.plot_tournaments(tournobjs, 'plots//results.svg')
def tournaments_list(): print("Liste des tournois sauvegardés:\n" "-------------------------------\n") db = TinyDB("data/db.json") tournaments_table = db.table("tournaments") count = 0 for _ in tournaments_table: count += 1 tournament = Tournament(jsonpickle.decode(_["Tournaments"]).__dict__) print(f"{count} - {tournament.name}")
def getChild(self, name, request): name = urllib.unquote(name).decode("utf-8") if name == '': return self elif name == 'new': return NewTournament(self.manager) elif self.manager.tournaments.get(name): return Tournament(self.manager, self.manager.tournaments.get(name)) else: return NoResource()
def play_tournament(self): """Play a tournament with multiple matches.""" t = Tournament(self.number_of_games, self.player_list, self.game_arity, self.time_limits, self.verbose, self.show_map) t.play_all_games() t.print_win_data()
def __init__(self, name, dealsDefinition): #dealsDefinition: list of dealsets (no external ID) #each dealset list of matches in format # (NSpair, EWPair) Tournament.__init__(self, name) dealsetID = 0 onlyRound = [] deals = {} self.rounds = [onlyRound] self.Nrounds = 1 self.nPairs = 0 #assuming pairs numbered 1..nPairs for dealset in dealsDefinition: for m in dealset: a = m[0] b = m[1] if a>self.nPairs: self.nPairs = a if b>self.nPairs: self.nPairs = b onlyRound.append(Match(a-1, b-1, dealsetID)) dealsetID +=1
if position_player in self.point_position: score_position = self.point_position[position_player] for i in range(len(score_player)): score_total += int(score_player[i]) * int(score_position[i]) return score_total # player 1;nick1;4;Team A;G;10;2;7 # player 2;nick2;8;Team A;F;0;10;0 # player 3;nick3;15;Team A;C;15;10;4 # player 4;nick4;16;Team B;G;20;0;0 # player 5;nick5;23;Team B;F;4;7;7 # player 6;nick6;42;Team B;C;8;10;0 my_tournament = Tournament() my_tournament.create_game("basketball", Basketball()) strPlayer = "player 1;nick1;4;Team A;G;10;2;7" strPlayer2 = "player 2;nick2;8;Team A;F;0;10;0" strPlayer3 = "player 4;nick4;16;Team B;G;20;0;0" my_tournament.parser("basketball", strPlayer) my_tournament.parser("basketball", strPlayer2) my_tournament.parser("basketball", strPlayer3) my_tournament.create_game("basketballHARD", Basketball()) strPlayer = "player 1;nick1;4;Team A;G;10;2;7" strPlayer2 = "player 2;nick2;8;Team A;F;0;10;0" strPlayer3 = "player 4;nick4;16;Team B;G;230;0;0" my_tournament.parser("basketballHARD", strPlayer) my_tournament.parser("basketballHARD", strPlayer2)
import drabinkaGUI from PyQt4 import QtCore, QtGui from PyQt4.QtCore import SIGNAL, SLOT import sys, string, re, os import player from tournament import Tournament app = QtGui.QApplication(sys.argv) t=Tournament("atgsahgajj", "hdgytra") t.createMatchList() mainWindow = drabinkaGUI.drabinkaGUI(text_parent=t) mainWindow.show() sys.exit(app.exec_())
def get_tournament_fittest(self): tournament = Tournament() tournament.randomly_populate(self.current_population, self.tournament_size) return tournament.get_fittest(self.target_individual)
def setUp(self): self.t = Tournament() self.t.deleteMatches() self.t.deletePlayers()
class TestTournament(unittest.TestCase): def setUp(self): self.t = Tournament() self.t.deleteMatches() self.t.deletePlayers() def tearDown(self): self.t.deleteTournamnets() self.t.deleteMatches() self.t.deletePlayers() del self.t def test_DeleteMatches(self): self.t.deleteMatches() print "Old matches can be deleted." def testDelete(self): self.t.deletePlayers() print "Player records can be deleted." def testCount(self): c = self.t.countPlayers() if c == '0': raise TypeError( "countPlayers() should return numeric zero, not string '0'.") if c != 0: raise ValueError("After deleting, countPlayers should return zero.") print "After deleting, countPlayers() returns zero." def testRegister(self): self.t.registerPlayer("Chandra Nalaar") c = self.t.countPlayers() if c != 1: raise ValueError( "After one player registers, countPlayers() should be 1.") print "After registering a player, countPlayers() returns 1." def testRegisterCountDelete(self): self.t.registerPlayer("Markov Chaney") self.t.registerPlayer("Joe Malik") self.t.registerPlayer("Mao Tsu-hsi") self.t.registerPlayer("Atlanta Hope") c = self.t.countPlayers() if c != 4: raise ValueError( "After registering four players, countPlayers should be 4.") self.t.deletePlayers() c = self.t.countPlayers() if c != 0: raise ValueError("After deleting, countPlayers should return zero.") print "Players can be registered and deleted." def testStandingsBeforeMatches(self): self.t.registerPlayer("Melpomene Murray") self.t.registerPlayer("Randy Schwartz") standings = self.t.playerStandings() if len(standings) < 2: raise ValueError("Players should appear in playerStandings even before " "they have played any matches.") elif len(standings) > 2: raise ValueError("Only registered players should appear in standings.") if len(standings[0]) != 4: raise ValueError("Each playerStandings row should have four columns.") [(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0: raise ValueError( "Newly registered players should have no matches or wins.") if set([name1, name2]) != set(["Melpomene Murray", "Randy Schwartz"]): raise ValueError("Registered players' names should appear in standings, " "even if they have no matches played.") print "Newly registered players appear in the standings with no matches." def testReportMatches(self): self.t.registerPlayer("Bruno Walton") self.t.registerPlayer("Boots O'Neal") self.t.registerPlayer("Cathy Burton") self.t.registerPlayer("Diane Grant") standings = self.t.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] self.t.reportMatch(id1, id2) self.t.reportMatch(id3, id4) standings = self.t.playerStandings() for (i, n, w, m) in standings: if m != 1: raise ValueError("Each player should have one match recorded.") if i in (id1, id3) and w != 1: raise ValueError("Each match winner should have one win recorded.") elif i in (id2, id4) and w != 0: raise ValueError("Each match loser should have zero wins recorded.") print "After a match, players have updated standings." def testPairings(self): self.t.deleteMatches() self.t.deletePlayers() self.t.registerPlayer("Twilight Sparkle") self.t.registerPlayer("Fluttershy") self.t.registerPlayer("Applejack") self.t.registerPlayer("Pinkie Pie") standings = self.t.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] self.t.reportMatch(id1, id2) self.t.reportMatch(id3, id4) pairings = self.t.swissPairings() if len(pairings) != 2: raise ValueError( "For four players, swissPairings should return two pairs.") [(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4)] = pairings correct_pairs = set([frozenset([id1, id3]), frozenset([id2, id4])]) actual_pairs = set([frozenset([pid1, pid2]), frozenset([pid3, pid4])]) if correct_pairs != actual_pairs: raise ValueError( "After one match, players with one win should be paired.") print "After one match, players with one win are paired." def testHaveMathced(self): self.t.registerPlayer("Player 1") self.t.registerPlayer("Player 2") self.t.registerPlayer("Player 3") self.t.registerPlayer("Player 4") standings = self.t.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] self.t.reportMatch(id1, id2) self.t.reportMatch(id4, id3) matches = self.t.getMatches() self.assertTrue(self.t._haveMatched(id1, id2, matches)) self.assertTrue(self.t._haveMatched(id2, id1, matches)) self.assertTrue(self.t._haveMatched(id3, id4, matches)) self.assertFalse(self.t._haveMatched(id1, id3, matches)) self.assertFalse(self.t._haveMatched(id3, id1, matches)) def testNoRematches(self): self.t.registerPlayer("Player 1") self.t.registerPlayer("Player 2") self.t.registerPlayer("Player 3") self.t.registerPlayer("Player 4") self.t.registerPlayer("Player 5") self.t.registerPlayer("Player 6") self.t.registerPlayer("Player 7") self.t.registerPlayer("Player 8") self.t.registerPlayer("Player 9") self.t.registerPlayer("Player 10") self.t.registerPlayer("Player 11") self.t.registerPlayer("Player 12") standings = self.t.playerStandings() [id1, id2, id3, id4, id5, id6, id7, id8, id9, id10, id11, id12] = [row[0] for row in standings] # Round 1 self.t.reportMatch(id1, id2) self.t.reportMatch(id4, id3) self.t.reportMatch(id5, id6) self.t.reportMatch(id7, id8) self.t.reportMatch(id9, id10) self.t.reportMatch(id12, id11) # Round 2 self.t.reportMatch(id4, id1) self.t.reportMatch(id5, id7) self.t.reportMatch(id9, id12) self.t.reportMatch(id3, id2) self.t.reportMatch(id6, id8) self.t.reportMatch(id11, id10) # Round 3 self.t.reportMatch(id4, id5) self.t.reportMatch(id9, id1) self.t.reportMatch(id7, id11) self.t.reportMatch(id3, id12) self.t.reportMatch(id2, id6) self.t.reportMatch(id10, id8) pairings = self.t.swissPairings() self.assertFalse((id6, 'Player 6', id10, 'Player 10') in pairings, "Two players should not play against each onther more than once.") print "Rematches are prevented."
def test_prediction_calculation(self): path = 'test_tournament.json' tournament = Tournament.from_json(path, WebPredictor()) final_prediction = tournament.calculate_prediction() self.assertEquals(len(final_prediction), 5) self.assertAlmostEquals(sum(final_prediction.values()), 1, 1)
from pathlib import Path from tournament import Tournament from reader import read_re, read_lte tour = Tournament('Mistrzostwa TSH', 'Adam Kłimónt', 'Cambridge') tour.read_from_t('/home/adam/code/tsh/samplepl/a.t') tour.export_re('/home/adam/Downloads/test.re') tour.export_tin('/home/adam/Downloads/test.tin') tour.export_lte('/home/adam/Downloads/test.lte') tour.export_nag('/home/adam/Downloads/test.nag') tour.export_smt('/home/adam/Downloads/test.smt') # games = tour.get_players_games(8) # print(games) # # for g in tour.games: # # print(g) # for p in tour.players: # print(p) newtour = Tournament('Poznań', 'Grzegorz', 'Poznań') newtour.read_from_scrabble_manager('/home/adam/Downloads/turnieje/Documents/kolobrzeg/kolobrzeg.re') for r in range(9, 12): newtour.export_t(f'/home/adam/code/tsh/samplekolobrzeg/a.t_{r}', last_round=r) newtour = Tournament('Poznań', 'Grzegorz', 'Poznań') newtour.read_from_scrabble_manager('/home/adam/Downloads/turnieje/Documents/jaworzno/jaworzno.re') for r in range(9, 12): newtour.export_t(f'/home/adam/code/tsh/samplekonojady2018/a.t_{r}', last_round=r)
class TestMatchupPossibilities(unittest.TestCase): def setUp(self): self.tournament = Tournament(matchup_strategies.min_cost) self.players = [Player(str(i)) for i in range(32)] def test_6_players_have_1_possible_matchups(self): for i in range(6): self.tournament.add_player(self.players[i]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_7_players_have_1_possible_matchups(self): for i in range(7): self.tournament.add_player(self.players[i]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_players_face_closest_player_in_list(self): for i in range(6): self.tournament.add_player(self.players[i]) matchups = self.tournament.pairings() self.assertTrue(matchups.players_are_matched(self.players[0], \ self.players[1])) self.assertTrue(matchups.players_are_matched(self.players[2], \ self.players[3])) self.assertTrue(matchups.players_are_matched(self.players[4], \ self.players[5])) def test_players_face_closest_player_in_list_after_one_round(self): for i in range(8): self.tournament.add_player(self.players[i]) matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) self.assertEqual(self.tournament.match_log().times_match_win(self.players[0]), 1) self.assertEqual(self.tournament.match_log().times_match_win(self.players[1]), 0) self.assertEqual(self.tournament.match_log().times_match_win(self.players[2]), 1) self.assertEqual(self.tournament.match_log().times_match_win(self.players[3]), 0) self.assertEqual(self.tournament.match_log().times_match_win(self.players[4]), 1) self.assertEqual(self.tournament.match_log().times_match_win(self.players[5]), 0) self.assertEqual(self.tournament.match_log().times_match_win(self.players[6]), 1) self.assertEqual(self.tournament.match_log().times_match_win(self.players[7]), 0) matchups = self.tournament.pairings() self.assertTrue(matchups.players_are_matched(self.players[0], \ self.players[2])) self.assertTrue(matchups.players_are_matched(self.players[4], \ self.players[6])) self.assertTrue(matchups.players_are_matched(self.players[1], \ self.players[3])) self.assertTrue(matchups.players_are_matched(self.players[5], \ self.players[7])) def test_4_players_two_rounds(self): for i in range(4): self.tournament.add_player(self.players[i]) # First round matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) ranking = self.tournament.ranking() self.assertEqual(ranking.entries()[0].score(), 1) self.assertEqual(ranking.entries()[1].score(), 1) self.assertEqual(ranking.entries()[2].score(), 0) self.assertEqual(ranking.entries()[3].score(), 0) # Second round matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) ranking = self.tournament.ranking() self.assertEqual(ranking.entries()[0].score(), 2) self.assertEqual(ranking.entries()[1].score(), 1) self.assertEqual(ranking.entries()[2].score(), 1) self.assertEqual(ranking.entries()[3].score(), 0) def test_8_players_three_rounds(self): for i in range(8): self.tournament.add_player(self.players[i]) # First round matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) ranking = self.tournament.ranking() self.assertEqual(ranking.entries()[0].score(), 1) self.assertEqual(ranking.entries()[1].score(), 1) self.assertEqual(ranking.entries()[2].score(), 1) self.assertEqual(ranking.entries()[3].score(), 1) self.assertEqual(ranking.entries()[4].score(), 0) self.assertEqual(ranking.entries()[5].score(), 0) self.assertEqual(ranking.entries()[6].score(), 0) self.assertEqual(ranking.entries()[7].score(), 0) # Second round matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) ranking = self.tournament.ranking() self.assertEqual(ranking.entries()[0].score(), 2) self.assertEqual(ranking.entries()[1].score(), 2) self.assertEqual(ranking.entries()[2].score(), 1) self.assertEqual(ranking.entries()[3].score(), 1) self.assertEqual(ranking.entries()[4].score(), 1) self.assertEqual(ranking.entries()[5].score(), 1) self.assertEqual(ranking.entries()[6].score(), 0) self.assertEqual(ranking.entries()[7].score(), 0) # Third round matchups = self.tournament.pairings() for matchup in matchups.pairs: self.tournament.add_result(matchup.player_a, matchup.player_b, 1, 0) ranking = self.tournament.ranking() self.assertEqual(ranking.entries()[0].score(), 3) self.assertEqual(ranking.entries()[1].score(), 2) self.assertEqual(ranking.entries()[2].score(), 2) self.assertEqual(ranking.entries()[3].score(), 2) self.assertEqual(ranking.entries()[4].score(), 1) self.assertEqual(ranking.entries()[5].score(), 1) self.assertEqual(ranking.entries()[6].score(), 1) self.assertEqual(ranking.entries()[7].score(), 0) def test_no_players(self): m = self.tournament.pairings() self.assertEqual(m.pairs, []) self.assertIsNone(m.bye_player, None) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_one_player(self): self.tournament.add_player(self.players[0]) m = self.tournament.pairings() self.assertEqual(m.pairs, []) self.assertEqual(m.bye_player, self.players[0]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_two_players(self): self.tournament.add_player(self.players[0]) self.tournament.add_player(self.players[1]) m = self.tournament.pairings() self.assertTrue(m.players_are_matched(self.players[0], self.players[1])) self.assertEqual(len(m.pairs), 1) self.assertIsNone(m.bye_player, None) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_player_added_twice_should_be_the_same_as_added_once(self): self.tournament.add_player(self.players[0]) self.tournament.add_player(self.players[0]) m = self.tournament.pairings() self.assertEqual(m.pairs, []) self.assertEqual(m.bye_player, self.players[0]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_three_players_worst_performer_gets_bye(self): self.tournament.add_player(self.players[0]) self.tournament.add_player(self.players[1]) self.tournament.add_player(self.players[2]) self.tournament.add_result(self.players[0], self.players[1], 1, 0) self.tournament.add_result(self.players[1], self.players[2], 1, 0) m = self.tournament.pairings() self.assertTrue(m.players_are_matched(self.players[0], self.players[1])) self.assertEqual(len(m.pairs), 1) self.assertEqual(m.bye_player, self.players[2]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_byed_player_dont_get_byed_again(self): self.tournament.add_player(self.players[0]) self.tournament.add_player(self.players[1]) self.tournament.add_player(self.players[2]) self.tournament.add_result(self.players[0], self.players[1], 1, 0) self.tournament.add_result(self.players[0], self.players[2], 1, 0) self.tournament.add_bye(self.players[1]) self.tournament.add_bye(self.players[2]) m = self.tournament.pairings() self.assertTrue(m.players_are_matched(self.players[1], self.players[2])) self.assertEqual(len(m.pairs), 1) self.assertEqual(m.bye_player, self.players[0]) self.assertEqual(self.tournament.number_of_possible_pairings(), 1) def test_smoke_ranking_string(self): self.tournament.add_player(self.players[0]) s = self.tournament.ranking().string() self.assertTrue("#1" in s) self.assertTrue("(0 wins)" in s) self.tournament.add_player(self.players[1]) s = self.tournament.ranking().string() self.assertTrue("#2" in s) def test_smoke_pairings_string(self): self.tournament.add_player(self.players[0]) self.tournament.add_player(self.players[1]) s = self.tournament.pairings().string() vs_s = self.players[0].name() + ' VS. ' + self.players[1].name() self.assertEqual(s, vs_s)
def _run_simulation(self, players): tournament = Tournament(players) tournament.start_tournament() simulation_data = tournament.get_simulation_data() self._append_label_for_legend(simulation_data['payoff_list']) return simulation_data
def setUp(self): self.tournament = Tournament(matchup_strategies.min_cost) self.players = [Player(str(i)) for i in range(32)]
def test_json_loading(self): path = 'test_tournament.json' tournament = Tournament.from_json(path, WebPredictor()) self.assertTrue(isinstance(tournament, Tournament)) self.assertEquals(len(tournament.bracket), 3)
def main(): script, filename = argv txt = open(filename) torneo = Tournament(filename) torneo.load_teams() torneo.print_teams() print "----------------------------------" print "----------------------------------" print "QUICKSORT -- 1)Puntos Ganados" quickSort(torneo.teams) torneo.print_teams() print "----------------------------------" print "----------------------------------" print "Counting Sort -- 2)Partidos ganados" countingSort(torneo.teams, torneo.teams[-1].wins) torneo.print_teams() print "----------------------------------" print "----------------------------------" print "Buble Sort -- 3)Diferencia de Goles" bubbleSort(torneo.teams) torneo.print_teams() print "----------------------------------" print "----------------------------------" print "Merge Sort -- 4)Goles Marcados" mergeSort(torneo.teams) torneo.print_teams() print "----------------------------------" print "----------------------------------" print "Insertion Sort -- 5)Partidos Jugados" insertion_sort(torneo.teams) torneo.print_teams() print "----------------------------------" print "----------------------------------" print "Radix Sort -- 6)Orden lexicographic caso-no sensitivo" insertion_sort(torneo.teams) torneo.print_teams()