Search code examples
pythonpython-turtle

function won't detect variable in python "unresolved refernce"


I started to play with the turtle module a little bit and started space invaders type of game and when i added the bullets i ran into a problem, i wanted to create a list of active bullets each entry in this list is an object called Shot and created a variable called shot_num which is basically the ID of each shot here is the main class

import turtle
from shots import Shots


**** some code ****

# shot
shot = turtle.Turtle()
shot.speed(5)
shot.shape("square")
shot.color("white")
shot.shapesize(stretch_wid=2, stretch_len=0.2)
shot.penup()
shot.goto(1200, 1200)

# variables
active_shots = []


shot_num = 0


def gun_shot():
    temp_shot = Shots(shot_num, gun.xcor())
    shot_num += 1                             ###where the problem happends


main_win.listen()
main_win.onkeypress(gun_shot, "space")


while True:
    main_win.update()

and here is the Shot class

import turtle


    class Shots:
    def __init__(self, number, x_location):
        self.number = number
        self.x_location = x_location
        self.shot1 = turtle.Turtle()
        self.shot1.speed(5)
        self.shot1.shape("square")
        self.shot1.color("white")
        self.shot1.shapesize(stretch_wid=2, stretch_len=0.2)
        self.shot1.penup()
        self.shot1.goto(x_location, -200)



    def border_check(self):
        if self.x_location > 400:
            del self

and it says "unresolved refernce shot_num", i dont really understand why when i delete this line it works thank you


Solution

  • As I stated in the commits just add global shot_num

    def gun_shot():
        global shot_num 
        temp_shot = Shots(shot_num, gun.xcor())
        shot_num += 1
    

    It seems like Python doesn't want to recognize your global variable...