コード例 #1
0
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."
コード例 #2
0
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."
コード例 #3
0
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")
コード例 #4
0
def handleFirstRound():
    '''Return matchList for the current set of matches at the beginning of a new
    round.
    '''
    global roundsLeft, matchesToPlay, currentMatches
    matchList = ''

    prepareForNextRound() # Clear currentMatches and insert into database

    # A match must be played for every swiss pairing
    pairings = tournament.swissPairings()
    matchesToPlay = len(pairings)

    i = 0 # index for the matches for the current round
    # use the information in pairings to create a currentMatches list of
    # dictionaries holding information about each match
    for pairing in pairings:
        currentMatches.append(createMatch(pairing, i))
        # Keep track of index to determine which round users are interacting
        # with.
        i += 1
    # Append all previous match results to roundList
    # Add all current matches to the match list
    for match in currentMatches:
        matchList = addPendingMatch(matchList, match)
    # We've now handled the round, all that is left is to play matchesToPlay
    # matches
    roundsLeft -= 1
    return matchList
コード例 #5
0
def initTournament():
    '''Set up a tournament with a correct number of rounds'''
    global tournamentBegan, roundsLeft
    tournamentBegan = True
    # Determine the number of rounds that need to be played based on the number
    # of swiss pairings.
    roundsLeft = determineRoundsNeeded(len(tournament.swissPairings()))
コード例 #6
0
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."
コード例 #7
0
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!'
コード例 #8
0
ファイル: index.py プロジェクト: phyrenight/Udacity-project-2
def startTournamentMenu():
    """
        menu to update each match. To view the standings and the match line ups
    """

    currentLineUp = tournament.swissPairings()
    numberOfPlayers = tournament.countPlayers()
    totalMatchesPlayed = 0
    matchesPlayedThisRound = 0
    totalMatches = numberOfPlayers * (numberOfPlayers-1)
    print numberOfPlayers, totalMatches
    choice = ""
    while choice != 'quit':
        if matchesPlayedThisRound == numberOfPlayers/2:
            # checks to see if all the matches were played for the round
            currentLineUp = tournament.swissPairings()
            matchesPlayedThisRound = 0
            displayCurrentMatches()
        print "How would you like to proceed:"
        print "1) Display current matches"
        print "2) Display player's current standings"
        print "3) Update current matches"
        print "Enter quit to exit"
        if totalMatchesPlayed == totalMatches:
            player = getTopThree()
            print "tournament has ended"
            print "1st place winner is: {}".format(player.next())
            print "2nd place winner is: {}".format(player.next())
            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)
コード例 #9
0
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")
コード例 #10
0
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
コード例 #11
0
def display_pairings(pause=True):
    '''
    display_pairings(): display the PID and Player names paired (matched)
    for the next round in the current Tournament

    TODO: Extra Credit - Prevent rematches between players in a tournament.

    TODO: Argument: pairings - object
              prompt - Boolean controls pausing display

    Return: None - returns to main menu
    '''
    # get Tournament ID, pairings, and round information
    tid = getTid()
    pairings = tour.swissPairings(tid)

    current_round, round_complete, next_round = getRound(tid)
    # convert Long int
    current_round = int(current_round)

    print '=' * 80
    print '''{:^80}'''.format('PLAYER PAIRING')
    print '''{:>39} {:>3d}'''.format('Tournament:', tid)
    print '''{:>39} {:>3d}'''.format('Round:', current_round)
    if current_round == 1:
        text = 'adjacent PID\'s'
        print '''{:>40} {:<{width}}'''.format('Pairing by: ',
                                              text,
                                              width=len(text))
    else:
        text = 'adjacent PID\'s'
        print '''{:>40} {:<{width}}'''.format('Pairing by: ',
                                              text,
                                              width=len(text))
    print '-' * 80
    print '''  {:^9}  {:^25}  {:^5}  {:^9}  {:^25}'''.\
               format('PLAYER 1','NAME',' ','PLAYER 2','NAME')

    print ''' {:^9}  {:^31}  {:^9}'''.\
              format('PID','  ','PID')
    print '-' * 80

    for (pid1, name1, pid2, name2) in pairings:
        print ''' {:^9d}  {:<25}  {:^5}  {:^9d}  {:<25}'''.\
                  format(pid1,name1,'vs.',pid2,name2)
    print '=' * 80

    # pause to allow the pairing table to be viewed
    if pause:
        queryEnter()

    return
コード例 #12
0
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
コード例 #13
0
ファイル: populate_data.py プロジェクト: gravic07/tournament
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!'
コード例 #14
0
def display_pairings(pause=True):
    '''
    display_pairings(): display the PID and Player names paired (matched)
    for the next round in the current Tournament

    TODO: Extra Credit - Prevent rematches between players in a tournament.

    TODO: Argument: pairings - object
              prompt - Boolean controls pausing display

    Return: None - returns to main menu
    '''
    # get Tournament ID, pairings, and round information
    tid = getTid()
    pairings = tour.swissPairings(tid)

    current_round, round_complete, next_round = getRound(tid)
    # convert Long int
    current_round = int(current_round)

    print '='*80
    print '''{:^80}'''.format('PLAYER PAIRING')
    print '''{:>39} {:>3d}'''.format('Tournament:', tid)
    print '''{:>39} {:>3d}'''.format('Round:', current_round)
    if current_round == 1:
        text = 'adjacent PID\'s'
        print '''{:>40} {:<{width}}'''.format('Pairing by: ', text, width=len(text))
    else:
        text = 'adjacent PID\'s'
        print '''{:>40} {:<{width}}'''.format('Pairing by: ', text, width=len(text))
    print '-'*80
    print '''  {:^9}  {:^25}  {:^5}  {:^9}  {:^25}'''.\
               format('PLAYER 1','NAME',' ','PLAYER 2','NAME')

    print ''' {:^9}  {:^31}  {:^9}'''.\
              format('PID','  ','PID')
    print '-'*80

    for (pid1,name1,pid2,name2) in pairings:
        print ''' {:^9d}  {:<25}  {:^5}  {:^9d}  {:<25}'''.\
                  format(pid1,name1,'vs.',pid2,name2)
    print '='*80

    # pause to allow the pairing table to be viewed
    if pause:
        queryEnter()

    return
コード例 #15
0
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"
コード例 #16
0
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.")
コード例 #17
0
ファイル: play.py プロジェクト: stonescar/tournament-planner
def printSwiss(t):
    """Prints the player pairings after the Swiss model"""
    global message
    pairings = swissPairings(t)
    if pairings:
        c = 0
        os.system('cls' if os.name == 'nt' else 'clear')
        print """\n\n
                    -----------------------------------------
                         SWISS PAIRINGS FOR NEXT ROUND:
                    ------------------- o -------------------
                                        |"""
        for pair in pairings:
            c += 1
            id1, name1, id2, name2 = pair
            p1, p2 = ("%s (ID: %s)" % (name1, id1),
                      "%s (ID: %s)" % (name2, id2))
            print "%s%s   V S   %s" % (" " * (36 - len(p1)), p1, p2)
            print "                                        |"
        print "                                  ----- o -----\n\n"
        raw_input('Press ENTER to continue')
        message = ""
    else:
        message = "There are no players assigned to this tournament"
コード例 #18
0
    # Register all players
    for player in PLAYERS:
        registerPlayer(player)

    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
コード例 #19
0
def originalTestPairings():
    pairings = swissPairings()
    print(pairings)
コード例 #20
0
ファイル: demo.py プロジェクト: jrrembert/tournament
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]))
コード例 #21
0
        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!"
コード例 #22
0
    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!"
コード例 #23
0
ファイル: populate.py プロジェクト: bkeyvani/fsnd
    # Register all players
    for player in PLAYERS:
        registerPlayer(player)

    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
コード例 #24
0
tournament.registerTournamentPlayer(chess_tournament, b)
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"
コード例 #25
0
    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
コード例 #26
0
ファイル: test.py プロジェクト: johlym/tournament
 def test_no_players(self):
     """swissPairings() throws if there are no players in the database"""
     q = "TRUNCATE TABLE players;"
     tools.query(q)
     with self.assertRaises(ValueError):
         tournament.swissPairings()