def add_player(name=None):
    '''
    add_player(): Register a new Player for the current Tournament. The Player
    ID (PID) will be assigned by the dB. The Player's name is input by the user
    and verified to contain non-numeric characters.

    Argument: name - default = None

    Return: None - returns to main menu
    '''
    tid = getTid()

    if tid < 100:
        print 'Please "Select Tournament" from the main menu.'
        queryEnter()
        return

    print '''Tournament Manager supports an even numbers of players. This function will help you add two players at a time.'''.format(
    )

    while True:
        # the name must be alphabetic characters only
        pname = verify_name()
        tour.registerPlayer(pname, tid)
        if tour.countPlayers(tid) % 2 != 0:
            continue
        else:
            break

    # display registered tournament players after entry
    display_players()
    return
def AddPlayer(env, resp):
    '''
    Add a player into the SQL database.
    '''
    # Get fields from the submitted form
    fields = getFields(env)

    # Use a try and except to avoid KeyError if the input field is empty
    try:
        player = fields['new-player'][0]
    except KeyError:
        print 'No input string for new player.'
        player = ''

    # If the name is just whitespace, don't save it.
    player = player.strip()

    # Cut down to 9 characters to avoid names leaking over buttons
    if len(player) > 9:
        player = player[:9]

    if player: # player is not an empty string
        # Save it in the database
        clearTournament() # need to reset tournament, otherwise new player confuses it
        tournament.registerPlayer(player)

    # 302 redirect back to the player standings
    headers = [('Location', '/ShowPlayers'),
               ('Content-type', 'text/plain')]
    resp('302 REDIRECT', headers)
    return ['Redirecting']
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 add_player(name=None):
    '''
    add_player(): Register a new Player for the current Tournament. The Player
    ID (PID) will be assigned by the dB. The Player's name is input by the user
    and verified to contain non-numeric characters.

    Argument: name - default = None

    Return: None - returns to main menu
    '''
    tid = getTid()

    if tid < 100:
        print 'Please "Select Tournament" from the main menu.'
        queryEnter()
        return

    print '''Tournament Manager supports an even numbers of players. This function will help you add two players at a time.'''.format()

    while True:
        # the name must be alphabetic characters only
        pname = verify_name()
        tour.registerPlayer(pname, tid)
        if tour.countPlayers(tid) % 2 != 0:
            continue
        else:
            break

    # display registered tournament players after entry
    display_players()
    return
def testCount():
    """
    Test for initial player count,
             player count after 1 and 2 players registered,
             player count after players deleted.
    """
    tournament.deleteMatches()
    tournament.deletePlayers()
    c = tournament.countPlayers()
    if c == '0':
        raise TypeError(
            "countPlayers should return numeric zero, not string '0'.")
    if c != 0:
        raise ValueError(
            "After deletion, countPlayers should return zero. Got {c}".format(c=c))
    print "1. countPlayers() returns 0 after initial deletePlayers() execution."
    tournament.registerPlayer("Chandra Nalaar")
    c = tournament.countPlayers()
    if c != 1:
        raise ValueError(
            "After one player registers, countPlayers() should be 1. Got {c}".format(c=c))
    print "2. countPlayers() returns 1 after one player is registered."
    tournament.registerPlayer("Jace Beleren")
    c = tournament.countPlayers()
    if c != 2:
        raise ValueError(
            "After two players register, countPlayers() should be 2. Got {c}".format(c=c))
    print "3. countPlayers() returns 2 after two players are registered."
    tournament.deletePlayers()
    c = tournament.countPlayers()
    if c != 0:
        raise ValueError(
            "After deletion, countPlayers should return zero.")
    print "4. countPlayers() returns zero after registered players are deleted.\n5. Players can be registered and deleted."
def testRegister():
    tournament.deleteMatches()
    tournament.deletePlayers()
    tournament.registerPlayer("Chandra Nalaar")
    c = tournament.countPlayers()
    if c != 1:
        raise ValueError("After one player registers, countPlayers() should be 1.")
    print("4. After registering a player, countPlayers() returns 1.")
Example #8
0
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 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 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"
Example #11
0
def setup_players_and_matches():
    testDelete()
    # create a tournament
    tourney = Tourney.create_tournament("One Hundred")
    for player in the_players:
        p_id = registerPlayer(player[1], tourney.id)
        player_ids.append(p_id)

    create_random_matches(the_players, tourney, 100)
def setup_players_and_matches():
    testDelete()
    # create a tournament
    tourney = Tourney.create_tournament("One Hundred")
    for player in the_players:
        p_id = registerPlayer(player[1], tourney.id)
        player_ids.append(p_id)

    create_random_matches(the_players, tourney, 100)
Example #13
0
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 testRegisterCountDelete():
    tournament.deleteMatches()
    tournament.deletePlayers()
    tournament.registerPlayer("Markov Chaney")
    tournament.registerPlayer("Joe Malik")
    tournament.registerPlayer("Mao Tsu-hsi")
    tournament.registerPlayer("Atlanta Hope")
    c = tournament.countPlayers()
    if c != 4:
        raise ValueError("After registering four players, countPlayers should be 4.")
    tournament.deletePlayers()
    c = tournament.countPlayers()
    if c != 0:
        raise ValueError("After deleting, countPlayers should return zero.")
    print("5. Players can be registered and deleted.")
def testCount():
    """
    Test for initial player count,
             player count after 1 and 2 players registered,
             player count after players deleted.
    """
    tournament.deleteMatches()
    tournament.deletePlayers()
    c = tournament.countPlayers()
    if c == '0':
        raise TypeError(
            "countPlayers should return numeric zero, not string '0'.")
    if c != 0:
        raise ValueError(
            "After deletion, countPlayers should return zero. Got {c}".format(
                c=c))
    print "1. countPlayers() returns 0 after initial deletePlayers() execution."
    tournament.registerPlayer("Chandra Nalaar")
    c = tournament.countPlayers()
    if c != 1:
        raise ValueError(
            "After one player registers, countPlayers() should be 1. Got {c}".
            format(c=c))
    print "2. countPlayers() returns 1 after one player is registered."
    tournament.registerPlayer("Jace Beleren")
    c = tournament.countPlayers()
    if c != 2:
        raise ValueError(
            "After two players register, countPlayers() should be 2. Got {c}".
            format(c=c))
    print "3. countPlayers() returns 2 after two players are registered."
    tournament.deletePlayers()
    c = tournament.countPlayers()
    if c != 0:
        raise ValueError("After deletion, countPlayers should return zero.")
    print "4. countPlayers() returns zero after registered players are deleted.\n5. Players can be registered and deleted."
Example #16
0
def testCount():
    """
    Test for initial player count,
             player count after 1 and 2 players registered,
             player count after 4 players reg and 2 assigned
             player count after players deleted.
    """
    deleteMatches()
    deletePlayers()
    deleteTournaments()
    c = countPlayers()
    if c == '0':
        raise TypeError(
            "countPlayers should return numeric zero, not string '0'.")
    if c != 0:
        raise ValueError("After deletion, countPlayers should return zero.")
    print ("1.  countPlayers() returns 0 after "
           "initial deletePlayers() execution.")
    registerPlayer("Chandra Nalaar")
    c = countPlayers()
    if c != 1:
        raise ValueError("After one player registers, countPlayers() should "
                         "be 1. Got {c}".format(c=c))
    print "2.  countPlayers() returns 1 after one player is registered."
    registerPlayer("Jace Beleren")
    c = countPlayers()
    if c != 2:
        raise ValueError("After two players register, countPlayers() should "
                         "be 2. Got {c}".format(c=c))
    print "3.  countPlayers() returns 2 after two players are registered."

    t1 = newTournament("Tournament 1")
    p1 = registerPlayer("Steinar Utstrand")
    p2 = registerPlayer("Donald Duck")
    assignPlayers(t1, p1, p2)
    c = countPlayers()
    if c != 4:
        raise ValueError("Even players not assigned to "
                         "tournament should be counted.")
    print ("4.  countPlayers() returns 4 when 2 of 4 players are assigned "
           "to tournament.")
    c = countPlayers(t1)
    if c != 2:
        raise ValueError("countPlayers(t_id) should only count players "
                         "assigned to given tournament")
    print ("5.  countPlayers(t_id) returns 2 when 2 of 4 players are assigned "
           "to given tournament id")

    deletePlayers()
    c = countPlayers()
    if c != 0:
        raise ValueError(
            "After deletion, countPlayers should return zero.")
    print ("6.  countPlayers() returns zero after registered players are "
           "deleted.\n7.  Player records successfully deleted.")
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 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 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 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.
    """
    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 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"
Example #23
0
            ?+menu item for help (Ex: '?5')


    """ % (active_t, message))
    selection = raw_input('Select a menu item: ')

    if selection == '1':  # New tournament
        t_name = raw_input('Tournament name: ')
        t_id = newTournament(t_name)
        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
Example #24
0
def dummy_player(player_name="", country=""):
    s = tournament.registerPlayer(player_name=player_name, country=country)
    return s
Example #25
0
    create_tables()
    logger.info('Created tables')
    create_indices()
    logger.info('Created indices')
    create_views()
    logger.info('Created views')

    # Register players
    PLAYERS = ['Player 1', 'Player 2', 'Player 3', 'Player 4', 'Player 5', 'Player 6', 'Player 7', 'Player 8', 'Player 9', 'Player 10', 'Player 11', 'Player 12', 'Player 13', 'Player 14', 'Player 15', 'Player 16', 'Player 17', 'Player 18', 'Player 19', 'Player 20', 'Player 21', 'Player 22', 'Player 23', 'Player 24', 'Player 25', 'Player 26', 'Player 27', 'Player 28', 'Player 29', 'Player 30', 'Player 31', 'Player 32', 'Player 33', 'Player 34', 'Player 35', 'Player 36', 'Player 37', 'Player 38', 'Player 39', 'Player 40', 'Player 41', 'Player 42', 'Player 43', 'Player 44', 'Player 45', 'Player 46', 'Player 47', 'Player 48', 'Player 49', 'Player 50', 'Player 51', 'Player 52', 'Player 53', 'Player 54', 'Player 55', 'Player 56', 'Player 57', 'Player 58', 'Player 59', 'Player 60', 'Player 61', 'Player 62', 'Player 63', 'Player 64',]

    # Shuffle PLAYERS in order to have a random list
    random.shuffle(PLAYERS)

    # 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]
Example #26
0
from tournament import registerPlayer, reportMatch, connect
import random

for i in range(0,15):
    registerPlayer("player%s" % i)

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)

createRandomMatches(10)
    def load_players_from_file(self, filename):
        """
        This will load all the players from file and save them to the database
        :param filename:
        :return:
        """
        tournament.deletePlayers(self.database,self.cursor)
        try:
            players = open(filename, "r")
        except IOError, error:
            raise IOError(error.message)
        else:
            for line in players:
                player = line.strip('\n')
                tournament.registerPlayer(player, self.database, self.cursor)
        finally:
            players.close()

    def number_of_players(self):
        """
        This sets the number of players in the tournament
        :return:
        """
        players = tournament.countPlayers(self.database, self.cursor)
        self.logger.info("Number of players " + str(players))
        self.numplayers = players

    def load_players_from_db(self):
        """
        This will load the players from the database and setup
def registerPlayers(list):
    for person in list:
        tournament.registerPlayer(person)
Example #29
0
from pprint import pprint


if __name__ == '__main__':

    # Create some new tournaments
    t0 = registerTournament('t0')
    t1 = registerTournament('t1')

    # Register some players
    # Here, we register players to tournaments too
    # although that isn't strictly necessary.
    # It can be done in a separete step
    # 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
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."
Example #31
0
 def test_name_first_and_last(self):
     """registerPlayer() should reject if both a first and last name aren't
     present"""
     with self.assertRaises(AttributeError):
         tournament.registerPlayer(player_name="James")
import math
import random
import tournament

# register tournaments
chess_tournament = tournament.registerTournament('Chess Master Tournament')

# register players
a = tournament.registerPlayer('Adam')
b = tournament.registerPlayer('Bogdan')
c = tournament.registerPlayer('Cristina')
d = tournament.registerPlayer('Daniel')
e = tournament.registerPlayer('Elena')

# register tournaments players
tournament.registerTournamentPlayer(chess_tournament, a)
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
def registerPlayers(list):
    for person in list:
        tournament.registerPlayer(person)
Example #34
0
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]))
Example #35
0
 def test_name_less_two_characters(self):
     """registerPlayer() should reject if name is less than two characters"""
     with self.assertRaises(AttributeError):
         tournament.registerPlayer(player_name="a")
Example #36
0
        'Player 57',
        'Player 58',
        'Player 59',
        'Player 60',
        'Player 61',
        'Player 62',
        'Player 63',
        'Player 64',
    ]

    # Shuffle PLAYERS in order to have a random list
    random.shuffle(PLAYERS)

    # 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]
Example #37
0
 def test_name_contains_symbols(self):
     """registerPlayer() should reject if name contains symbols"""
     with self.assertRaises(AttributeError):
         tournament.registerPlayer(player_name="J!mes Dean")
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."
Example #39
0
 def test_name_contains_integer(self):
     """registerPlayer() should reject if name contains integer"""
     with self.assertRaises(AttributeError):
         tournament.registerPlayer(player_name="1")