+1 (315) 557-6473 

Python Program to Create Team Management System Assignment Solution.


Instructions

Objective
To complete your Python homework, you have been assigned the task of developing a program to create a team management system using Python language. This system will enable users to efficiently manage teams, their members, and various related tasks. By implementing this project, you will not only gain a better understanding of Python programming but also learn about data structures, file handling, and user input processing. Utilize the knowledge you've acquired from previous lessons and feel free to explore additional Python libraries if needed.

Requirements and Specifications

Team Management Program: Part 3
Convert the previous Baseball Team Manager program from procedural to object-oriented. This version will still have the same functionality from the second project, but it will make the code more modular, reusable, and easier to maintain.
Sample Console Output
================================================================
                                                   Baseball Team Manager
CURRENT DATE: 2020-09-12
GAME DATE: 2020-09-19
DAYS UNTIL GAME: 7
MENU OPTIONS
  1. Display lineup
  2. Add player
  3. Remove player
  4. Move player
  5. Edit player position
  6. Edit player stats
  7. Exit program
POSITIONS
C, 1B, 2B, 3B, SS, LF, CF, RF, P
============================================================
Menu option: 1
   Player                               POS                 AB                      H                   AVG
---------------------------------------------------------------------------------------------------
1 Dominick Gilbert              1B                  545                  174                 0.319
2 Craig Mitchell                    CF                 533                  127                 0.238
3 Jack Quinn                         RF                 535                  176                 0.329
4 Simon Harris                      C                   485                  174                 0.359
5 Darryl Moss                       3B                  532                  125                 0.235
6 Grady Guzman                  SS                  477                  122                 0.256
7 Wallace Cruz                      LF                  475                  138                 0.291
8 Cedric Cooper                   2B                  215                   58                   0.270
9 Alberto Gomez                  P                    103                   21                   0.204
Menu option:
Specifications
  • 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()