Skip to content

Commit

Permalink
* cleaned + sql pairing working
Browse files Browse the repository at this point in the history
  • Loading branch information
tboquet committed Oct 25, 2015
1 parent 9ba032b commit b62bb10
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 104 deletions.
2 changes: 1 addition & 1 deletion vagrant/forum/forumdb.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#
# Database access functions for the web forum.
#
#

import time
import psycopg2
Expand Down
187 changes: 96 additions & 91 deletions vagrant/tournament/tournament.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,59 +96,80 @@ def countMatches():


def registerTournament(t_name):
"""Adds a player to the tournament database.
"""Adds a tournament to the tournament table.
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.)
The database assigns a unique serial id number for the tournament.
Args:
f_name(str): the player's first name.
name(str): the player's name
t_name(str): the tournament's name.
"""
conn = connect()
query = "insert into tournaments (t_name) values ({!r})"
query = "insert into tournaments (t_name) values (%s)"
c = conn.cursor()
c.execute(query.format(t_name))

c.execute(query, (t_name,))
conn.commit()
conn.close()


def registerPlayer(f_name, name):
"""Adds a player to the tournament database.
"""Adds a player to the player_c table.
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.)
The database assigns a unique serial id number for the player.
Args:
f_name(str): the player's first name.
name(str): the player's name
"""
conn = connect()
query = "insert into players_c (p_sname, p_name) values ({!r}, {!r})"
query = "insert into players_c (p_sname, p_name) values (%s, %s)"
c = conn.cursor()
c.execute(query.format(f_name, name))
c.execute(query, (f_name, name))
conn.commit()
conn.close()


def getTournamentId(tournament_name):
"""Utility function to retrieve a tournament id using its name
Args:
tournament_name(str): the name of the tournament
Returns:
the unique id of a tournament (int).
.. note::
We take the first tournament we find in the db!!!"""

# get the tournament's id
conn = connect()
c = conn.cursor()
query = "select id_tournament from tournaments where t_name={!r}"
c.execute(query.format(tournament_name))
query = "select id_tournament from tournaments where t_name=%s"
c.execute(query, (tournament_name,))
t_id = c.fetchall()
conn.close()
return t_id[0][0]


def getPlayerId(p_sname, p_name):
"""Utility function to retrieve a player id using his first and last names
Args:
p_sname(str): the first name of the player
p_name(str): the last name of the player
Returns:
the unique id of a player from the players_c table (int).
.. note::
We take the first player we find in the db!!!"""

# get the player's id
conn = connect()
c = conn.cursor()
condition = "where p_sname={!r} and p_name={!r}".format(p_sname, p_name)
condition = "where p_sname=%s and p_name=%s"
query = "select id_player_c from players_c " + condition
c.execute(query)
c.execute(query, (p_sname, p_name))
p_id = c.fetchall()
conn.close()
return p_id[0][0]
Expand All @@ -157,18 +178,19 @@ def getPlayerId(p_sname, p_name):
def registerPlayerTournament(p_id, t_id):
"""Adds 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.)
The database assigns a unique serial id number for the player, tournament
pair. We use the player id from the players_c table and the tournament
id from the tournaments table.
Args:
f_name(str): the player's first name.
name(str): the player's name
p_id(int): the player's unique id from the players_c table.
t_id(int): the tournament's unique id from the tournaments table
"""
# register a player in a tournament
conn = connect()
c = conn.cursor()
query = """insert into players (id_player_c, tournament) values ({!r}, {!r})"""
c.execute(query.format(p_id, t_id))
query = """insert into players (id_player_c, tournament) values (%s, %s)"""
c.execute(query, (p_id, t_id))
conn.commit()
conn.close()

Expand All @@ -180,97 +202,55 @@ def playerStandings():
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
A list of tuples, each of which contains (id, p_sname, p_name, tournament
wins, matches, tournament_id):
id(int): the player's unique id (assigned by the database)
p_sname(str): the player's first name (as registered)
p_name(str): the player's last name (as registered)
wins(int): the number of matches the player has won
matches(int): the number of matches the player has played
"""

# First register a tournament and players
# get the tournament's id
conn = connect()
c = conn.cursor()
# my_players = [("Melpomene", "Murray"), ("Randy", "Schwartz")]
# insert_values = []
# p_ids = []
# for player in my_players:
# p_sname, p_name = player
# # registerPlayer(p_sname, p_name)

# # get the player's id
# condition = "where p_sname={!r} and p_name={!r}".format(p_sname, p_name)
# query = "select id_player_c from players_c " + condition
# c.execute(query)
# p_id = c.fetchall()
# print(p_id)
# p_ids.append(p_id[0][0])

# # build the insert values
# insert_values.append("({!r}, {!r})".format(p_id[0][0], t_id[0][0]))

# # join all the values
# ins = ",".join(insert_values)

# # register the players in the tournament
# query = "insert into players \
# (id_player_c, tournament) values {}".format(ins)
# c.execute(query)
# conn.commit()
# search for these players in the players_c table

# view = """DROP VIEW playstats;
# CREATE VIEW playstats AS
# SELECT id_player, p_sname, p_name, t_name, wins, matches
# FROM players, players_c, tournaments
# WHERE players.id_player_c = players_c.id_player_c
# AND tournaments.id_tournament = players.tournament;"""
# c.execute(view)
# conn.commit()
query = "select * from playstats;"
c.execute(query)
players_reg = c.fetchall()
conn.close()
return players_reg



def reportMatch(score_p1, score_p2, tournament, p1, p2):
"""
MODIFIED THE FUNCTION TO RECORD THE SCORE
Records the outcome of a single match between two players.
Args:
id_p1: the id number of the player 1
id_p2: the id number of the player 2
score_p1: the score of the player 1
score_p2: the score of the player 2
tournament: the id number of the tournament
id_p1(int): the id number of the player 1
id_p2(int): the id number of the player 2
score_p1(int): the score of the player 1
score_p2(int): the score of the player 2
tournament(int): the id number of the tournament
"""
conn = connect()
c = conn.cursor()
# build the inserts for the match
assert p1 != p2, "You have to use two different player ids!"
match_val = "({!r}, {!r}, {!r}, {!r}, {!r})".format(score_p1,
score_p2,
tournament,
p1,
p2)
match_val = "(%s, %s, %s, %s, %s)"
# add a new match between those 2 players
query = "insert into matches \
(score_p1, score_p2, tournament, id_p1, id_p2) values {}".format(match_val)
(score_p1, score_p2, tournament, id_p1, id_p2) values " + match_val

c.execute(query)
c.execute(query, (score_p1, score_p2, tournament, p1, p2))
conn.commit()

# update matches in the players table
# update matches variable in the players table

condition = "where id_player = {} or id_player = {};".format(p1, p2)
query = "update players set matches = matches + 1 {}"
c.execute(query.format(condition))
conn.commit()

# update wins in the player table
# update wins variable in the players table
if score_p1 > score_p2:
condition = "where id_player = {};".format(p1)
query = "update players set wins = wins + 1 {}"
Expand All @@ -281,27 +261,25 @@ def reportMatch(score_p1, score_p2, tournament, p1, p2):
query = "update players set wins = wins + 1 {}"
c.execute(query.format(condition))
conn.commit()
else:
condition = "where id_player = {};".format(p1)
query = "update players set wins = wins + 1 {}"

conn.close()


def swissPairings():
def swissPairingsPython():
"""Returns a list of pairs of players for the next round of a match.
USING PYTHON!
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
id1(int): the first player's unique id
p_sname1(str): the first player's first name
p_sname1(str): the first player's last name
id2(int): the second player's unique id
p_sname2(str): the second player's first name
p_sname1(str): the second player's last name
"""

conn = connect()
Expand All @@ -315,3 +293,30 @@ def swissPairings():
l_of_tup.append((p1[0], p1[1], p1[2],
p2[0], p2[1], p2[2]))
return l_of_tup


def swissPairingsSQL():
"""Returns a list of pairs of players for the next round of a match.
USING A VIEW IN THE DATABASE!
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(int): the first player's unique id
p_sname1(str): the first player's first name
p_sname1(str): the first player's last name
id2(int): the second player's unique id
p_sname2(str): the second player's first name
p_sname1(str): the second player's last name
"""

conn = connect()
c = conn.cursor()
query = "select * from pairing"
c.execute(query)
pairing = c.fetchall()
conn.close
return pairing
27 changes: 23 additions & 4 deletions vagrant/tournament/tournament.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ DROP TABLE IF EXISTS players CASCADE;
DROP TABLE IF EXISTS matches CASCADE;
DROP TABLE IF EXISTS rounds CASCADE;
DROP VIEW IF EXISTS playstats;
DROP VIEW IF EXISTS pairing;

-- We create the tournaments table to store all the informations about
-- a given tournaments.
Expand Down Expand Up @@ -107,17 +108,35 @@ CREATE TABLE matches ( id_match SERIAL,
players(id_player, tournament),
FOREIGN KEY (id_p2, tournament) REFERENCES
players(id_player, tournament),
-- FOREIGN KEY (round, tournament) REFERENCES
-- rounds(id_round, tournament),
-- PRIMARY KEY (id_match, round, tournament, id_p1, id_p2));
PRIMARY KEY (id_match, tournament, id_p1, id_p2));


-- A view to retrieve players characteristics, names and tournaments infos

CREATE VIEW playstats AS
SELECT id_player, p_sname, p_name, t_name, wins, matches
SELECT id_player, p_sname, p_name, t_name, wins, matches, tournament
FROM players, players_c, tournaments
WHERE players.id_player_c = players_c.id_player_c
AND tournaments.id_tournament = players.tournament
ORDER BY wins DESC;


-- A view to add the ranking of each player

CREATE VIEW interrank AS
SELECT id_player, p_sname, p_name, wins, matches, tournament, t_name,
int4(row_number() over(order by wins)) as r1
from playstats
order by wins DESC;


-- A view to build pairs of adjacent players in terms of ranking

CREATE VIEW pairing AS
SELECT ir1.id_player as id1, ir1.p_sname as p1_sname, ir1.p_name as p1_name,
ir2.id_player as idp2, ir2.p_sname as p2_sname, ir2.p_name as p2_name
FROM interrank as ir1, interrank as ir2
WHERE ir1.tournament = ir2.tournament
AND ir1.matches = ir2.matches
AND ir1.r1=(ir2.r1-1)
AND ir2.r1%2=0;
Loading

0 comments on commit b62bb10

Please sign in to comment.