0

I'm working on making a "Wheel of Fortune" game in my Intro to Programming class. The step that I'm working on states that you need to ask the player if they want to "spin the wheel" or buy a vowel. The code I have sets the variable 'money' equal to zero before I make a def, however when I try to reference it within the definition it says:

line 77, in <module>
r=askSpin()
line 67, in askSpin
if money >= 250:
UnboundLocalError: local variable 'money' referenced before assignment

The code that I currently have is as follows:

import random

names = ["FAMOUS NAMES","jack black","john johns", "donald trump", "filthy frank", "idubbbztv", "john cena"]
places = ["PLACES","rome","home", "maryland", "china", "trump towers", "white house", "reddit"]
categories = [names,places]

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

def displayBoard(missedLetters, correctLetters, secretWord):
    print 'Missed letters:',
    for letter in missedLetters:
        print letter,
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
    print clue
    for letter in blanks: # show the secret word with spaces in between each letter
        print letter,

    print()

def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
    while True:
        guess = raw_input('Guess a letter:')
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return raw_input().lower().startswith('y')

#gets a puzzle
def getRandomPuzzle(cat):
    return cat[random.randint(1,len(cat)-1)]

print('WHEEL OF FORTUNE')
wheel = [900, 2500, 900, 700, 600, 800, 700, 1000000, 600, 550, 900, 650, 700, 800, 650, 0]
missedLetters = ''
correctLetters = ' '
secretIndex = random.randint(0, len(categories) - 1)
c = categories[secretIndex]
secretWord = getRandomPuzzle(c)
clue = c[0]
global money
money = 0
gameIsDone = False
def askSpin():
    ans = raw_input("Would you like to buy a vowel [b], or would you like to spin? [s]")
    if ans == "b":
        if money >= 250:
            money = money - 250
            guess = guess
        if money < 250:
            guess = raw_input("You have insufficient funds, please guess a letter.")
    return ans.lower().startswith('s')
while True:
    displayBoard( missedLetters, correctLetters, secretWord)

    #give user option to spin
    r=askSpin()
    while not r:
        r=askSpin()
    #spin wheel
    value = wheel[random.randint(0,len(wheel)-1)]
    allowGuess = True #flag remains True unless spin BANKRUPT
    if value == 0:
        print "BANKRUPT!!! Good luck paying off those debts! - You have $0"
        allowGuess = False #do not allow user to guess letter
        money = 0
    else:
        print "You rolled $",value

    # Let the player type in a guess.
    if allowGuess:
        guess = getGuess(missedLetters + correctLetters)

        #if the letter is in the word
        if guess in secretWord:
            correctLetters = correctLetters + guess
            #handle money
            letterCount = secretWord.count(guess) #get num occurrences of guess
            money +=(letterCount*value) #add winnings to money

            #print how many occurrences there are
            intro = "There is"
            outro = ""
            if letterCount>1:
                intro = "There are"
                outro = "'s"
            print intro,letterCount,guess,outro

            # Check if the player has won
            foundAllLetters = True
            for i in range(len(secretWord)):
                if secretWord[i] not in correctLetters:
                    foundAllLetters = False
                    break
            if foundAllLetters:
                print('Yes! The secret word is "' + secretWord + '"! You have won!')
                gameIsDone = True

        else: #the letter is not in the word
            print "There are no", guess + "'s"
            missedLetters = missedLetters + guess
        print "You have $", money
    # Ask the player if they want to play again (but only if the game is done).
    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ' '
            gameIsDone = False
            money = 0 #reset money
            secretIndex = random.randint(0, len(categories) - 1)
            c = categories[secretIndex]
            secretWord = getRandomPuzzle(c)
            clue = c[0]
        else:
            break

If you could tell me what I'm doing wrong that gives me this error, that would help me so much.

Daniel E
  • 40
  • 4
  • 4
    You need to use `global` in each function that references the global variable. Otherwise, local scope is assumed. Also, global variables are really frowned upon. You should create a class called `Game` and have `money` as a member variable. – Jonathon Reinhart Mar 13 '17 at 14:20

2 Answers2

2

Declaring global money in a random place in your code brings no good. If you want to tell a function that a variable is a global one, you should declare this global inside the function.

Uriel
  • 15,579
  • 6
  • 25
  • 46
1

Add global money inside the askPin method.

declaring a variable as global inside a function means this is the variable declared in the global scope instead of creating a new variable at this scope.

Fallen
  • 4,435
  • 2
  • 26
  • 46