Global name is not defined python recursion
In the line ( Show
Korem 10.9k7 gold badges53 silver badges71 bronze badges asked Jun 18, 2014 at 17:46
5
and it would work. answered Jun 18, 2014 at 17:49
KoremKorem 10.9k7 gold badges53 silver badges71 bronze badges You have not imported any function named Use answered Jun 18, 2014 at 17:51
AlexAlex 1,9831 gold badge15 silver badges25 bronze badges Change answered Jun 18, 2014 at 17:49
timgebtimgeb 74.5k20 gold badges114 silver badges139 bronze badges I want to make a player that can shoot bullets. To do this i tried defining a class bullet: def __init__(self): self.x = None self.y = None self.radius = 10 self.shooting = False self.speed = 5 def shoot(self): self.shooting = True if self.shooting == True: self.x = (p.x + 60) self.y = (p.y + 25) self.x += self.speed self.y += self.speed pygame.draw.circle(d, (0, 0, 0), (self.x, self.y), self.radius) shoot() I was hoping that the function would keep calling itself and the bullet would keep moving forward. However what actually happens is when i press space, it gives me an error shoot() NameError: name 'shoot' is not defined How i called the function: while True: d.fill((98, 98, 98)) p.draw() for event in pygame.event.get(): pass if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: b.shoot() Something i observed
is that if i remove the recursion AdvertisementAnswer
for recursion. However, this is a poor way to keep the bullet moving. This is a job for a loop. Recursion is best used when you’re calling the routine with a smaller version of the problem; this is just a continuance. while self.shooting == True: self.x = (p.x + 60) self.y = (p.y + 25) self.x += self.speed self.y += self.speed pygame.draw.circle(d, (0, 0, 0), (self.x, self.y), self.radius) This raises the question of how you intend to quit moving the bullet. You need something like self.shooting = (self.x <= x_limit) and (self.y <= y_limit) Where x/y_limit are the upper bounds in that movement direction. |