Home > database >  How to solve "object is not defined"
How to solve "object is not defined"

Time:04-05

I wanted to randomize math question inside a snake game. And allow the snake to eat it. Therefore I have to make question appear on the screen. And the answer and wrong answer has to appear as the food. How to solve ""answer" is not defined"?

class Question:

def question():
    num_1 = random.randint(1,12)
    num_2 = random.randint(1,12)
    
    n = random.randint(1,99)
    answer = num_1 * num_2
    canvas.create_text(window,0,
                     font=('consolas',50), text= "{}x{}=".format(num_1,num_2) , fill="red", tag="question")

The food code

class Food:

def __init__(self):

    x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-2) * SPACE_SIZE
    y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 2) * SPACE_SIZE

    self.coordinates = [x, y]

    canvas.create_text(x, y, 
                   font=('consolas',50), text= answer , fill="red", tag="food") # this is [line 47,Col52]

Problem : "answer"is not defined Pylance(reportUndefinedVariable) [Ln47,Col52]

CodePudding user response:

Answer is not global. if you want to access it from the other class you either need to declare it as global variable or you need to pass the variable when calling the other class.

You might want to check here which explains global variables with playground for you to try

  • Related