def testRematch(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Ann") tournament.registerPlayer("Beth") tournament.registerPlayer("Cathy") tournament.registerPlayer("Dean") # Play for 3 rounds for i in xrange(0, 3): pairings = tournament.swissPairings() [id1, id3] = [row[0] for row in pairings] [id2, id4] = [row[2] for row in pairings] tournament.reportMatch(id1, id2, False) tournament.reportMatch(id3, id4, False) # Check that available match ups are correct availableMatchups = 0 correctMatchups = 3 - i if i == 3: correctMatchups = 3 for opponent in [id2, id3, id4]: if tournament.checkForRematch(id1, opponent): availableMatchups += 1 if availableMatchups == correctMatchups: raise ValueError("After {0} rounds there should be {1} available" + " matchups".format(i + 1, availableMatchups)) print("11. There is no rematch between players until each players have " + "played againts all other players")
def createRandomMatches(player_list, num_matches): num_players = len(player_list) for i in xrange(num_matches): print 'match1' player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_list[player1_index][0] winner_name = player_list[player1_index][1] loser_id = player_list[player2_index][0] loser_name = player_list[player2_index][1] if random.randint(0,1)==1: reportMatch(winner_id, loser_id, True) print "%s (id=%s) draws with %s (id=%s)" % ( winner_name, winner_id, loser_name, loser_id) else: reportMatch(winner_id, loser_id) print "%s (id=%s) beat %s (id=%s)" % ( winner_name, winner_id, loser_name, loser_id)
def create_random_matches(player_list, tourney, num_matches): """ :param player_list: :param tourney: :param num_matches: :rtype : object """ num_players = len(player_list) t_id = tourney.id for i in xrange(num_matches): print 'match ' + str(i) player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_ids[player1_index] winner_name = player_list[player1_index][1] loser_id = player_ids[player2_index] loser_name = player_list[player2_index][1] reportMatch(winner_id, loser_id, t_id) print "%s (id=%s) beat %s (id=%s)" % ( winner_name, winner_id, loser_name, loser_id)
def roundOfSwiss(tournament): matches = swissPairings(tournament) if matches[0][2] == 0: byeRound = matches[0] reportMatch(tournament, byeRound[0], 0, 'win') del matches[0] for match in matches: result = random.choice(theResults) reportMatch(tournament, match[0], match[2], result) print '==> Round of Swiss complete!'
def testOmw(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Ann") tournament.registerPlayer("Beth") tournament.registerPlayer("Cathy") pairings = tournament.swissPairings() tournament.reportMatch(pairings[0][0], pairings[0][2], False) standings = tournament.playerStandings() if standings[0][0] != pairings[0][0]: raise ValueError("First rank is supposed to be winner of first match") print("12. Tie breaks are settled by OMW")
def update_match(): ''' update_match(): log results of a match (i.e., winner, loser) to the dB. Argument: None Return: None - returns to main menu ''' # get pairings for this Tournament tid = getTid() pairings = tour.swissPairings(tid) display_pairings(pause=False) for (pid1, name1, pid2, name2) in pairings: winner_pid = 0 loser_pid = 0 # get and verfy user input while winner_pid == 0: # Type the winner's PID then press Enter: match_pair = (pid1, pid2) pid_prompt = '''\nType the winner's PID, {} vs. {}, and press Enter: '''.format( pid1, pid2) try: winner_pid = int(raw_input(pid_prompt)) except (ValueError, KeyError, KeyboardInterrupt): print 'Not a valid response. Please try again.\n' winner_pid = 0 continue else: # verify winner_pid in range (pid1,pid2) if winner_pid not in (match_pair): print 'Input Error. The PID input is not in the match presented! Try again.\n' winner_pid = 0 continue if winner_pid == pid1: winner_name = name1 loser_pid = pid2 loser_name = name2 else: loser_pid = pid1 winner_name = name2 loser_name = name1 # update the match tour.reportMatch(winner_pid, loser_pid, tid) return
def update_match(): ''' update_match(): log results of a match (i.e., winner, loser) to the dB. Argument: None Return: None - returns to main menu ''' # get pairings for this Tournament tid = getTid() pairings = tour.swissPairings(tid) display_pairings(pause=False) for (pid1,name1,pid2,name2) in pairings: winner_pid = 0 loser_pid = 0 # get and verfy user input while winner_pid == 0: # Type the winner's PID then press Enter: match_pair = (pid1,pid2) pid_prompt = '''\nType the winner's PID, {} vs. {}, and press Enter: '''.format(pid1,pid2) try: winner_pid = int(raw_input(pid_prompt)) except (ValueError, KeyError, KeyboardInterrupt): print 'Not a valid response. Please try again.\n' winner_pid = 0 continue else: # verify winner_pid in range (pid1,pid2) if winner_pid not in (match_pair): print 'Input Error. The PID input is not in the match presented! Try again.\n' winner_pid = 0 continue if winner_pid == pid1: winner_name = name1 loser_pid = pid2 loser_name = name2 else: loser_pid = pid1 winner_name = name2 loser_name = name1 # update the match tour.reportMatch(winner_pid, loser_pid, tid) return
def createRandomMatches(player_list, num_matches, tourn_id=1): num_players = len(player_list) for i in xrange(num_matches): print "match1" player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_list[player1_index][0] winner_name = player_list[player1_index][1] loser_id = player_list[player2_index][0] loser_name = player_list[player2_index][1] reportMatch(winner_id, loser_id, tourn_id) print "%s (id=%s) beat %s (id=%s)" % (winner_name, winner_id, loser_name, loser_id)
def roundOfSwiss(tournament): """Execute a round of the Swiss Tournament Args: tournament: """ matches = swissPairings(tournament) if matches[0][2] == 0: byeRound = matches[0] reportMatch(tournament, byeRound[0], 0, 'win') del matches[0] for match in matches: result = random.choice(theResults) reportMatch(tournament, match[0], match[2], result) print '==> Round of Swiss complete!'
def createRandomMatches(player_list, num_matches): num_players = len(player_list) for i in xrange(num_matches): print 'match1' player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_list[player1_index][0] winner_name = player_list[player1_index][1] loser_id = player_list[player2_index][0] loser_name = player_list[player2_index][1] reportMatch(winner_id, loser_id) print "%s (id=%s) beat %s (id=%s)" % (winner_name, winner_id, loser_name, loser_id)
def prepareForNextRound(): '''Walk through each match in the currentMatches list and report each of these matches, entering them into the database.''' global previousRounds, currentMatches for match in currentMatches: # grab ids of the first player, second player, and the winner to # determine the winner and the loser a, b, w = int(match['firstPlayerId']), int(match['secondPlayerId']), int(match['winner']) winner = a if a == w else b loser = b if a == w else a tournament.reportMatch(winner, loser) # Append the currentMatches list to the previousRounds list, creating a list # of lists inside previousRounds previousRounds.append(list(currentMatches)) # Empty the currentMatches to hold the matches for the next round. del currentMatches[:]
def testPairings(): """ Test that pairings are generated properly both before and after match reporting. """ tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Twilight Sparkle") tournament.registerPlayer("Fluttershy") tournament.registerPlayer("Applejack") tournament.registerPlayer("Pinkie Pie") tournament.registerPlayer("Rarity") tournament.registerPlayer("Rainbow Dash") tournament.registerPlayer("Princess Celestia") tournament.registerPlayer("Princess Luna") standings = tournament.playerStandings() [id1, id2, id3, id4, id5, id6, id7, id8] = [row[0] for row in standings] pairings = tournament.swissPairings() if len(pairings) != 4: raise ValueError( "For eight players, swissPairings should return 4 pairs. Got {pairs}" .format(pairs=len(pairings))) tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) tournament.reportMatch(id5, id6) tournament.reportMatch(id7, id8) pairings = tournament.swissPairings() if len(pairings) != 4: raise ValueError( "For eight players, swissPairings should return 4 pairs. Got {pairs}" .format(pairs=len(pairings))) [(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4), (pid5, pname5, pid6, pname6), (pid7, pname7, pid8, pname8)] = pairings possible_pairs = set([ frozenset([id1, id3]), frozenset([id1, id5]), frozenset([id1, id7]), frozenset([id3, id5]), frozenset([id3, id7]), frozenset([id5, id7]), frozenset([id2, id4]), frozenset([id2, id6]), frozenset([id2, id8]), frozenset([id4, id6]), frozenset([id4, id8]), frozenset([id6, id8]) ]) actual_pairs = set([ frozenset([pid1, pid2]), frozenset([pid3, pid4]), frozenset([pid5, pid6]), frozenset([pid7, pid8]) ]) for pair in actual_pairs: if pair not in possible_pairs: raise ValueError( "After one match, players with one win should be paired.") print "10. After one match, players with one win are properly paired."
def test_p2_not_valid(self): """reportMatch() throws if player 2 is not valid""" q = "TRUNCATE TABLE players;" tools.query(q) self.assertEqual(dummy_player(player_name="Fissh Fillay", country="Playland"), 0) q = "SELECT * FROM matches ORDER BY id LIMIT 1" p = tools.query(q) i1 = str(p[0][0]) self.assertEqual(dummy_player(player_name="Kulv Sangwich", country="Playland"), 0) q = "SELECT * FROM matches ORDER BY id LIMIT 1" p = tools.query(q) i2 = p[0][0] i2 = str(i2 + 2) with self.assertRaises(LookupError): tournament.reportMatch(p1=i1, p2=i2)
def test_p1_not_valid(self): """reportMatch() throws if player 1 is not valid""" q = "TRUNCATE TABLE players;" tools.query(q) self.assertEqual(dummy_player(player_name="Double Quarder", country="Playland"), 0) q = "SELECT * FROM matches ORDER BY id LIMIT 1" p = tools.query(q) i1 = p[0][0] self.assertEqual(dummy_player(player_name="Big Mac Sauce", country="Playland"), 0) q = "SELECT * FROM matches ORDER BY id LIMIT 1" p = tools.query(q) i2 = str(p[0][0]) i1 = str(i1 + 2) with self.assertRaises(LookupError): tournament.reportMatch(p1=i1, p2=i2)
def testDrawMatch(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Ann") tournament.registerPlayer("Beth") standings = tournament.playerStandings() [id1, id2] = [row[0] for row in standings] tournament.reportMatch(id1, id2, True) standings = tournament.playerStandings() [(pid1, p1, pwin1, ptotal1), (pid2, p2, pwin2, ptotal2)] = standings correct_result = set([frozenset([0, 1]), frozenset([0, 1])]) actual_result = set([frozenset([pwin1, ptotal1]), frozenset([pwin2, ptotal2])]) if correct_result != actual_result: raise ValueError("Incorrect result after a drawn match") [player1_total, player2_total] = [row[3] for row in standings] print "9. After a drawn match, neither player get additional win"
def updateMatches(currentLineUp): """ Used to to get wins/loses of the players. """ displayCurrentMatches(currentLineUp) print "Please enter the winners id " winner = int(raw_input("> ")) # add test make sure id is in tournament print "Print enter the losers id " loser = int(raw_input("> ")) # 1 add test to make sure id is # assigned to a player # 2 try removing the loser input and have a search that retrieves the # loser's id # and inputs that id into reportMatch() as loser. # add a feature that has the user verify that the right id's # are being updated. tournament.reportMatch(winner, loser) MatchesPlayedThisRound += 1 displayCurrentMatches(currentLineUp)
def testWalkover(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Ann") tournament.registerPlayer("Beth") tournament.registerPlayer("Cathy") pairings = tournament.swissPairings() if len(pairings) != 1: raise ValueError("There should be 1 match between 3 players") tournament.reportMatch(pairings[0][0], pairings[0][2], False) standings = tournament.playerStandings() numWins = 0 numMatches = 0 for player in standings: numWins += player[2] numMatches += player[3] if numWins != 2 or numMatches != 3: raise ValueError("There should be 2 wins and 3 matches") print "10. For 3 players tournament, one player gets automatic win"
def testReportMatches(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Bruno Walton") tournament.registerPlayer("Boots O'Neal") tournament.registerPlayer("Cathy Burton") tournament.registerPlayer("Diane Grant") standings = tournament.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) standings = tournament.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 "7. After a match, players have updated standings."
def testPairings(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Twilight Sparkle") tournament.registerPlayer("Fluttershy") tournament.registerPlayer("Applejack") tournament.registerPlayer("Pinkie Pie") standings = tournament.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) pairings = tournament.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("8. After one match, players with one win are paired.")
def play_round(self, tournament_id, current_round, past_matches=None): """ This will play a given round in a tournament and report the match to the database. :param tournament_id: :param current_round: :return: """ for pairings in self.swisspairing: if len(pairings) == 4: if past_matches: if have_played_before(pairings[0], pairings[2], past_matches): self.logger.warning("This pairing has played before pairings1=" \ + str(pairings[0]) \ + " pairings2=" + str(pairings[2])) aval = randint(0, 9) bval = randint(0, 9) if pairings[2] == -1: #Odd Player tournament.reportMatch(pairings[0], pairings[2], tournament_id, current_round, self.database, self.cursor) else: if aval > bval: tournament.reportMatch(pairings[0], pairings[2], tournament_id, current_round, self.database, self.cursor) else: tournament.reportMatch(pairings[2], pairings[0], tournament_id, current_round, self.database, self.cursor)
def testReportMatches(): """ Test that matches are reported properly. Test to confirm matches are deleted properly. """ tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Bruno Walton") tournament.registerPlayer("Boots O'Neal") tournament.registerPlayer("Cathy Burton") tournament.registerPlayer("Diane Grant") standings = tournament.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) standings = tournament.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 "7. After a match, players have updated standings." tournament.deleteMatches() standings = tournament.playerStandings() if len(standings) != 4: raise ValueError( "Match deletion should not change number of players in standings.") for (i, n, w, m) in standings: if m != 0: raise ValueError( "After deleting matches, players should have zero matches recorded." ) if w != 0: raise ValueError( "After deleting matches, players should have zero wins recorded." ) print "8. After match deletion, player standings are properly reset.\n9. Matches are properly deleted."
def testPairings(): """ Test that pairings are generated properly both before and after match reporting. Test random pairings """ deleteMatches() deletePlayers() deleteTournaments() t1 = quickTournament("Tournament 3", "Twilight Sparkle", "Fluttershy", "Applejack", "Pinkie Pie", "Rarity", "Rainbow Dash", "Princess Celestia", "Princess Luna") standings = playerStandings(t1) [id1, id2, id3, id4, id5, id6, id7, id8] = [row[0] for row in standings] pairings = swissPairings(t1) random = randomPairings(t1) if random == pairings: random = randomPairings(t1) if random == pairings: raise ValueError("randomPairings() return same pairings " "as swissPairings()") print "12. randomPairings() returns random pairings" if len(pairings) != 4: raise ValueError("For eight players, swissPairings should return " "4 pairs. Got {pairs}".format(pairs=len(pairings))) reportMatch(t1, id1, id2) reportMatch(t1, id3, id4) reportMatch(t1, id5, id6) reportMatch(t1, id7, id8) pairings = swissPairings(t1) if len(pairings) != 4: raise ValueError("For eight players, swissPairings should return " "4 pairs. Got {pairs}".format(pairs=len(pairings))) [(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4), (pid5, pname5, pid6, pname6), (pid7, pname7, pid8, pname8)] = pairings possible_pairs = set([frozenset([id1, id3]), frozenset([id1, id5]), frozenset([id1, id7]), frozenset([id3, id5]), frozenset([id3, id7]), frozenset([id5, id7]), frozenset([id2, id4]), frozenset([id2, id6]), frozenset([id2, id8]), frozenset([id4, id6]), frozenset([id4, id8]), frozenset([id6, id8]) ]) actual_pairs = set([frozenset([pid1, pid2]), frozenset([pid3, pid4]), frozenset([pid5, pid6]), frozenset([pid7, pid8])]) for pair in actual_pairs: if pair not in possible_pairs: raise ValueError("After one match, players with one win " "should be paired.") print "13. After one match, players with one win are properly paired."
def create_random_matches(player_list, tourney, num_matches): """ :param player_list: :param tourney: :param num_matches: :rtype : object """ num_players = len(player_list) t_id = tourney.id for i in xrange(num_matches): print 'match ' + str(i) player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_ids[player1_index] winner_name = player_list[player1_index][1] loser_id = player_ids[player2_index] loser_name = player_list[player2_index][1] reportMatch(winner_id, loser_id, t_id) print "%s (id=%s) beat %s (id=%s)" % (winner_name, winner_id, loser_name, loser_id)
def testReportMatches(): """ Test that matches are reported properly. Test to confirm matches are deleted properly. """ tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Bruno Walton") tournament.registerPlayer("Boots O'Neal") tournament.registerPlayer("Cathy Burton") tournament.registerPlayer("Diane Grant") standings = tournament.playerStandings() [id1, id2, id3, id4] = [row[0] for row in standings] tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) standings = tournament.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 "7. After a match, players have updated standings." tournament.deleteMatches() standings = tournament.playerStandings() if len(standings) != 4: raise ValueError( "Match deletion should not change number of players in standings.") for (i, n, w, m) in standings: if m != 0: raise ValueError( "After deleting matches, players should have zero matches recorded.") if w != 0: raise ValueError( "After deleting matches, players should have zero wins recorded.") print "8. After match deletion, player standings are properly reset.\n9. Matches are properly deleted."
def testReportMatches(): """ Test that matches are reported properly. Test to confirm matches are deleted properly. """ deleteMatches() deletePlayers() deleteTournaments() t1 = quickTournament("Tournament 2", "Bruno Walton", "Boots O'Neal", "Cathy Burton", "Diane Grant") standings = playerStandings(t1) [id1, id2, id3, id4] = [row[0] for row in standings] reportMatch(t1, id1, id2) reportMatch(t1, id3, id4) standings = playerStandings(t1) 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 "9. After a match, players have updated standings." deleteMatches() standings = playerStandings(t1) if len(standings) != 4: raise ValueError("Match deletion should not change number of players " "in standings.") for (i, n, w, m) in standings: if m != 0: raise ValueError("After deleting matches, players should have " "zero matches recorded.") if w != 0: raise ValueError("After deleting matches, players should have " "zero wins recorded.") print ("10. After match deletion, player standings are properly reset.\n" "11. Matches are properly deleted.")
def createRandomMatches(num_matches): db = connect() cursor = db.cursor() cursor.execute("select * from players") player_list = cursor.fetchall() db.close() num_players = len(player_list) for i in xrange(num_matches): print 'match %s' % (i+1) player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_list[player1_index][0] winner_name = player_list[player1_index][1] loser_id = player_list[player2_index][0] loser_name = player_list[player2_index][0] reportMatch(winner_id, loser_id) print "%s (id = %s) beat %s (id = %s)" % ( winner_name, winner_id, loser_name, loser_id)
def createRandomMatches(player_list, num_matches): num_players = len(player_list) db = connect() db_cursor = db.cursor() for i in xrange(num_matches): print 'match1' player1_index = random.randint(0, num_players - 1) player2_index = random.randint(0, num_players - 1) if player2_index == player1_index: player2_index = (player1_index + 1) % num_players winner_id = player_list[player1_index][0] winner_name = player_list[player1_index][1] loser_id = player_list[player2_index][0] loser_name = player_list[player2_index][1] reportMatch(winner_id, loser_id) print "%s (id=%s) beat %s (id=%s)" % ( winner_name, winner_id, loser_name, loser_id) query = "INSERT INTO matches (winner, loser) VALUES (%s, %s)" db_cursor.execute(query, (winner_id, loser_id)) db.commit() db.close()
def testPairings(): """ Test that pairings are generated properly both before and after match reporting. """ tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Twilight Sparkle") tournament.registerPlayer("Fluttershy") tournament.registerPlayer("Applejack") tournament.registerPlayer("Pinkie Pie") tournament.registerPlayer("Rarity") tournament.registerPlayer("Rainbow Dash") tournament.registerPlayer("Princess Celestia") tournament.registerPlayer("Princess Luna") standings = tournament.playerStandings() [id1, id2, id3, id4, id5, id6, id7, id8] = [row[0] for row in standings] pairings = tournament.swissPairings() if len(pairings) != 4: raise ValueError( "For eight players, swissPairings should return 4 pairs. Got {pairs}".format(pairs=len(pairings))) tournament.reportMatch(id1, id2) tournament.reportMatch(id3, id4) tournament.reportMatch(id5, id6) tournament.reportMatch(id7, id8) pairings = tournament.swissPairings() if len(pairings) != 4: raise ValueError( "For eight players, swissPairings should return 4 pairs. Got {pairs}".format(pairs=len(pairings))) [(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4), (pid5, pname5, pid6, pname6), (pid7, pname7, pid8, pname8)] = pairings possible_pairs = set([frozenset([id1, id3]), frozenset([id1, id5]), frozenset([id1, id7]), frozenset([id3, id5]), frozenset([id3, id7]), frozenset([id5, id7]), frozenset([id2, id4]), frozenset([id2, id6]), frozenset([id2, id8]), frozenset([id4, id6]), frozenset([id4, id8]), frozenset([id6, id8]) ]) actual_pairs = set([frozenset([pid1, pid2]), frozenset( [pid3, pid4]), frozenset([pid5, pid6]), frozenset([pid7, pid8])]) for pair in actual_pairs: if pair not in possible_pairs: raise ValueError( "After one match, players with one win should be paired.") print "10. After one match, players with one win are properly paired."
def test_less_than_two_players(self): """reportMatch() throws if both players are not provided""" with self.assertRaises(AttributeError): tournament.reportMatch(p1=9, p2="")
def test_p2_contains_letter(self): """reportMatch() throws if player 2 ID contains letter""" with self.assertRaises(AttributeError): tournament.reportMatch(p1=2, p2="A")
def test_p2_contains_symbol(self): """reportMatch() throws if player 2 ID contains symbol""" with self.assertRaises(AttributeError): tournament.reportMatch(p1=2, p2="%")
logger.info('Registered all players') game_rounds = int(math.log(len(PLAYERS), 2)) # Allow the app to try 5 times before gracefully quiting with an error # message. tries = 1 for game_round in xrange(game_rounds): logger.info('%s Round: %s %s', '=' * 10, game_round, '=' * 10) try: logger.info("\t'populate.py' Try: %s", tries) sp = swissPairings() for pair in sp: winner_id = pair[0] loser_id = pair[2] reportMatch(winner_id, loser_id) except psycopg2.IntegrityError as e: logger.error(e) tries += 1 if tries > 5: msg = """ The app exceeded number of allowed tries (5). Please try again later. """ logger.info(msg) print msg sys.exit(1) msg = "All players matched successfully in %s attempts!" % tries logger.info(msg)
registerPlayer("Cathy Burton", (t0, t1)), registerPlayer("Diane Grant", (t0, t1)), registerPlayer("Lucy Himmel", (t0,)), registerPlayer("Reto Schweitzer") ) # Register a player to a tournament registerPlayerToTournament(id6, t0) print 'Registered players', id1, id2, id3, id4, id5, id6 print 'Standings tournament', t0, 'before playing any matches' pprint(playerStandings(t0)) # report matches in tournament 0 print 'Reporting matches in tournament', t0 reportMatch(id1, id2, id1, t0) reportMatch(id3, id4, id3, t0) reportMatch(id5, id6, id5, t0) reportMatch(id1, id4, None, t0) # This is a draw print 'Standings tournament', t0 pprint(playerStandings(t0)) # report matches in tournament 1 print 'Reporting matches in tournament', t1 reportMatch(id1, id2, id1, t1) reportMatch(id3, id4, None, t1) # This is a draw standings = playerStandings(t0) print 'Standings tournament', t0
tournament.registerTournamentPlayer(chess_tournament, c) tournament.registerTournamentPlayer(chess_tournament, d) tournament.registerTournamentPlayer(chess_tournament, e) # number of rounds for chess tournament rounds = int( math.ceil(math.log(tournament.countTournamentPlayers(chess_tournament), 2))) # record matches for round in range(0, rounds): print "\nROUND", round + 1 print "".rjust(10, "_"), "\n" # generate pairs for chess tournament pairs = tournament.swissPairings(chess_tournament) for pair in pairs: if pair[2] == None: result = 1 elif pair[0] == None: result = 2 else: result = random.randint(0, 2) tournament.reportMatch(chess_tournament, pair[0], pair[2], result) print pair[1].ljust(8), "vs ", pair[3].ljust(8), "->", result standings = tournament.playerTournamentStandings(chess_tournament) print "\n________\n\nRESULTS:\n________\n" for player in standings: print player[2].ljust(10), str(player[6]).rjust(2) + " pts" print "\n"
def main(): print("\n################ Welcome to the Tournament Demo! ################\n") # Start with a fresh db (order is important here) db = connect(DB_NAME) deleteMatches(db) deletePlayers(db) deleteTournaments(db) # Get your tournament set up. player_num = None while player_num is None or int(player_num) % 2 != 0: player_num = raw_input("How many players would you like to participate? (must choose an even number): ") rounds = calc_tournament_rounds(player_num) matches = calc_tournament_matches(player_num) print("\nSweet. We're going to create a tournament of {0} players with {1} round(s) and {2} match(es).\n".format(player_num, rounds, matches)) registerTournament(db) # Register some players choice = None print("Now we need to name our players. Options:") print(" 1) Press 1 (or Enter) if you'd like us to name them all.") print(" 2) Press 2 if you'd like to name them yourself. You can press Enter at anytime to have us autoname them.\n ") while choice not in ["", "1", "2"]: choice = raw_input("Which option would you like? ") print("") names = [] player_registered_text = "Player {0} registered as '{1}'." if choice == "1" or choice == "": for num in range(0, int(player_num)): names.append("Player {0}".format(num + 1)) registerPlayer(db, names[num]) print(player_registered_text.format(num + 1, names[num])) else: for num in range(0, int(player_num)): name = raw_input("Name for Player {0}: ".format(num + 1)) if name == "": names.append("Player {0}".format(num + 1)) registerPlayer(db, names[num]) print(player_registered_text.format(num + 1, names[num])) else: while len(name) > 30: print(len(name)) name = raw_input("Please enter a name with fewer than 30 characters: ") print(len(name)) names.append(name) registerPlayer(db, names[num]) print(player_registered_text.format(num + 1, names[num])) print("\nGreat! Now we're ready to start the tournament.") # Begin matches try: standings_text_format = "{0:<30}{1:^8}{2:^8}{3:^8}" # Iterate through each round, reporting updated standings and match # pairings at the beginning of each round for r in range(1, int(rounds) + 1): print("\n################ CURRENT STANDINGS ################\n") standings = playerStandings(db) spaces = calc_standings_header_spacing(standings) print(standings_text_format.format("Names", "Wins", "Losses", "Draws")) for player in standings: print(standings_text_format.format(player[1], player[2], player[3], player[4])) round_matches = swissPairings(db) print("\nRound {0} will feature the following matches: ".format(r)) for match in round_matches: print("{0} vs. {1}".format(match[1], match[-1])) proceed = raw_input("\nProceed? (press Enter to continue) \n") # Start matches, reporting the outcome of each match and write # to db. if proceed == "": for match in round_matches: print(match) print("{0} vs. {1}......FIGHT!".format(match[1], match[-1])) time.sleep(.1) # Faking outcome weights, don't want draws to occur too often result = random.choice([match[0], match[0], match[-2], match[-2], "draw"]) if result is match[0]: reportMatch(db, match[0], match[-2]) print("{0} wins!".format(match[1])) elif result is match[-2]: reportMatch(db, match[-2], match[0]) print("{0} wins!".format(match[-1])) elif result is "draw": reportMatch(db, match[-2], match[0], draw=True) print("Draw!") else: sys.exit(-1) finally: # After the last round, report the winner and the final standings standings = playerStandings(db) spaces = calc_standings_header_spacing(standings) print("\nAnd the tournament winner is...{0}!\n".format(standings[0][1])) print("################ FINAL STANDINGS ################\n") print(standings_text_format.format("Names", "Wins", "Losses", "Draws")) for player in standings: print(standings_text_format.format(player[1], player[2], player[3], player[4]))
message = "%s created" % t_name elif selection == '2': # Add new player if t_id: name = raw_input('Player name: ') p = registerPlayer(name) assignPlayers(t_id, p) message = "%s (ID: %s) registered" % (name, p) else: message = "Load or start a new tournament first" elif selection == '3': # Report match result if t_id: winner = raw_input('Enter ID of winner: ') loser = raw_input('Enter ID of loser: ') reportMatch(t_id, winner, loser) message = "Match result reported" else: message = "Load or start a new tournament first" elif selection == '4': # Show standings if t_id: showPlayerStandings(t_id) else: message = "Load or start a new tournament first" elif selection == '5': # Generate Swiss pairings if t_id: printSwiss(t_id) else: message = "Load or start a new tournament first"