Skip to content

Commit

Permalink
completed essential coding, added some extra credit from udacity#1
Browse files Browse the repository at this point in the history
  • Loading branch information
DeannaWagner committed Oct 18, 2015
1 parent ebcbda6 commit 379ab19
Show file tree
Hide file tree
Showing 4 changed files with 192 additions and 13 deletions.
47 changes: 47 additions & 0 deletions vagrant/tournament/extra_credit_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python
#
# Test cases for tournament.py


from tournament import *
import math


def testRematches():
deleteMatches()
deletePlayers()
#change player count to anything greater than 4, tested up to 64 players
playerCount = 16
i = 0
while i < playerCount:
registerPlayer("P%d" % i)
i += 1
tour_round = 1
rounds = math.log(playerCount, 2)
print "Rounds=%d" % rounds
while tour_round <= rounds:
pairings = swissPairings()
i = 0
print "Pairings:"
print pairings
while i < len(pairings):
reportMatch(pairings[i][0], pairings[i][2])
players_matched = matchCount(pairings[i][0], pairings[i][2])
print players_matched
i += 1
tour_round += 1
print "Standings:"
print playerStandings()
if False:
raise ValueError(
"Players should only meet in one match.")
print """1. After one match, players with one win are paired, avoiding.
rematches between players!"""
# db.close()


if __name__ == '__main__':
testRematches()
print "Success! Tests for extra credit pass!"


120 changes: 116 additions & 4 deletions vagrant/tournament/tournament.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
#!/usr/bin/env python
# !/usr/bin/env python
# Tournament Project 2 is copyright 2015 Deanna M. Wagner.
# tournament.py is an implementation of a Swiss-system tournament.
#
# tournament.py -- implementation of a Swiss-system tournament
#


import psycopg2
import bleach


def connect():
Expand All @@ -13,14 +16,30 @@ def connect():

def deleteMatches():
"""Remove all the match records from the database."""
db = connect()
cursor = db.cursor()
cursor.execute("DELETE FROM matches;")
db.commit()
db.close()


def deletePlayers():
"""Remove all the player records from the database."""
db = connect()
cursor = db.cursor()
cursor.execute("DELETE FROM players;")
db.commit()
db.close()


def countPlayers():
"""Returns the number of players currently registered."""
db = connect()
cursor = db.cursor()
cursor.execute("SELECT count(*) FROM players;")
sum_player = cursor.fetchone()
db.close()
return sum_player[0]


def registerPlayer(name):
Expand All @@ -32,6 +51,12 @@ def registerPlayer(name):
Args:
name: the player's full name (need not be unique).
"""
db = connect()
cursor = db.cursor()
bleach.clean(name)
cursor.execute("INSERT INTO players (name) VALUES (%s);", (name, ) )
db.commit()
db.close()


def playerStandings():
Expand All @@ -47,6 +72,25 @@ def playerStandings():
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
db = connect()
cursor = db.cursor()
cursor.execute("""
SELECT players.id,
players.name,
(SELECT count(*)
FROM matches
WHERE players.id = matches.winner_id)
AS wins,
(SELECT count(*)
FROM matches
WHERE players.id = matches.winner_id
OR players.id = matches.loser_id)
AS matches_played
FROM players
ORDER BY wins DESC;""")
standings = cursor.fetchall()
db.close()
return standings


def reportMatch(winner, loser):
Expand All @@ -56,7 +100,38 @@ def reportMatch(winner, loser):
winner: the id number of the player who won
loser: the id number of the player who lost
"""
db = connect()
cursor = db.cursor()
cursor.execute("""
INSERT INTO matches (winner_id, loser_id)
VALUES ( %s, %s );""", (winner, loser) )
db.commit()
db.close()


def matchCount(player1, player2):
"""Counts time players have had matches in a given tournament.
Args:
player1: id of first player
player2: id of second player
Returns:
Integer indicating the number of matches the players have played
together
"""
db = connect()
cursor = db.cursor()
cursor.execute("""
SELECT count(*) AS numMatches
FROM matches
WHERE (%s = matches.winner_id OR %s = matches.loser_id)
AND (%s = matches.winner_id OR %s = matches.loser_id)""", \
(player1, player1, player2, player2))
numMatches = cursor.fetchone()
db.close()
return numMatches[0]


def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Expand All @@ -73,5 +148,42 @@ def swissPairings():
id2: the second player's unique id
name2: the second player's name
"""


standings = playerStandings() #(id, name, wins, matches)
pairings = []
p_id = 0 #first item in tuple
name = 1 #second item in tuple
i = 0
while i < len(standings) - 1:
if matchCount(standings[i][p_id], standings[i+1][p_id]) > 0:
if i == len(standings) - 2:
print "We hit rematch with last pair"
pairings.append((standings[i][p_id], \
standings[i][name], \
standings[i-2][p_id], \
standings[i-2][name]))
pairings.append((standings[i+1][p_id], \
standings[i+1][name], \
standings[i-1][p_id], \
standings[i-1][name]))
else:
print "We hit rematch"
pairings.append((standings[i][p_id], \
standings[i][name], \
standings[i+2][p_id], \
standings[i+2][name]))
pairings.append((standings[i+1][p_id], \
standings[i+1][name], \
standings[i+3][p_id], \
standings[i+3][name]))
print standings[i][name]
print standings[i+2][name]
print standings[i+1][name]
print standings[i+3][name]

else:
pairings.append((standings[i][p_id], \
standings[i][name], \
standings[i+1][p_id], \
standings[i+1][name]))
i += 2
return pairings
36 changes: 29 additions & 7 deletions vagrant/tournament/tournament.sql
Original file line number Diff line number Diff line change
@@ -1,9 +1,31 @@
-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes, like
-- these lines here.
/* Tournament Project 2 is copyright 2015 Deanna M. Wagner.
* DATABASE definition for the tournament project is found in tournament.sql file.
* SQL 'CREATE TABLE' statements are in this file.
*/


DROP DATABASE IF EXISTS tournament;
CREATE database tournament;

\c tournament;

CREATE TABLE players (
id serial PRIMARY KEY NOT NULL,
name varchar(80) NOT NULL );

CREATE TABLE matches (
match_id serial PRIMARY KEY NOT NULL,
winner_id integer REFERENCES players(id),
loser_id integer REFERENCES players(id) );

CREATE TABLE tournaments (
tour_id serial PRIMARY KEY NOT NULL,
tour_name varchar(80) NOT NULL );

CREATE TABLE tournaments_players (
tournament_id integer REFERENCES tournaments(tour_id),
player_id integer REFERENCES players(id) );

--Create View standings query

\q
2 changes: 0 additions & 2 deletions vagrant/tournament/tournament_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,3 @@ def testPairings():
testReportMatches()
testPairings()
print "Success! All tests pass!"


0 comments on commit 379ab19

Please sign in to comment.