简体   繁体   中英

I have this python trivia game that asks what type of trivia you want at the start, but if you want to play again it doesn't ask the question again

At the start it asks if you want NBA, MLB, or NFL trivia. Once it's done with the trivia, it asks if you want to play again, and if yes it gives the same type of trivia as before. For example if you say NBA at the start, and then play again, it gives the NBA questions again. I want it to ask what type of trivia you want again, if you want to play again. Here's the full code

#-------------------------------
print("Sports Trivia Game")
#-------------------------------
game_mode = input("Enter Game Mode - NBA | MLB | NFL: ")
game_mode = game_mode.upper()
#-------------------------------
if game_mode=="NBA":
  def new_game():

    guesses = []
    correct_guesses = 0
    question_num = 1
    
    for key in nba_questions:
      print("-------------------------------------------------")
      print(key)
      for i in nba_options[question_num-1]:
        print(i)
      guess = input("Enter (A, B, C, or D): ")
      guess = guess.upper()
      guesses.append(guess)
      
      correct_guesses += check_answer(nba_questions.get(key), guess)
      question_num += 1
      
    display_score(correct_guesses, guesses)
#-------------------------
  def check_answer(answer, guess):
    if answer == guess:
      print("CORRECT!")
      return 1
    else:
      print("INCORRECT!")
      return 0
#-------------------------------
  def display_score(correct_quesses, guesses):
    print("-------------------------------------------------")
    print("RESULTS:")
    print("-------------------------------------------------")

    print("Answers: ")
    for i in nba_questions:
      print(nba_questions.get(i))
    print("")

    print("Guesses: ")
    for i in guesses:
      print(i)
    print("")

    score = int((correct_quesses/len(nba_questions))*100)
    print("Your score is: "+str(score)+"%")
    
#-------------------------------

elif game_mode=="MLB":
  def new_game():

    guesses = []
    correct_guesses = 0
    question_num = 1
    
    for key in mlb_questions:
      print("-------------------------------------------------")
      print(key)
      for i in mlb_options[question_num-1]:
        print(i)
      guess = input("Enter (A, B, C, or D): ")
      guess = guess.upper()
      guesses.append(guess)
      
      correct_guesses += check_answer(mlb_questions.get(key), guess)
      question_num += 1
      
    display_score(correct_guesses, guesses)
#-------------------------
  def check_answer(answer, guess):
    if answer == guess:
      print("CORRECT!")
      return 1
    else:
      print("INCORRECT!")
      return 0
#-------------------------------
  def display_score(correct_quesses, guesses):
    print("-------------------------------------------------")
    print("RESULTS:")
    print("-------------------------------------------------")

    print("Answers: ")
    for i in mlb_questions:
      print(mlb_questions.get(i))
    print("")

    print("Guesses: ")
    for i in guesses:
      print(i)
    print("")

    score = int((correct_quesses/len(mlb_questions))*100)
    print("Your score is: "+str(score)+"%")

#-------------------------------

elif game_mode=="NFL":
  def new_game():

    guesses = []
    correct_guesses = 0
    question_num = 1
    
    for key in nfl_questions:
      print("-------------------------------------------------")
      print(key)
      for i in nfl_options[question_num-1]:
        print(i)
      guess = input("Enter (A, B, C, or D): ")
      guess = guess.upper()
      guesses.append(guess)
      
      correct_guesses += check_answer(nfl_questions.get(key), guess)
      question_num += 1
      
    display_score(correct_guesses, guesses)
#-------------------------
  def check_answer(answer, guess):
    if answer == guess:
      print("CORRECT!")
      return 1
    else:
      print("INCORRECT!")
      return 0
#-------------------------------
  def display_score(correct_quesses, guesses):
    print("-------------------------------------------------")
    print("RESULTS:")
    print("-------------------------------------------------")

    print("Answers: ")
    for i in nfl_questions:
      print(nfl_questions.get(i))
    print("")

    print("Guesses: ")
    for i in guesses:
      print(i)
    print("")

    score = int((correct_quesses/len(nfl_questions))*100)
    print("Your score is: "+str(score)+"%")

#-------------------------------
def play_again():
    
    response = input("Do you want to play again? (Yes or No): ")
    response = response.upper()
    
    if response == "YES":
      return True
    else:
      return False
      
#-------------------------------
nba_questions = {
  "What player has made the most 3 pointers in their career?: ": "C",
  "What player scored the most points in one game?: ": "B",
  "What player has the highest career points per game?: ": "A",
  "Who is the shortest NBA player of all time?: ": "B",
  "What NBA team has the most playoff appearances?: ": "D",
  "What NBA team has had the best regular season record?: ": "C"
}

nba_options = [["A. Ray Allen", "B. Reggie Miller", "C. Stephen Curry", "D. Larry Bird"],
          ["A. Lebron James", "B. Wilt Chamberlain", "C. Kobe Bryant", "D. Devin Booker"],
          ["A. Michael Jordan", "B. Lebron James", "C. Kevin Durant", "D. Elgin Baylor"],
          ["A. Spud Webb","B. Muggsy Bogues", "C. Nate Robinson", "D. Nate Archibald"],
          ["A. Chicago Bulls","B. Golden State Warriors", "C. Boston Celtics", "D. Los Angeles Lakers"],
          ["A. 1996 Chicago Bulls","B. 1972 Los Angeles Lakers", "C. 2016 Golden State Warriors", "D. 1997 Chicago Bulls"]]
#-----------------------------------------------------------------------------------------------------------------------------------------
mlb_questions = {
  "What player has hit the most home runs in their career?: ": "B",
  "What player has had the highest career batting average?: ": "C",
  "What MLB team has had the best regular season record?: ": "B",
  "What player has had the most hits in their career?: ": "A",
  "What MLB team has won the most World Series titles?: ": "D",
  "What pitcher has won the most Cy Young Awards?: ": "C"
}

mlb_options = [["A. Babe Ruth", "B. Barry Bonds", "C. Alex Rodriguez", "D. Albert Pujols"],
          ["A. Willie Mays", "B. Joe Jackson", "C. Ty Cobb", "D. Babe Ruth"],
          ["A. 1909 Pittsburgh Pirates", "B. 1906 Chicago Cubs", "C. 2001 Seattle Mariners", "D. 1927 New York Yankees"],
          ["A. Pete Rose","B. Derek Jeter", "C. Ty Cobb", "D. Ichiro Suzuki"],
          ["A. Oakland Athletics","B. St. Louis Cardinals", "C. Boston Red Sox", "D. New York Yankees"],
          ["A. Max Scherzer","B. Randy Johnson", "C. Roger Clemens", "D. Greg Maddux"]]
#-----------------------------------------------------------------------------------------------------------------------------------------
nfl_questions = {
  "What quarterback has thrown the most passing yards in their career?: ": "D",
  "What running back has had the most rushing yards in a single season?: ": "B",
  "What player has scored the most touchdowns in their career?: ": "B",
  "What NFL team has won the most Super Bowls?: ": "D",
  "What NFL team has had the best regular season record?: ": "C",
  "What quarterback has thrown the most touchdowns in a single season?: ": "A"
}

nfl_options = [["A. Brett Favre", "B. Peyton Manning", "C. Drew Brees", "D. Tom Brady"],
          ["A. Derrick Henry", "B. Eric Dickerson", "C. Marshawn Lynch", "D. Barry Sanders"],
          ["A. Emmitt Smith", "B. Jerry Rice", "C. Randy Moss", "D. LaDainian Tomlinson"],
          ["A. San Francisco 49ers","B. Pittsburgh Steelers", "C. New England Patriots", "D. Tie Between Patriots and Steelers"],
          ["A. 2011 Green Bay Packers","B. 2015 Carolina Panthers", "C. 2007 New England Patriots", "D. 1984 San Francisco 49ers"],
          ["A. Peyton Manning","B. Tom Brady", "C. Patrick Mahomes", "D. Aaron Rodgers"]]

#-----------------------------------------------------------------------------------------------------------------------------------------

new_game()

while play_again():
  new_game()
    
print("Game Over: Thanks For Playing!")

The problem is that a different new_game() function is created based on the initial input of game_mode . The code needs to be rewritten to include only one new_game() function definition and do the game_mode logic within that function. In fact, all of the functions are created differently depending on input, this is a poor game design in general. This game could be coded with about 1/10 of the lines used here and be much more readable. I would consider rewriting the entire game with the intended logic in mind from the start.

If you want to keep the scuffed logic that is currently used you can include this scuffed fix:

Change the entire file to be included in a main() function and loop that instead. Something like:

def main():
    if gamemode1:
        #define functions 1
    if gamemode2:
        #define functions 2
    if gamemode3:
        #define functions 3
    #define question variables
    new_game()

while input("Start a new game?") == 'yes':
    main()

But again, this is a terrible approach to creating this game. A better attempt would be to use this type of format:

while input("Start a new game? ").lower() == 'yes':
    game_mode = input("What mode?")
    if mode1:
        questionDict = mode1Dict
    elif mode2:
        questionDict = mode2Dict   
    elif mode3:
        questionDict = mode3Dict

    #define functions that use questionDict

    new_game()

There are many repetitions in your code, here is a rewritten version with the problem fixed.

def new_game(questions, options):
    guesses = []
    correct_guesses = 0
    question_num = 1
  
    for key in questions:
        print("-------------------------------------------------")
        print(key)
        for i in options[question_num-1]:
            print(i)
        guess = input("Enter (A, B, C, or D): ")
        guess = guess.upper()
        guesses.append(guess)
    
        correct_guesses += check_answer(questions.get(key), guess)
        question_num += 1
    
    display_score(correct_guesses, guesses)
    
#-------------------------
def check_answer(answer, guess):
  if answer == guess:
    print("CORRECT!")
    return 1
  else:
    print("INCORRECT!")
    return 0
#-------------------------------
def display_score(correct_quesses, guesses):
  print("-------------------------------------------------")
  print("RESULTS:")
  print("-------------------------------------------------")

  print("Answers: ")
  for i in questions:
    print(questions.get(i))
  print("")

  print("Guesses: ")
  for i in guesses:
    print(i)
  print("")

  score = int((correct_quesses/len(questions))*100)
  print("Your score is: "+str(score)+"%")
  
#-------------------------------
nba_questions = {
  "What player has made the most 3 pointers in their career?: ": "C",
  "What player scored the most points in one game?: ": "B",
  "What player has the highest career points per game?: ": "A",
  "Who is the shortest NBA player of all time?: ": "B",
  "What NBA team has the most playoff appearances?: ": "D",
  "What NBA team has had the best regular season record?: ": "C"
}

nba_options = [["A. Ray Allen", "B. Reggie Miller", "C. Stephen Curry", "D. Larry Bird"],
          ["A. Lebron James", "B. Wilt Chamberlain", "C. Kobe Bryant", "D. Devin Booker"],
          ["A. Michael Jordan", "B. Lebron James", "C. Kevin Durant", "D. Elgin Baylor"],
          ["A. Spud Webb","B. Muggsy Bogues", "C. Nate Robinson", "D. Nate Archibald"],
          ["A. Chicago Bulls","B. Golden State Warriors", "C. Boston Celtics", "D. Los Angeles Lakers"],
          ["A. 1996 Chicago Bulls","B. 1972 Los Angeles Lakers", "C. 2016 Golden State Warriors", "D. 1997 Chicago Bulls"]]
#-----------------------------------------------------------------------------------------------------------------------------------------
mlb_questions = {
  "What player has hit the most home runs in their career?: ": "B",
  "What player has had the highest career batting average?: ": "C",
  "What MLB team has had the best regular season record?: ": "B",
  "What player has had the most hits in their career?: ": "A",
  "What MLB team has won the most World Series titles?: ": "D",
  "What pitcher has won the most Cy Young Awards?: ": "C"
}

mlb_options = [["A. Babe Ruth", "B. Barry Bonds", "C. Alex Rodriguez", "D. Albert Pujols"],
          ["A. Willie Mays", "B. Joe Jackson", "C. Ty Cobb", "D. Babe Ruth"],
          ["A. 1909 Pittsburgh Pirates", "B. 1906 Chicago Cubs", "C. 2001 Seattle Mariners", "D. 1927 New York Yankees"],
          ["A. Pete Rose","B. Derek Jeter", "C. Ty Cobb", "D. Ichiro Suzuki"],
          ["A. Oakland Athletics","B. St. Louis Cardinals", "C. Boston Red Sox", "D. New York Yankees"],
          ["A. Max Scherzer","B. Randy Johnson", "C. Roger Clemens", "D. Greg Maddux"]]
#-----------------------------------------------------------------------------------------------------------------------------------------
nfl_questions = {
  "What quarterback has thrown the most passing yards in their career?: ": "D",
  "What running back has had the most rushing yards in a single season?: ": "B",
  "What player has scored the most touchdowns in their career?: ": "B",
  "What NFL team has won the most Super Bowls?: ": "D",
  "What NFL team has had the best regular season record?: ": "C",
  "What quarterback has thrown the most touchdowns in a single season?: ": "A"
}

nfl_options = [["A. Brett Favre", "B. Peyton Manning", "C. Drew Brees", "D. Tom Brady"],
          ["A. Derrick Henry", "B. Eric Dickerson", "C. Marshawn Lynch", "D. Barry Sanders"],
          ["A. Emmitt Smith", "B. Jerry Rice", "C. Randy Moss", "D. LaDainian Tomlinson"],
          ["A. San Francisco 49ers","B. Pittsburgh Steelers", "C. New England Patriots", "D. Tie Between Patriots and Steelers"],
          ["A. 2011 Green Bay Packers","B. 2015 Carolina Panthers", "C. 2007 New England Patriots", "D. 1984 San Francisco 49ers"],
          ["A. Peyton Manning","B. Tom Brady", "C. Patrick Mahomes", "D. Aaron Rodgers"]]

#-----------------------------------------------------------------------------------------------------------------------------------------
print("Sports Trivia Game")
#-------------------------------
game_mode = input("Enter Game Mode - NBA | MLB | NFL: ")
game_mode = game_mode.upper()

while True:
    if game_mode=="NBA":
        questions = dict(nba_questions)
        options = nba_options[:]
        break 
    elif game_mode=="MLB":
        questions = dict(mlb_questions)
        options = mlb_options[:]
        break 
    elif game_mode=="NFL":
        questions = dict(nfl_questions)
        options = nfl_options[:]
        break        
    else:
        game_mode = input("Enter Game Mode - NBA | MLB | NFL: ")
        game_mode = game_mode.upper()

new_game(questions, options)
    
while input("Do you want to play again?: ").lower() == 'yes':
    game_mode = input("Enter Game Mode - NBA | MLB | NFL: ")
    game_mode = game_mode.upper()

    while True:
        if game_mode=="NBA":
            questions = dict(nba_questions)
            options = nba_options[:]
            break 
        elif game_mode=="MLB":
            questions = dict(mlb_questions)
            options = mlb_options[:]
            break 
        elif game_mode=="NFL":
            questions = dict(nfl_questions)
            options = nfl_options[:]
            break        
        else:
            game_mode = input("Enter Game Mode - NBA | MLB | NFL: ")
            game_mode = game_mode.upper()
    new_game(questions, options)
    
print("Game Over: Thanks For Playing!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM