0

Recently I've started learning Python and I'm trying to create a basic game to practice several topics. Basically, I'm trying to create a baseball batting simulator based on batting average (accuracy) and the import random module.

I want the user to be able to choose a batter when the game loads up. This batter would be an object with two attributes: name and accuracy.

For example:

    class Batter:
    def __init__(self,name,accuracy):
        self.name = name
        self.accuracy = accuracy

p1 = Batter("Bob",303)
p2 = Batter("Mike",373)

I know I can input this all manually, but say I have a csv file called 'data.csv' with hundreds of batter names and accuracy values. In the form of:

Batter, At-Bats, Batting Average
Bob, 300, 303
Mike 274, 373
Nick, 313, 234
Joe,233, 280.....

The idea would be to pull the first and third columns of the csv. It has been driving me nuts because I can't figure out a way to automate this process and be able to pull data from the csv into individual object classes.

My goal was to have everything loaded in from the csv, and when the game would start out it would ask the user: "Please choose a player:". If the user inputs "Joe" it would pull his attributes and set the accuracy to his value of 280 and use the following command to determine whether he hits the ball or not. Imagine Joe was loaded in with the variable "p4"

    import random
    acc = p4.accuracy
    n = p4.name
    number = random.randint(1,1000) 

    if number <= acc:
        print("%s hit the ball!" % n)
    else:
        print("%s did not hit the ball!" % n)

Just struggling with the automation process of object creation from csv data is all. Any help would be appreciated!

  • Where are you having trouble exactly? How have you tried to read the csv? – Burrito Apr 04 '20 at 20:01
  • The trouble I'm having is how to create a loop to retrieve data from the csv, and create individual objects for each "Batter". My idea was to have a list of objects in the form of p1,p2,p3,p4,.... Unless there is a better way to go about it. – starkpl9 Apr 04 '20 at 20:04
  • Could you share the code where you're trying to get the data from the csv? – Burrito Apr 04 '20 at 20:06
  • So I know I can extract it with the pandas module. Here I have the individual columns in W and Z. I'm sure there's a way to combine it into a 2 column array. Just not certain how to run the loop for object creation from this. import pandas as pd stats = pd.read_csv('data.csv') W = data.Batter Z = data.BattingAverage – starkpl9 Apr 04 '20 at 21:13
  • Maybe this is what you're looking for: https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary (dictionary would be a good choice so you can do a lookup by name) – Burrito Apr 04 '20 at 21:29
  • Thanks! This is what I needed! – starkpl9 Apr 05 '20 at 22:52

0 Answers0