Instructions
Requirements and Specifications
- Display lineup
- Add player
- Remove player
- Move player
- Edit player position
- Edit player stats
- Exit program
- Use a Player class that provides attributes that store the first name, last name, position, at bats, and hits for a player. The class constructor should use these five attributes as parameters. This class should also provide a method that returns the full name of a player and a method that returns the batting average for a player.
- Use a Lineup class to store the lineup for the team as a private list attribute. This class will include the following methods to modify the private list attribute: add player, remove player, get player, and move player, with appropriate parameters. The add method will add a new player to the end of the list. The remove and get methods require the lineup location of the targeted player and both methods will return the player object at the specified location; the only difference is that the get method will not delete the object from the list attribute. In addition, it must include an iterator so that the lineup object can be used in a for loop.
- Use a file named objects to store the code for the Player and Lineup classes.
- Use a file named ui to store the code for the user interface. This is the existing code from the main module in projects #1 and #2. Rename the existing module and refactor the code to use a Lineup object instead of a list of dictionaries (project #2) or a list of lists (project #1). Modify the code to separately ask the user for both the first name and last so that the two inputs can be used when creating a player object.
- Use a file named db to store the two functions that read from and write to the file that stores the data. These functions should use the same names used in the previous project. The function that reads the file does not use a parameter and returns a lineup object which holds the player objects that are created when the data is read from the given players.txt file. A lineup object is used as the parameter for the function that writes the data to the file.
- Correct errors from the 2nd project before turning in the 3rd project.
Source Code
DB
#Casey Barton
#Project 3 - Baseball Managment Application
#April 2 2022
#Baseball manager application for editing and changing lineups, stats and player positions reading from and writingto csv with dictionary format
# db
from objects import *
def readCsv(): #read csv function
# First, create a Lineup object
lineup = Lineup()
for line in open("players.csv"): #iterate through players csv
row = line.split(",") #create list from csv
name = row[0].split(' ')
# Divide name into first and last name
first_name = name[0]
last_name = name[1]
pos = row[1]
ab = int(row[2])
hits = int(row[3])
# Create player object
player = Player(first_name, last_name, pos, ab, hits)
# Add to lineup
lineup.addPlayer(player)
# Return
return lineup
def writeToCSV(lineup: Lineup): #write csv function
"""
Writes a CSV file containing the info about all players in the lineup
:param lineup: Lineup object
:return: None
"""
filename = open("players.csv","w") #open csv
# Loop through players
for player in lineup:
row = "{0},{1},{2},{3}\n".format(player.name(), player.pos, player.ab, player.hits)
filename.write(row) #write file to csv
filename.close() #close file
OBJECTS
class Player:
# Constructor
def __init__(self, first_name: str, last_name: str, pos: str, ab: int, hits: int):
self.first_name = first_name
self.last_name = last_name
self.pos = pos
self.ab = ab
self.hits = hits
def average(self) -> float:
"""
Returns the player's average
:return: player's average (float)
"""
return self.hits/self.ab
def name(self) -> str:
"""
Return player's full name
:return: player's full name (str)
"""
return self.first_name + " " + self.last_name
class Lineup:
# Constructor
def __init__(self):
# Define the attribute team as private
self.__team = list()
# The following variable is used for the iterator
self.__index = 0
def addPlayer(self, player: Player):
# add player
self.__team.append(player)
def removePlayer(self, lineup: int):
# Search for a player with that lineup and remove
if 0 <= lineup < len(self.__team):
return self.__team.pop(lineup)
return None
def getPlayer(self, lineup: int):
# Search for a player with that name and remove
if 0 <= lineup < len(self.__team):
return self.__team[lineup]
return None
def movePlayer(self, oldLineup: int, newLineup: int):
if 0 <= oldLineup < len(self.__team) and 0 <= newLineup < len(self.__team):
deleted = self.removePlayer(oldLineup)
self.__team.insert(newLineup, deleted)
return True
return False
def editPlayerPosition(self, lineup: int, newPos: str):
self.__team[lineup].pos = newPos
def editPlayerStat(self, lineup: int, stat: str, newStat):
stat = stat.lower()
if stat == 'first name':
self.__team[lineup].first_name = newStat
elif stat == 'last name':
self.__team[lineup].last_name = newStat
elif stat == 'ab':
self.__team[lineup].ab = int(newStat)
elif stat == 'pos':
self.__team[lineup].pos = newStat
elif stat == 'hits':
self.__team[lineup].hits = int(newStat)
def __iter__(self):
self.index = 0
return self
def __next__(self):
if self.index < len(self.__team):
self.index += 1
return self.__team[self.index - 1]
else:
raise StopIteration
UI
# Casey Barton
# Project 2 - Baseball Managment Application
# April 2 2022
# Baseball manager application for editing and changing lineups, stats and player positions reading from and writingto csv with dictionary format
# main file
from datetime import datetime, date # inport date and time functions
from objects import *
from db import *
def displayLineup(lineup: Lineup): # display lineup function
#print("\tPlayer\t\t\t\tPOS\tAB\tH\t\tAVG") # header for stat layout
print("{:<10s} {:<30s} {:<10s} {:<10s} {:<10s} {:<15s}".format("Lineup", "Name", "POS", "AB", "H", "AVG"))
print("{:<10s} {:<30s} {:<10s} {:<10s} {:<10s} {:<15s}".format("------", "----", "---", "--", "-", "---"))
for i, player in enumerate(lineup): # iterate through disctionary
#print(str(i + 1) + "\t" + player.name() + "\t" + player.pos + "\t" + str(
# player.ab) + "\t" + str(player.hits) + "\t" + str(player.average())) # show stats for each player
print("{:<10d} {:<30s} {:<10s} {:<10d} {:<10d} {:<15.2f}".format(i+1, player.name(), player.pos, player.ab, player.hits, player.average()))
def addPlayer(lineup: Lineup): # add player function
first_name = input("First name: ") # enter player name
last_name = input("Last name: ") # last name
position = input("Position, in caps: ") # enter player position
at_bats = int(input("At Bats: ")) # enter number of at bats
hits = int(input("Hits: ")) # enter number of hits
# Create player object
player = Player(first_name, last_name, position, at_bats, hits)
lineup.addPlayer(player)
writeToCSV(lineup) # write csv function
def removePlayer(lineup: Lineup): # remove player function
name = input("Enter the name of player to be removed: ") # select palyer to delete
for i, player in enumerate(lineup): # iterate through dictionary
if player.name() == name: # search for player
lineup.removePlayer(i)
writeToCSV(lineup) # write file to csv
break # break loop
def movePlayer(lineup: Lineup): # move player to new lineup number function
name = input("Enter the name of player to be moved: ") # select lineup number for player to be moved
newOrder = int(input("Enter a new lineup number: ")) # enter new linup number
for i, player in enumerate(lineup): # iterate through lineup
if player.name() == name: # search for player
lineup.movePlayer(i, newOrder-1)
writeToCSV(lineup) # write csv file
break # break loop
def editPlayerPosition(lineup: Lineup): # edit player position function
name = input("Enter the name of player to edit: ") # select player to edit
pos = input("Enter a new Position, in caps: ") # enter new player position
for i, player in enumerate(lineup): # iterate through distionary
if player.name() == name: # search for player name
lineup.editPlayerPosition(i, pos)
writeToCSV(lineup) # write to file
break # break loop
def editPlayerStats(lineup: Lineup): # edit player stats function
name = input("Enter the name of player to edit: ") # select player to edit stats
stat = input("Enter stat to be edit: ") # prompt for stat type
newStat = input("Enter value for " + stat + ": ") # prompt for stat
for i, player in enumerate(lineup): # iterate through lineup
if player.name() == name: # search for player
lineup.editPlayerStat(i, stat, newStat)
#players[i][stat] = newStat # enter new stat into dictionary
writeToCSV(lineup) # write to file
break # Break the loop
def menu():
"""
This function displays the menu
:return: None
"""
print("MENU OPTIONS") # display menu
print("1 – Display lineup")
print("2 – Add player")
print("3 – Remove player")
print("4 – Move player")
print("5 – Edit player position")
print("6 – Edit player stats")
print("7 - Exit program")
def main(): # main function
# Read csv
lineup = readCsv()
todaysDate = date.today() # set date
print("CURRENT DATE : ", todaysDate) # show date
gameDay = input("GAME DATE : ") # prompt for game day
if (gameDay != "" or len(gameDay) != 0): # check for a date to start counter
dateOfGame = datetime.strptime(gameDay, '%Y-%m-%d') # set game date
countdown = dateOfGame - datetime(todaysDate.year, todaysDate.month, todaysDate.day) # calculate countdown
print("DAYS LEFT UNTIL GAME: ", countdown.days) # show days left
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print("\t\t\t\tBaseball Team Management Program") # program name
menu()
#print("POSITIONS")
menuSelection = input("Enter Menu Option: ") # prompt for menu selection
while menuSelection <= "7": # menu loop
# Display menu
if menuSelection == "1": # first menu selection
displayLineup(lineup) # run displayLineup function with list parameter
elif menuSelection == "2": # second menu selection
addPlayer(lineup) # run addPlayer function with list parameter
elif menuSelection == "3": # third menu selection
removePlayer(lineup) # run removePlayer function with list parameter
elif menuSelection == "4": # fourth menu selection
movePlayer(lineup) # run movePlayer function with list parameter
elif menuSelection == "5": # fifth menu selection
editPlayerPosition(lineup) # run editPlayerPosition function with list parameter
elif menuSelection == "6": # sixth menu selection
editPlayerStats(lineup) # run editPlayerStats function with list parameter
elif menuSelection == "7": # seventh menu selection
print("Goodbye!") # leave program message
writeToCSV(lineup)
break # exit program loop
print()
menu()
menuSelection = input("Enter Menu Option: ") # re-enter loop
print()
if __name__ == '__main__':
main()