def testStandingsBeforeMatches(): """ Test to ensure players are properly represented in standings prior to any matches being reported. """ deleteMatches() deletePlayers() deleteTournaments() t1 = newTournament("Test tournament") p1 = registerPlayer("Melpomene Murray") p2 = registerPlayer("Randy Schwartz") registerPlayer("Lucky Luke") registerPlayer("Charlie Brown") assignPlayers(t1, p1, p2) standings = playerStandings(t1) 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 assigned 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 ("8. Newly registered players appear in the " "standings with no matches.")
def showPlayerStandings(t): """Prints a table of player standings. Gives error message if no players""" global message standings = playerStandings(t) if standings: os.system('cls' if os.name == 'nt' else 'clear') t = Terminal() print """\n\n\n TOURNAMENT STANDINGS ========================================================================= | # | id | name | wins | matches | -------------------------------------------------------------------------""" place = 0 for row in standings: place += 1 id = len(str(row[0])) name = len(str(row[1])) wins = len(str(row[2])) match = len(str(row[3])) print " | %s%s | %s%s | %s%s | %s%s | %s%s |" % ( " " * (3 - len(str(place))), place, " " * (4 - id), row[0], " " * (39 - name), row[1], " " * (4 - wins), row[2], " " * (7 - match), row[3]) print " =========================================================================\n" # NOQA raw_input('Press ENTER to continue') message = "" else: message = "There are no players assigned to this tournament"
def getRound(tid=100): ''' getRound(): return the current round of the Tournament, if the last round is complete, and the next round Argument: tid Return: Tournament round, Boolean for last round complete, Tournament next round ''' playerCount = tour.countPlayers(tid) # number of rounds in Swiss Pairing is based on number of players # need calculatedRounds to know when Tournament is finished # i.e., current round > calculatedRounds calculatedRounds = int(ceil(log(playerCount,2))) standings = tour.playerStandings(tid) sumMatches = 0 for playerStatistics in standings: pid,name,wins,matches = playerStatistics sumMatches += matches matchesPlayed = sumMatches / 2 sumMatches_div_playerCount = sumMatches / playerCount current_round = sumMatches_div_playerCount + 1 next_round = current_round + 1 round_complete = False if playerCount / 2 == matchesPlayed: # is True only when all matches for last round are played # is False during current_round round_complete = True return current_round, round_complete, next_round
def testStandingsBeforeMatches(): """ Test to ensure players are properly represented in standings prior to any matches being reported. """ tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Melpomene Murray") tournament.registerPlayer("Randy Schwartz") standings = tournament.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 "6. Newly registered players appear in the standings with no matches."
def testStandingsBeforeMatches(): tournament.deleteMatches() tournament.deletePlayers() tournament.registerPlayer("Melpomene Murray") tournament.registerPlayer("Randy Schwartz") standings = tournament.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( "6. Newly registered players appear in the standings with no \ matches." )
def getRound(tid=100): ''' getRound(): return the current round of the Tournament, if the last round is complete, and the next round Argument: tid Return: Tournament round, Boolean for last round complete, Tournament next round ''' playerCount = tour.countPlayers(tid) # number of rounds in Swiss Pairing is based on number of players # need calculatedRounds to know when Tournament is finished # i.e., current round > calculatedRounds calculatedRounds = int(ceil(log(playerCount, 2))) standings = tour.playerStandings(tid) sumMatches = 0 for playerStatistics in standings: pid, name, wins, matches = playerStatistics sumMatches += matches matchesPlayed = sumMatches / 2 sumMatches_div_playerCount = sumMatches / playerCount current_round = sumMatches_div_playerCount + 1 next_round = current_round + 1 round_complete = False if playerCount / 2 == matchesPlayed: # is True only when all matches for last round are played # is False during current_round round_complete = True return current_round, round_complete, next_round
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 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 displayStandings(): """ tournament standings are print to the screen """ results = tournament.playerStandings() print "Current standings are: " for i in results: print "id:{} name: {} wins: {} loses:\ {} ".format(i[0], i[1], i[2], i[3])
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 getWinner(): '''Return a bool signifying whether a winner could be determined, and, if True, the string of the winner's name''' standings = tournament.playerStandings() topScore = standings[0][2] # If the second best score is equal to the top score, we don't have a winner if standings[1][2] == topScore: return False, 'undetermined' else: # Return the name of the person with the top score return True, standings[0][1]
def cleanUp(): ''' Clear all matches stored in the database if there are no matches stored in the python code. This means that the tournament was closed before it was stored and the matches cannot be recorded. ''' standings = tournament.playerStandings() # There are some players registered if standings: # There are matches currently stored in the database but not in the code if standings[0][3] and not (previousRounds or lastTournamentResult): clearTournament()
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 menu(): """ menu system for swiss pair tournament """ choice = "" while choice != 'quit': print "What would you like to do: " print "1) add a player" print "2) start tournament" print "3) view current players" print "4) reset database" print "Enter quit to exit" choice = raw_input("> ") if choice == '1': print "Enter a player's name:" name = raw_input("> ") if name != "" or name != " ": tournament.registerPlayer(name) else: print "Invalid name" elif choice == '2': numberOfPlayers = tournament.countPlayers() if numberOfPlayers < 6: print "Insufficient number of players. Tournament can \ not be started." else: print "Do you wish to start the tournament?" print "You will not be able to add anymore players if you do." print "Enter yes to continue and no to cancel." start = raw_input("> ") if start == 'yes': choice = 'quit' startTournamentMenu() else: print "start of tournament cancelled" elif choice == '3': players = tournament.playerStandings() for i in players: print "player's name: {} id: {}".format(i[1], i[0]) elif choice == '4': print " Are you sure you want to erase the database:(yes/no)" answer = raw_input("> ") if answer == 'yes': tournament.deleteMatches() tournament.deletePlayers() elif answer == 'no': print "Deletion of database cancelled" else: print "Invalid input {}.".format(answer) elif choice == 'quit': print "Exiting now...." else: print "Invalid entry"
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 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 overall_tournament_results(self, web_support): """ This will create a web page for the overall results :param web_support: :return: """ html_file = create_html_page("Overall Tournament Results") results = tournament.playerStandings(0, self.database, self.cursor) print_html_standings(html_file, results, 0) html_file.write("</div>\n</body>\n</html>\n") html_file.close() url = os.path.abspath(html_file.name) if web_support == "True": webbrowser.open('file://' + url, new=2) # open in a new tab, if possible
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 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 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 display_standings(): ''' display_standings(): display the win/loss statistics of matches in the current Tournament Argument: none Return: None - returns to main menu TODO: add round to header ''' # get the current tid tid = getTid() # get round info current_round, round_complete, next_round = getRound(tid) # convert Long int current_round = int(current_round) print '=' * 80 print '''{:^80}'''.format('PLAYER STANDINGS') print '''{:>39} {:>3d}'''.format('Tournament:', tid) print '''{:>39} {:>3d}'''.format('Round:', current_round) print '-' * 80 print '''{:^5} {:^45} {:^5} {:^5}'''.format('PID', 'NAME', 'WINS', 'MATCHES') print '-' * 80 standings = tour.playerStandings(tid) for (pid, name, wins, matches) in standings: print ''' {0:^3d} {1:<45} {2:^3d} {3:^3d}'''.\ format(pid,name,wins,matches) print '=' * 80 queryEnter() return
def display_standings(): ''' display_standings(): display the win/loss statistics of matches in the current Tournament Argument: none Return: None - returns to main menu TODO: add round to header ''' # get the current tid tid = getTid() # get round info current_round, round_complete, next_round = getRound(tid) # convert Long int current_round = int(current_round) print '='*80 print '''{:^80}'''.format('PLAYER STANDINGS') print '''{:>39} {:>3d}'''.format('Tournament:', tid) print '''{:>39} {:>3d}'''.format('Round:', current_round) print '-'*80 print '''{:^5} {:^45} {:^5} {:^5}'''.format('PID','NAME','WINS','MATCHES') print '-'*80 standings = tour.playerStandings(tid) for (pid,name,wins,matches) in standings: print ''' {0:^3d} {1:<45} {2:^3d} {3:^3d}'''.\ format(pid,name,wins,matches) print '='*80 queryEnter() return
def ShowPlayers(env, resp): ''' Gets the current list of registered players. ''' cleanUp() # Remove matches if not stored in python (due to unsubmitted tournament) # get list of tuples (playerid, name, wins, matches, tourny_wins) players = tournament.playerStandings() playerList = '' # this will hold HTML content to format into templates.HTML_WRAP for player in players: # Use tuples to create HTML markup to organize each player's info and # store all of this in playerList playerList += templates.PLAYER % {'name': player[1], 'wins': player[2], 'matches': player[3], 'playerid': player[0], 'tournyWins': player[4] or 0} # playerList needs to be inside <ul> tags as each player is a <li> element roundList = '<ul>%s</ul>' % playerList headers = [('Content-type', 'text/html')] resp('200 OK', headers) # Fill the main template with the list of players return templates.HTML_WRAP % roundList
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]))
# using registerPlayerToTournament (id1, id2, id3, id4, id5, id6) = ( registerPlayer("Bruno Walton", (t0, t1)), registerPlayer("Boots O'Neal", (t0, t1)), 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
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." if __name__ == '__main__': testCount() testStandingsBeforeMatches() testReportMatches() testPairings() tournament.playerStandings() tournament.swissPairings() print "Success! All tests pass!"
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." if __name__ == '__main__': testCount() testStandingsBeforeMatches() testReportMatches() testPairings() tournament.playerStandings() tournament.swissPairings() print "Success! All tests pass!"
print "3rd place winner is: {}".format(player.next()) choice = 'quit' else: choice = raw_input("> ") if choice == '1': displayCurrentMatches(currentLineUp) elif choice == '2': displayStandings() elif choice == '3': updateMatches(currentLineUp) elif choice == 'quit': print "Exiting now" else: print "{} is an invalid choice, please try again".format(choice) def getTopThree(): """ returns the top three players one at a time """ for i in tournament.playerStandings(): yield i[1] if __name__ == "__main__": displayStandings() tournament.connect() # updateMatches() displayCurrentMatches(tournament.playerStandings()) menu()
def getTopThree(): """ returns the top three players one at a time """ for i in tournament.playerStandings(): yield i[1]
def start_tournament(self, tournament_name, web_support): """ This method is to start a new tournament. :param tournament_name: :return: """ self.logger.info("Starting New Tournament!!! Tournament Name = " + tournament_name ) self.output_fd.write("Starting New Tournament!!! Tournament Name = " + tournament_name + "\n") html_file = create_html_page(tournament_name) self.load_players_from_db() tournament.registerSwissTournament(tournament_name, self.database,self.cursor) tournament_id = tournament.getSwissTournamentId(tournament_name, self.database, self.cursor) results = tournament.playerStandings(tournament_id, self.database, self.cursor) print_standings(results, 1, self.output_fd) self.play_round(tournament_id, 1) tournament.updateSwissTournamentRound(tournament_id, 1, self.database, self.cursor) results = tournament.playerStandings(tournament_id, self.database, self.cursor) print_standings(results, 1, self.output_fd) print_html_standings(html_file, results, 1) past_matches = tournament.getPastMatchesForTournament(self.database, self.cursor, tournament_id) self.swisspairing = tournament.swissPairings(tournament_id, self.database, self.cursor, past_matches) self.play_round(tournament_id, 2) tournament.updateSwissTournamentRound(tournament_id, 2, self.database, self.cursor) results = tournament.playerStandings(tournament_id, self.database, self.cursor) print_standings(results, 2, self.output_fd) print_html_standings(html_file, results, 2) past_matches = tournament.getPastMatchesForTournament(self.database, self.cursor, tournament_id) self.swisspairing = tournament.swissPairings(tournament_id, self.database, self.cursor, past_matches) self.play_round(tournament_id, 3, past_matches) tournament.updateSwissTournamentRound(tournament_id, 3, self.database, self.cursor) results = tournament.playerStandings(tournament_id, self.database, self.cursor) print_standings(results, 3, self.output_fd) print_html_standings(html_file, results, 3) past_matches = tournament.getPastMatchesForTournament(self.database, self.cursor, tournament_id) self.swisspairing = tournament.swissPairings(tournament_id, self.database, self.cursor, past_matches) self.play_round(tournament_id, 4, past_matches) tournament.updateSwissTournamentRound(tournament_id, 4, self.database, self.cursor) results = tournament.playerStandings(tournament_id, self.database, self.cursor) print_standings(results, 4, self.output_fd) print_html_standings(html_file, results, 4) html_file.write("</div>\n</body>\n</html>\n") html_file.close() url = os.path.abspath(html_file.name) if web_support == "True": webbrowser.open('file://' + url, new=2) # open in a new tab, if possible
def test_list_win_ranking(self): """playerStandings() function executes without issue""" self.assertTrue(tournament.playerStandings())