Exemplo n.º 1
0
def create_tables():
    """
    Create players and matches tables.
    """
    conn = connect()
    c = conn.cursor()

    # Create players table
    c.execute("""
        CREATE TABLE players (
            name text NOT NULL,
            id serial PRIMARY KEY
        );
        """)

    # Create matches table
    c.execute("""
        CREATE TABLE matches (
            winner int REFERENCES players (id),
            loser int REFERENCES players (id),
            PRIMARY KEY (winner, loser)
        );
        """)
    conn.commit()
    conn.close()
Exemplo n.º 2
0
def countPlayers():
    """Returns the number of players currently registered."""

    conn, c = main.connect()
    c.execute("SELECT count(*) FROM player")

    return c.fetchone()[0]
Exemplo n.º 3
0
def create_tables():
    """
    Create players and matches tables.
    """
    conn = connect()
    c = conn.cursor()

    # Create players table
    c.execute(
        """
        CREATE TABLE players (
            name text NOT NULL,
            id serial PRIMARY KEY
        );
        """)

    # Create matches table
    c.execute(
        """
        CREATE TABLE matches (
            winner int REFERENCES players (id),
            loser int REFERENCES players (id),
            PRIMARY KEY (winner, loser)
        );
        """)
    conn.commit()
    conn.close()
Exemplo n.º 4
0
def registerPlayerUpdated(tournament, id, name):
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (tournament, id, name) VALUES (%s, %s, %s)"
    db_cursor.execute(query, (tournament, id, name,))
    print '==>  ' + name + ' has been registered for tournament: ' + tournament
    db.commit()
    db.close()
Exemplo n.º 5
0
def deleteMatches():
    """Remove all the match records from the database."""

    conn, c = main.connect()

    c.execute("TRUNCATE tournamentMatch")

    conn.commit()
    conn.close()
Exemplo n.º 6
0
def deletePlayers():
    """Remove all the player records from the database."""

    conn, c = main.connect()

    c.execute("TRUNCATE player CASCADE")

    conn.commit()
    conn.close()
def registerPlayerSample(player_id, name, tourn_id=1):
    """Add a player to the tournament database.
    Args:
      name: the player's full name (need not be unique).
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (player_id, name, tournament_id) VALUES (%s, %s, %s)"
    db_cursor.execute(query, (player_id, name, tourn_id))
    db.commit()
    db.close()
Exemplo n.º 8
0
def get_t_name(t):
    """Returns the player's name from id, if found"""
    t = bleach.clean(t)
    db, c = connect()
    c.execute("SELECT name FROM tournaments WHERE id = %s", (t, ))
    if c.rowcount > 0:
        name = c.fetchone()[0]
        db.close()
        return name
    else:
        db.close()
def registerPlayerSample(player_id, name, tourn_id=1):
    """Add a player to the tournament database.
    Args:
      name: the player's full name (need not be unique).
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (player_id, name, tournament_id) VALUES (%s, %s, %s)"
    db_cursor.execute(query, (player_id, name, tourn_id))
    db.commit()
    db.close()
Exemplo n.º 10
0
def registerPlayerUpdated(id, name):
    """Add a player to the tournament database.

    The database assigns a unique serial id number for the player.

    """
    db = connect()
    db_cursor = db.cursor()
    print name
    query = "INSERT INTO players(id, name) VALUES ('%s','%s')" % (id, name)
    db_cursor.execute(query)
    db.commit()
    db.close()
Exemplo n.º 11
0
def registerPlayerUpdated(player_id, name):
    """Add a player to the tournament database.
    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)
    Args:
      name: the player's full name (need not be unique).
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (id, name) VALUES (%s, %s)"
    db_cursor.execute(query, (player_id, name))
    db.commit()
    db.close()
Exemplo n.º 12
0
def registerPlayerUpdated(player_id, name):
    """Add a player to the tournament database.
    The database assigns a unique serial id number for the player.  (This
    should be handled by your SQL database schema, not in your Python code.)
    Args:
      name: the player's full name (need not be unique).
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (id, name) VALUES (%s, %s)"
    db_cursor.execute(query, (player_id, name))
    db.commit()
    db.close()
Exemplo n.º 13
0
def create_indices():
    """
    Create indices for tables.
    """
    conn = connect()
    c = conn.cursor()

    # To prevent rematch btw players
    c.execute("""
        CREATE UNIQUE INDEX matches_uniq_idx ON matches
           (greatest(winner, loser), least(winner, loser));
        """)
    conn.commit()
    conn.close()
 def __init__(self, supportodd, logger, output_fd):
     """
     This is the constructor.  It takes one parameter if
     we will support odd lists
     :param supportodd:
     :return:
     """
     self.players = dict()
     self.swisspairing = []
     self.numplayers = None
     self.supportodd = supportodd
     self.database, self.cursor = tournament.connect()
     self.logger = logger
     self.output_fd = output_fd
Exemplo n.º 15
0
def create_indices():
    """
    Create indices for tables.
    """
    conn = connect()
    c = conn.cursor()

    # To prevent rematch btw players
    c.execute(
        """
        CREATE UNIQUE INDEX matches_uniq_idx ON matches
           (greatest(winner, loser), least(winner, loser));
        """)
    conn.commit()
    conn.close()
Exemplo n.º 16
0
def create_views():
    """
    Create the views for the following:

    v_numMatches: The number of matches each player has played
    v_numWins: The number of wins for each player
    v_playerStandings
    """
    conn = connect()
    c = conn.cursor()

    # Create v_numMatches view
    c.execute(
        """
        CREATE VIEW v_numMatches AS
            SELECT id, COUNT(winner) AS matchesPlayed
            FROM players LEFT JOIN matches
            ON (winner = id OR loser = id)
            GROUP BY players.id
            ORDER BY players.id;
        """)

    # Create v_numWins view
    c.execute(
        """
        CREATE VIEW v_numWins AS
            SELECT players.id, COUNT(winner) AS wins
            FROM players LEFT JOIN matches
            ON players.id = matches.winner
            GROUP BY players.id
            ORDER BY wins DESC;
        """)

    # Create v_playerStandings view
    c.execute(
        """
        CREATE VIEW v_playerStandings AS
            SELECT players.id, players.name, v_numWins.wins,
                   v_numMatches.matchesPlayed AS matches
            FROM players
            LEFT JOIN v_numWins ON
            (players.id = v_numWins.id)
            JOIN v_numMatches ON (players.id = v_numMatches.id)
            ORDER BY wins DESC;
        """)

    conn.commit()
    conn.close()
Exemplo n.º 17
0
def registerPlayerUpdated(tournament, id, name):
    """Add a player to the tournament database.

	This calls registerPlayer and adds the ability to set the players ID.

    Args:
      tournament:  A three character code assigned to each tournament.
			  id:  Establish the ID for player.  This NEEDS to be a unique value.
            name:  The player's full name.  This does not need to be a uniue value.
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (tournament, id, name) VALUES (%s, %s, %s)"
    db_cursor.execute(query, (tournament, id, name,))
    print '==>  ' + name + ' has been registered for tournament: ' + tournament
    db.commit()
    db.close()
Exemplo n.º 18
0
def create_views():
    """
    Create the views for the following:

    v_numMatches: The number of matches each player has played
    v_numWins: The number of wins for each player
    v_playerStandings
    """
    conn = connect()
    c = conn.cursor()

    # Create v_numMatches view
    c.execute("""
        CREATE VIEW v_numMatches AS
            SELECT id, COUNT(winner) AS matchesPlayed
            FROM players LEFT JOIN matches
            ON (winner = id OR loser = id)
            GROUP BY players.id
            ORDER BY players.id;
        """)

    # Create v_numWins view
    c.execute("""
        CREATE VIEW v_numWins AS
            SELECT players.id, COUNT(winner) AS wins
            FROM players LEFT JOIN matches
            ON players.id = matches.winner
            GROUP BY players.id
            ORDER BY wins DESC;
        """)

    # Create v_playerStandings view
    c.execute("""
        CREATE VIEW v_playerStandings AS
            SELECT players.id, players.name, v_numWins.wins,
                   v_numMatches.matchesPlayed AS matches
            FROM players
            LEFT JOIN v_numWins ON
            (players.id = v_numWins.id)
            JOIN v_numMatches ON (players.id = v_numMatches.id)
            ORDER BY wins DESC;
        """)

    conn.commit()
    conn.close()
Exemplo n.º 19
0
def getPlayerIDFromName(name):
    """Return the player ID for the name specified."""

    # Connect to the database.
    conn, c = main.connect()

    # Select the player that matches the name.
    SQL = "SELECT playerID FROM player WHERE playerName=%s"
    data = (name, )
    c.execute(SQL, data)

    toReturn = c.fetchone()

    conn.commit()
    conn.close()

    # Only return the first result
    return toReturn[0]
Exemplo n.º 20
0
def swissPairings():
    """
    Returns a list of pairs of players for the next round of a match.
    Legacy function for older tournament tests.

    Assuming that there are an even number of players registered, each player
    appears exactly once in the pairings.  Each player is paired with another
    player with an equal or nearly-equal win record, that is, a player adjacent
    to him or her in the standings.

    Returns:
      A list of tuples, each of which contains (id1, name1, id2, name2)
        id1: the first player's unique id
        name1: the first player's name
        id2: the second player's unique id
        name2: the second player's name
    """

    # Returns a sorted list of player standings.
    playerStandingsList = playerStandings()

    # Open DB.
    conn, c = main.connect()

    # Get each player's details.
    c.execute("SELECT playerID, playerName from player;")
    allPlayers = c.fetchall()
    totalPlayers = len(allPlayers)

    swissPairingsList = []

    # As this is a legacy function, bye rounds should not be accounted for.
    i = 0
    while i < totalPlayers:

        p1 = playerStandingsList[i]
        p2 = playerStandingsList[i+1]

        swissPairingsList.append((p1[0], p1[1], p2[0], p2[1]))

        i += 2

    # return the new list (id1, name1, id2, name2)
    return swissPairingsList
Exemplo n.º 21
0
def registerPlayer(playerName):
    """
    Adds a player to the tournament database. Included as legacy support for
    older tournament tests.

    Args:
      name: the player's full name (need not be unique).
    """

    tournName = "Tournament for legacy tests"

    # Connect to database
    conn, c = main.connect()

    # Insert a new player with this name
    SQL = "INSERT INTO player (playerName) values (%s);"
    data = (playerName, )
    c.execute(SQL, data)

    # If the legacy tournament doesn't exist,
    if main.getTournamentIDFromName(tournName) == None:
        SQL = "INSERT INTO tournament (tournamentName) values (%s);"
        data = (tournName, )
        c.execute(SQL, data)

    # Commit current changes.
    conn.commit()

    # Retrieve the newly created player, and legacy tournament.
    playerID = getPlayerIDFromName(playerName)
    tournID = main.getTournamentIDFromName(tournName)

    # Insert the player into the tournament.
    SQL = ("INSERT INTO tournamentPlayer (tournamentID, playerID)"
           " values (%s, %s);")
    data = (tournID, playerID)
    c.execute(SQL, data)

    # Close database connection
    conn.commit()
    conn.close()
Exemplo n.º 22
0
def registerPlayerUpdated(tournament, id, name):
    """Add a player to the tournament database.

	This calls registerPlayer and adds the ability to set the players ID.

    Args:
      tournament:  A three character code assigned to each tournament.
			  id:  Establish the ID for player.  This NEEDS to be a unique value.
            name:  The player's full name.  This does not need to be a uniue value.
    """
    db = connect()
    db_cursor = db.cursor()
    query = "INSERT INTO players (tournament, id, name) VALUES (%s, %s, %s)"
    db_cursor.execute(query, (
        tournament,
        id,
        name,
    ))
    print '==>  ' + name + ' has been registered for tournament: ' + tournament
    db.commit()
    db.close()
Exemplo n.º 23
0
def createRandomMatches(num_matches):
    db = connect()
    cursor = db.cursor()
    cursor.execute("select * from players")
    player_list = cursor.fetchall()
    db.close()
    num_players = len(player_list)
    for i in xrange(num_matches):
        print 'match %s' % (i+1)
        player1_index = random.randint(0, num_players - 1)
        player2_index = random.randint(0, num_players - 1)
        if player2_index == player1_index:
            player2_index = (player1_index + 1) % num_players
        winner_id = player_list[player1_index][0]
        winner_name = player_list[player1_index][1]
        loser_id = player_list[player2_index][0]
        loser_name = player_list[player2_index][0]
        reportMatch(winner_id, loser_id)
        print "%s (id = %s) beat %s (id = %s)" % (
            winner_name,
            winner_id,
            loser_name,
            loser_id)
def createRandomMatches(player_list, num_matches):
    num_players = len(player_list)
    db = connect()
    db_cursor = db.cursor()
    for i in xrange(num_matches):
        print 'match1'
        player1_index = random.randint(0, num_players - 1)
        player2_index = random.randint(0, num_players - 1)
        if player2_index == player1_index:
            player2_index = (player1_index + 1) % num_players
        winner_id = player_list[player1_index][0]
        winner_name = player_list[player1_index][1]
        loser_id = player_list[player2_index][0]
        loser_name = player_list[player2_index][1]
        reportMatch(winner_id, loser_id)
        print "%s (id=%s) beat %s (id=%s)" % (
            winner_name,
            winner_id,
            loser_name,
            loser_id)
        query = "INSERT INTO matches (winner, loser) VALUES (%s, %s)"
        db_cursor.execute(query, (winner_id, loser_id))
        db.commit()
    db.close()
Exemplo n.º 25
0
            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()
Exemplo n.º 26
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]))