UnboundLocalError: cannot access local variable 'points' where it is not associated with a value

79 Views Asked by At

I have no idea about what the problem is and how to fix it :( Please help me fix my code. I asked ChatGPT and tried fixing it, but I still failed. Below is my code. The first block is my Q3 Final.py file, and the second black is vampire_game.py file. I'm sorry for putting both codes without cutting some unnecessary parts.. I'm just not sure what parts of code I should show or not so.. Sorry for the inconvenience.

Problem: UnboundLocalError: cannot access local variable 'points' where it is not associated with a value

import random

#Global Variables
username = ""
confirmed_npc = ""
npc_lists = ['Witch', 'Lizzard Man', 'Vampire', 'Phoenix', 'Angel']
points = 0

# Phoenix Mini Game: Adventure Fighting
def phoenix_mg():
    print("p")
    
# Angel Mini Game: Hangman
def angel_mg():
    print("a")

#User Input Validation
def validate_input(prompt, valid_options):
    while True:
        user_input = input(prompt)
        if user_input in valid_options:
            return user_input
        else:
            print("Please enter a valid option.")

#NPC Confirmation Function
def confirmed_npc_function(npc_lists):
    global confirmed_npc
    confirmed_npc = ""
    while True:
        print("\nList of NPCs:")
        for npc in npc_lists:
            print(npc)
        conversation = input("\nNow, which NPC would you like to have a conversation with? (Type 'q' to quit): ").capitalize()
        if conversation.lower() == 'q' or conversation.lower() == 'quit':
            print("Quitting the game...")
            return  
        elif conversation in [npc.capitalize() for npc in npc_lists]:
            confirmed_npc = conversation
            break
        else:
            print("\nInvalid NPC selection. Please pick the correct NPC from the list or type 'q' to quit.")
            confirmed_npc_function()
    
    npc_confirmation = input(f"\nAre you sure that you would want to talk to the {confirmed_npc}?\nType in 'Yes' or 'No': ")
    if npc_confirmation.lower() == "yes":
        if confirmed_npc == "Witch":
            witch_story()
        elif confirmed_npc == "Lizzard man":
            from lizzard_game import dice_game
            dice_game(username, npc_lists)
        elif confirmed_npc == "Vampire":
            vampire_mg(username, points)        
        elif  confirmed_npc == "Phoenix":
            phoenix_mg()
        elif confirmed_npc == "Angel":
            angel_mg()
    else:
        print("\nInvalid NPC selection. Please pick the correct NPC from the list: ")
        confirmed_npc_function()

# Starting Point of Game: The Hidden Garden
def hidden_garden():
    global username
    print('\nWould you like to start a journey by opening the hidden pathway to the lost garden?')
    start_option = input("Enter 'Yes' or 'No': ")

    if start_option.lower() == "yes":
        username = input("What is your name?: ")
        if username.isalpha():
            print(f'\n{username.title()}, you are now the chosen warrior to save the village from the Dragon King.')
            spawn_area()
        else:
            print(f'\nSorry, please only type in alphabetical characters for your username.')
    else:
        print('Hoping to see you again next time!')
        
# Spawn Area Function
directions = """As previously said, you are now the chosen warrior to save this village in danger.
You can access an NPC shop to purchase and equip yourself with a legendary weapon.
In order to purchase the sword, you will have to earn points from playing mini-games 
prepared by each NPC. The designated games and points for each NPC are different. Please save the 
village from the dragon. Wish you all the best. - Wizard Y
"""
def spawn_area():
    print(directions)
    confirmed_npc_function(npc_lists)

#Imported Games
from witch_game import witch_story
from lizzard_game import dice_game
from vampire_game import vampire_mg

# Starting Function
hidden_garden()
import random

#Information Function for Vampire
def information():
    further_instruction = """\nNumber cards (Two through Ten): Face value (e.g., Two has a value of 2, Five has a value of 5). 
\nFace cards (Jack, Queen, King): Each has a value of 10. 
\nAces: Can have a value of either 1 or 11, depending on what is more beneficial to the player's hand.""" #(Appendix D)
    print(further_instruction)
    info_fin = input("\nWhen you are done reading, please enter 'Start' to play the game.\n'Quit' to go back to NPC selection.")
    if info_fin.lower() == "start":
        black_jack()
    elif info_fin.lower() == "quit":
        confirmed_npc_function()
    else:
        print("\nPlease provide a valid input.")

#Vampire Mini Game Instruction 
def vampire_mg(username, points):
    print("\nWelcome to Vampire's Black Jack!")
    vmg_instruction = f"""The rule of this game is same with normal Black Jack. The Vampire
will be the dealer of this game. {username}'s goal is to get as close to 21 by choosing hit 
or stand. Hit means you will continue to receive another card, and stand means that you will
keep your current cards and not receive anymore. If your hand value exceeds 21, you bust and
lose the game. The Vampire also must hit until their hand value is 17 or above. The winner 
is the one closest to the number 21. Wish you a good luck!"""
    print(vmg_instruction)
    while True:
        more_info = input("\nIf you would like to play the game, enter 'Play Game'\nIf you would like to read more information about the game, enter 'Information',\nIf you would like to quite the game, enter 'Quit Vampire'\nType: ")
        if more_info.lower() == "play game": 
            black_jack()
            break
        elif more_info.lower() == "information":
            information()
        elif more_info.lower() == "quit vampire":
            confirmed_npc_function()
        else: 
            print("Please provide a valid input.")
    return points
#Black Jack Function
def black_jack():
    suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
    values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10,
              'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
    decks = [{'value': value, 'suit': suit} for suit in suits for value in values.keys()]

    random.shuffle(decks)

    # Player and Vampire Hands
    vampire_point = 0
    player = []
    vampire = []
    
    def deal_card(deck):
        card = deck.pop(0)
        return card

    player.append(deal_card(decks))
    vampire.append(deal_card(decks))
    player.append(deal_card(decks))
    vampire.append(deal_card(decks))

    print(f"\nYour Cards: {player}")
    print(f"\nVampire's Cards: {vampire}")

    player_sum = sum(values[card['value']] for card in player)
    vampire_sum = sum(values[card['value']] for card in vampire)
    
    while True:
        player_choice = input("\nWould you like to hit or stand: ").lower()
        if player_choice == "hit":
            drawn_card = decks.pop(random.randint(0, len(decks)-1))
            player.append(drawn_card)
            player_sum = sum(values[card['value']] for card in player)
            print(f"\nYour Cards: {player}")
            if player_sum > 21 and any(card['value'] == 'Ace' for card in player):
                ace_value = input("\nChoose the value of Ace (1 or 11): ")
                if ace_value.isnumeric():
                    ace_value = int(ace_value)
                    for card in player:
                        if card['value'] == 'Ace':
                            card['value'] = ace_value
                    break
                else:
                    print("\nInvalid input. Please choose 1 or 11.")
                    continue
            elif player_sum > 21:
                print("\nBust! You lost the game against Vampire.")
                print(f"\nThe Vampire was kind enough to give you {vampire_point} points for entertaining him.")
                print("""\nI hope you had fun playing Black Jack against vampire, but I think you should improve more.
You can now choose other NPCs from the list below. Good luck and save the village from the dragon so that I can
continue my Black Jack Casino!""")
                break
            continue
        elif player_choice == "stand":
            print("\nPlayer stands. Vampire's turn.")
            break
        else:
            print("Please provide a valid input.")
            
#Vampire Turn
    while vampire_sum < 17:
        drawn_card = decks.pop(random.randint(0, len(decks)-1))
        vampire.append(drawn_card)
        vampire_sum = sum(values[card['value']] for card in vampire)
    
    print(f"\nVampire's Cards: {vampire}")
    if vampire_sum > 21:
        print("\nVampire Busts! You win!")
        points += 5
        vampire_point += 5
        print(f"\nYou will receive {vampire_point} for winning against Vampire!")
        print("""\nI hope you enjoyed playing Black Jack with the vampire. Now that the game has ended, you can now move onto other NPCs to enjoy other mini games. 
Just a reminder, please help my village from the dragon. Hope you keep the village safe!""")
        confirmed_npc_function()
    elif vampire_sum > player_sum:
        print("\nVampire Wins!")
        points += 3
        vampire_point += 3
        print(f"\nYou will receive {vampire_point} for your effort!")
        print("""\nI hope you enjoyed playing Black Jack with the vampire. Now that the game has ended, you can now move onto other NPCs to enjoy other mini games. 
Just a reminder, please help my village from the dragon. Hope you keep the village safe!""")
        confirmed_npc_function()
    elif vampire_sum < player_sum:
        points += 7
        vampire_point += 7
        print(f"\nYou will receive {vampire_point} for your winning against Vampire!")
        print("""\nI hope you enjoyed playing Black Jack with the vampire. Now that the game has ended, you can now move onto other NPCs to enjoy other mini games. 
Just a reminder, please help my village from the dragon. Hope you keep the village safe!""")
        confirmed_npc_function()
    else:
        print("\nIt's a tie! The game will restart again to find the winner.")
        black_jack()

The code should not break and continue by going back to the confirmed_npc_function() after the game ends so that the user can choose another npc to play another game. Also, I need the points given to be printed properly.

0

There are 0 best solutions below