Chess grade database controller – Second edit

Language: Python

Task:

This modification has added a second class allowing fixtures to be called and returned as a tuple. The interface will then be able to use this function to call up team names, dates etc in order to show them on the screen. Fixtures and Players class are now daughter classes of Admin so that the methods of Admin can be used in these classes. Reading the previous version of this program explains it in more depth.

Efficiency and improvement

The areas I would look to improve and expand are:

  1. A way to take incorrectly entered answers (e.g. using try and except)
  2. Adding new daughter classes to include view statistics of particular teams
  3. Adding an email method that allows the Admin to create an email
  4. Convert to Java
  5. Use variables that are inputted to methods/classes rather than collecting details through questions. This will allow the details to be collected by other classes that interact with the user by different means (e.g. buttons on a website or GUI)
def create_player_database():

import csv

with open('playersdatabase.csv','w',newline='') as database:
fieldnames = ['username', 'password', "permission", "grade", "name","email"]
writer = csv.DictWriter(database, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'username': 'Hywel862',
'password': 'secret',
'permission': 'captain',
'grade': '1816',
'name': 'Hywel Griffiths',
'email': 'Hywel862@aol.com'})
writer.writerow({'username': 'Sipho',
'password': 'anon',
'permission': 'admin',
'grade': '1576',
'name': 'Sipho Donovan',
'email':'sipho@gmail.com'})
writer.writerow({'username': 'Travis',
'password': 'hello',
'permission': 'none',
'grade': '850',
'name': "Travis O'Sullivan",
'email':'travis@yahoo.co.uk'})

def create_fixture_database():

import datetime
import csv

with open('fixturesdatabase.csv','w',newline='') as database:
fieldnames = ['home_team','away_team','date','KO/league','complete']
writer = csv.DictWriter(database,fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'home_team':'Emperors',
'away_team':'Morriston A',
'date':"13/05/2019",
'KO/league':'KO',
'complete':False})
writer.writerow({'home_team':'University A',
'away_team':'Nidum A',
'date':"30/06/2019",
'KO/league':'league',
'complete':False})
writer.writerow({'home_team':'Tribunes',
'away_team':'University B',
'date':"05/04/2019",
'KO/league':'league',
'complete':True})
writer.writerow({'home_team':'Emperors',
'away_team':'University A',
'date':"15/04/2019",
'KO/league':'league',
'complete':True})
writer.writerow({'home_team':'White Knights A',
'away_team':'Tribunes',
'date':"10/04/2019",
'KO/league':'league',
'complete':True})

def create_results_database():

#Not actual fields in resultsdatabase

import csv

with open('resultsdatabase.csv','w',newline='') as database:
fieldnames = ['result']
writer = csv.DictWriter(database,fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'result':'win'})

class Admin:

'''This Class allows administration to interact with the various databases, viewing and editing them'''

def __init__(self):
pass

def view(self, database="all"):

#Function to view the details of databases. !!!NB This will be edited to view specific entries into a database
#provided by the daughter classes fixture and stats

#Uses database_view to show the details of the requested database. 'all' shows them all whilst giving a specific
#name of a database shows that database. !!!NB This will be handed a specific element to view from other
#daughter classes.
if database=="all":
self.database_view("fixturesdatabase")
self.database_view("playersdatabase")
self.database_view("resultsdatabase")
else:
self.database_view(database)

def create_key_list(self,database):

if database =="all":
return
#Creates a list of the elements. This code is a separate function in order to avoid repeating code for two of
#the other functions
if database=="fixturesdatabase":
key_list = ["home_team","away_team","date","KO/league","complete"]
if database=="playersdatabase":
key_list = ["username","password","permission","grade","name","email"]
if database=="resultsdatabase":
key_list = ["result"]
return key_list

def database_view(self,database):

#Calls the various lines of the database to view them. !!NB This will be altered to read specific details if
#called by the daughter classes
import csv
#create list of keys
key_list = self.create_key_list(database)
#create database name for csv writer
database_name = database+".csv"
#print all the database lines
with open(database_name, 'r') as reader:
reader = csv.DictReader(reader)
for line in reader:
for i in key_list:
print (i,line[i],end=" ")
print("")

def add_entry(self,database,x = "manual"):

#Adds an entry to fixtures, results or players. This can be manual (if no third argument is sent) or
#automatically from the matchcard class is a third argument is provided
import csv
#Creates the appropriate list of keywords to go through depending on the database
key_list = self.create_key_list(database)
#No third argument has been given so function collects the various required entries
if x == "manual":
details_list=[]
for i in key_list:
answer = input ("What is the"+i+"?")
details_list.append(answer)
#If a third argument has been provided (a list of the details of a result) it uses this as the required
# details_list
else:
details_list=[x]
#Creates the required database name to be working with
database_name = database+".csv"
#Appends the details given
with open (database_name,'a') as appender:
writer = csv.writer(appender)
writer.writerow([])
writer.writerow (details_list)

def delete_or_edit(self,function, database):

#This method allows specific rows to be deleted from the database by creating a temp dictionary and writing over
#it
import csv
#Create the key list
key_list = self.create_key_list(database)
#Show the numbered entries in the database
self.create_numbered_database(key_list,database)
#Create the database name
database_name = database+".csv"
#Create a temporary file according to the function required (deleting or editing a line)
self.create_temp(function, database_name, key_list)
#Open the temp csv file to open and write over the old file
with open(database_name,'w',newline='') as writer_database:
writer = csv.DictWriter(writer_database,fieldnames=key_list)
writer.writeheader()
with open('temp.csv','r') as reader:
reader = csv.DictReader(reader)
for row in reader:
temp_dict=dict(row)
writer.writerow(temp_dict)

def create_numbered_database(self,key_list,database):

import csv

#Show the database with entries
database_name = database+".csv"
with open(database_name, 'r') as reader:
reader = csv.DictReader(reader)
n=1
for line in reader:
for i in key_list:
print (n,i,line[i],end=" ")
print("")
n+=1

def create_temp(self,function, database_name, key_list):

import csv

#Get the number that the admin wishes to delete
answer = int(input ("Which entry would you like to" + function + "?"))
#Opens the database being edited and make a copy of the line
with open('temp.csv','w', newline='') as writer_database:
writer=csv.DictWriter(writer_database,fieldnames=key_list)
writer.writeheader()
with open(database_name, 'r') as reader:
reader = csv.DictReader(reader)
n=1
for row in reader:
#If it is the row chosen and we are deleting it jump the row
if n!=answer:
temp_dict = dict(row)
writer.writerow(temp_dict)
if n==answer and function=="edit":
key_to_edit = input ("Which category would you like to edit?")
new_value = input ("What is the new value?")
temp_dict = dict(row)
temp_dict[key_to_edit]=new_value
writer.writerow(temp_dict)
#Otherwise write it into the temporary csv file
n+=1

class Player(Admin):

def __init__(self):
pass

'''Player class allows information to be extracted from player files'''

def username_compare(self, username, password):

import csv

"""method usernameCompare compares username to password to return a boolean. False if the username or
password is incorrect and true if they match"""

with open("playersdatabase.csv", "r") as database:
reader = csv.DictReader(database)
for row in reader:
if row['username'] == username:
if row['password'] == password:
# These print statements will be removed in the actual code
print("Username and password match.")
return True
elif row['password'] != password:
print("Incorrect password")
return False
print("No such username")
return False

def permission_check(self, username, request):

import csv

"""method to returning a boolean if the requested permission (captain or admin) matches their status"""

with open("playersdatabase.csv", "r") as database:
reader = csv.DictReader(database)
for row in reader:
if row['username'] == username:
if row['permission'] == request:
# Two print statements will be removed in actual code
print("You have permission to this status")
return True
print("You do not have permission to this status")
return False
print("No such username")
return False

def call(self, username, characteristic):

import csv

"""method calls any characteristic required"""

with open("playersdatabase.csv", "r") as database:
reader = csv.DictReader(database)
for row in reader:
if row['username'] == username:
return row[characteristic]
return "No such username"

class Fixture(Admin):

def __init__ (self):
pass

def fixture_tuple_creator(self,factor_to_test, team_name="NA",date="01/09/2019"):

#Creates the required dates for the test

import datetime
import csv
from datetime import timedelta
#Change string of date into datetime format
date = datetime.datetime.strptime(date, "%d/%m/%Y")
#Create a starting date to look from (7 days before the date given if date is the required defining factor,
#start of the season if the home team is the defining factor
if factor_to_test == "date" or factor_to_test == "both":
start_date = date - timedelta(days=7)
else:
start_date = date
fixtures_tuple = ()
#look through database for for rows that meet the criteria and add them to the list of dictionaries within
#fixtures_tuple
with open('fixturesdatabase.csv', 'r') as reader:
reader = csv.DictReader(reader)
#Have the program go through all dates (304 days) if teams are being checked, 15 if dates are being checked
if factor_to_test=="home_team":
end_point = 304
else:
end_point = 15
for row in reader:
for i in range (0,end_point):
row_date = datetime.datetime.strptime(row["date"], "%d/%m/%Y")
row_team = row['home_team']
#Add the current i value to the date to move to the next day (NB for the first loop i is 0)
next_day = start_date + timedelta(days=i)
#Test to see if defining factors meet and correct factor is being tested to add them to
# fixtures_tuple
if row_date==next_day and factor_to_test=="date" or row_team==team_name and \
factor_to_test=="home_team" or row_date==next_day and row_team==team_name and \
factor_to_test=="both":
new_tuple = (dict(row),)
fixtures_tuple = fixtures_tuple + new_tuple
print (fixtures_tuple)
return fixtures_tuple

create_fixture_database()
create_player_database()
create_results_database()

def fixtures():
fixtures_list = Fixture()
factor_to_test = input ("What would you like to find the fixtures for? A home_team, date or both?")
if factor_to_test =="date":
answer = input ("Give me a date in the format dd/mm/yyyy.")
fixtures_list.fixture_tuple_creator(factor_to_test, date=answer,)
if factor_to_test =="home_team":
answer = input ("Give me the name of the home team.")
fixtures_list.fixture_tuple_creator(factor_to_test, team_name=answer)
if factor_to_test == "both":
answer_one = input ("Give me a date in the format dd/mm/yyyy.")
answer_two = input ("Give me the name of the home team.")
fixtures_list.fixture_tuple_creator(answer_two,answer_one,factor_to_test)

def databases():

while True:
username=input("Please enter your username")
password=input("Please enter your password")
if Player.username_compare(Admin,username,password)==True and \
Player.permission_check(Admin,username,'admin')==True:
break
return
class_type = Admin()
while True:
answer = input ("What would you like to do? View (v), add (a), delete (d), edit (e) or finish (f)")
if answer == "v":
database = input ("Which database would you like to see? playersdatabase, fixturesdatabase, "
"resultsdatabase or all")
print (class_type.view(database))
if answer == "a":
database = input ("Which database would you like to add to? playersdatabase, fixturesdatabase or "
"resultsdatabase?")
class_type.add_entry(database)
if answer == "d":
database = input ("Which database would you like to delete from? playersdatabase, fixturesdatabase or "
"resultsdatabase?")
class_type.delete_or_edit("delete", database)
if answer == "e":
database = input("Which database would you like to edit? playersdatabase, fixturesdatabase or resultsdatabase?")
class_type.delete_or_edit("edit", database)
if answer == "f":
break

while True:

answer = input("Would you like to see (1) fixtures (2) change/edit databases or (3) end?")
if answer == "1":
fixtures()
if answer=="2":
databases()
if answer =="3":
break