2013-10-11 2 views
0

Меня попросили создать мелочи, в которой есть 10 вопросов. Каждый вопрос следует выбирать произвольно. Каждые четыре вопроса Python должен спросить, хочет ли пользователь снова играть. Если пользователь говорит «да», то он продолжается снова, если они говорят «нет», он заканчивается. Если игра доходит до того, что больше нет вопросов, она должна извиниться и закончить программу.Ошибки Python: Правильно не задано. Trivia Game

У меня есть две проблемы. Прямо сейчас, похоже, я не использую функцию playAgain(). Это также дает мне эту ошибку: «NameError: глобальное название« раунды »не определено», это также приводит к правильной переменной. Я не уверен, как я могу определить их вне mainObject() без изменения данных, которые они получают в mainObject().

Что мне делать?

import random, sys 

question1 = "In which US state would you find the zip code 12345?" 
question2 = "What never works at night and requires a gnomon to tell the time?" 
question3 = "What color is a polar bear's skin?" 
question4 = "What is Indiana Jones' first name?" 
question5 = "Which is bigger, the state of Florida or England?" 
question6 = "How many white stripes are there on the American flag?" 
question7 = "How many daily tides are there?" 
question8 = "Which country has the longest coastline?" 
question9 = "How many of the gifts in the song 'The Twelve Days of Christmas' do not  involve birds?" 
question10 = "It occurs once in a minute Twice in a week and once in a year what is it?" 

answer1 = "New York" 
answer2 = "Sundial" 
answer3 = "Black" 
answer4 = "Henry" 
answer5 = "Florida" 
answer6 = "Six" 
answer7 = "Two" 
answer8 = "Canada" 
answer9 = "Six" 
answer10 = "E" 


Questions = [question1, question2, question3, 
     question4, question5, question6, 
     question7, question8, question9, question10] 


Answers = [answer1, answer2, answer3, answer4, 
    answer5, answer6, answer7, answer8, answer9, 
    answer10] 

print ("Welcome to the Dynamic Duo's WJ Trivia Game!!") 
print ("Press \"enter\" to play.") 

input() 


last = len(Questions)-1 
#rounds = 0 
#correct = 0 
playagain = " " 

def playAgain(): 
    if (rounds == 4 or rounds == 8): 
      print("Do you want to play another round? (Yes or No)") 
      playAgain = input() 
      accept = "Yes" 
      if PlayAgain.lower() == accept.lower(): 
        mainObject() 
      else: 
        sys.quit() 


def mainObject(): 
    correct = 0 
    last = len(Questions)-1 
    rounds = 0 
    playagain = "yes" 
    while (last>=0): #This continually checks to make sure that there is a new question 
      randomQuestion = random.randint(0, last) 
      rounds += 1 

      print ("Round " + str(rounds)) 
      print (Questions[randomQuestion]) 
      userAnswer = input() 
      questionAsked = (Questions[randomQuestion]) 
      answerRequired = (Answers[randomQuestion]) 
      isitcorrect = False 
      if answerRequired.lower() == userAnswer.lower(): 
        isitcorrect = True 
      if isitcorrect == True: 
        print("Good job! You got the correct answer of " + Answers[randomQuestion]) 
        correct += 1 
        print("You have " + str(correct) + " points.") 
      else: print("Too bad, you got it wrong. The correct answer is " + answerRequired)   
      Questions.remove(questionAsked) 
      Answers.remove(answerRequired) 
      last = len(Questions)-1 
      playAgain()         

mainObject() 

print("I'm sorry, there are no more trivia questions. Your total score is " + str(correct)) 
print("Thanks for playing!") 
+1

Имея функцию под названием "mainObject" немного сбивает с толку. Из имени это похоже, что это должен быть объект, то есть экземпляр класса. И если у вас _did_ есть класс, у вас есть место для размещения «переменных-членов», которые могут быть разделены всеми методами, которые могут быть приятным дизайном здесь. – abarnert

ответ

1

Раскомментируйте

rounds = 0 # at the top 

и вставить

global rounds 

в функциях. Вы увеличиваете раунды (локальные) в основном, но раунды в playAgain не определены.

Есть и другие способы решения проблемы. Но это, скорее всего, самый быстрый и самый легкий для понимания.

+0

AHHH Это имеет смысл! Спасибо!! –

1

Переменная rounds определена в функции mainobject() и является локальной для этой функции. Он недоступен из-за пределов этой функции.

Одно простое решение проблемы было бы передать rounds функции playagain()

таким образом

def playagain(rounds): 
... 


def mainobject(): 
.... 
playagain(rounds)