简体   繁体   English

我有这个 python 问答游戏,一开始会问你想要什么类型的问答,但如果你想再玩一次,它不会再问这个问题

[英]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.一开始它会询问您是否想要 NBA、MLB 或 NFL 琐事。 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.比如你一开始说NBA,然后再打,又出NBA题了。 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 .问题是根据 game_mode 的初始输入创建了不同的new_game() 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.代码需要重写以仅包含一个new_game() function 定义,并在该 function 中执行game_mode逻辑。事实上,所有函数的创建都取决于输入,这通常是一个糟糕的游戏设计。 This game could be coded with about 1/10 of the lines used here and be much more readable.这个游戏可以用这里使用的大约 1/10 的代码行编码,并且更具可读性。 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.将整个文件更改为包含在main() function 中并改为循环。 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!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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