Project link: https://github.com/LAGx/abstract_game.git error in game_objects / player / player.py (initialized in init ) and game_objects / bullet / regular.py (responsible for creating player bullets)

in fact, this is the question: in order to be able to shoot many independent bullets at once, I decided to create a list of bullet objects. It works, but every next bullet affects the direction of all previous ones.

this is all updated 60 times per second (

if self.mousepress[0]: #эта штука создает новые объекты и помещает в лист (кстати, мне кажется что здесь и ошибка) self.allBullets.append(game_objects.bullet.regular.RegularBullet([ self.pos[0], self.pos[1] ], list(self.mouse))) for bullet in self.allBullets: bullet.blit(canvas) 

)

RegularBullet class itself:

 import phisic.vector import pygame from serving.cord import * class RegularBullet: posi = [0, 0] vector = phisic.vector.Vector() color = [167,34,46] speed = 2#30 isInit = False def __init__(self, start = [0,0], end = [0,0]): self.posi = start self.vector.changeXEx(end[0] - start[0]) self.vector.changeYEx(end[1] + start[1]) lenth = self.vector.getLenth() self.vector.changeXEx((self.vector.posX)/lenth) self.vector.changeYEx((-self.vector.posY)/lenth) self.isInit = True def blit(self, canvas): pygame.draw.line(canvas,self.color, [self.posi[0], -self.posi[1]], [self.posi[0]+self.vector.posX*self.speed*10, -self.posi[1]-self.vector.posY*self.speed*10], 4) self.posi[0] += self.vector.posX * self.speed self.posi[1] += self.vector.posY * self.speed 

and here's an example of an error: first I shoot one way and all the rules: Start

then, when I shoot in the other direction, ALL the bullets change their direction: mistake!!

    1 answer 1

    You have all the bullets using the same list, which is changed in the .blit() method.

     class RegularBullet: posi = [0, 0] 

    In this code, posi is created as a class variable — one object (list) for all bullets.

    Additionally, def __init__(self, start = [0,0], ...) default value is again the same for all class variables.

    Corrected by creating your own list for each bullet:

     class RegularBullet: def __init__(self, start=None): if start is None: start = [0, 0] self.posi = start 
    • That is, you need to create new objects and add them to the list? How to do it right? self.allBullets.append(copy.deepcopy(game_objects.bullet.regular.RegularBullet([self.pos[0], self.pos[1]], list(self.mouse)))) via copy.deepcopy () not works .... - LAG_x
    • @LAG_x The code that you showed in the question contains at least two problems (indicated in the answer). 1- Learn the difference between a class variable and an instance — do not use class variables (unless you know exactly what you are doing). 2- Do not use mutable default arguments (almost always an error). I showed an example with posi in the answer, you need to make changes for vector, color, etc. - jfs