0

Coding Movement in pygame but I have to do it a long way because I have to be able to send the Attributes as a JSON to be able to send across a network but it is not working. Any ideas to either be able to fix my code or make improvements to be able to send objects in a JSON across a socket connection out the other side and reconstructable?

class Player():
    def __init__(self, x, y, width, height, image):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.image = image
        self.vel = 3

    def getAllAtt(self):
        return self.x,self.y,self.height,self.width,self.vel

    def deconRect(self):
        tempRect = self.loadImage().get_rect()
        attArray = [tempRect.left,tempRect.top,tempRect.width,tempRect.height]
        return attArray

    def loadImage(self):
        loadedImage = load(path(basePath,"Graphics","Sprites",self.image))
        return loadedImage

    def loadRect(self):
        loadedRect = self.loadImage().get_rect()
        return loadedRect

    def draw(self, win):
        win.blit(self.loadImage(),(self.x,self.y))

    # def updatePlayer(self,my_dict):
    #     for key,value in my_dict.items:
    #         setattr(self, key, value)

    def move(self):
        keys = pygame.key.get_pressed()

        if keys[K_LEFT]:
            self.loadRect().move_ip(-self.vel,0)
        if keys[K_RIGHT]:
            self.loadRect().move_ip(self.vel, 0)
        if keys[K_UP]:
            self.loadRect().move_ip(0, -self.vel)
        if keys[K_DOWN]:
            self.loadRect().move_ip(0, self.vel)

    def __iter__(self):
        yield "x", self.x
        yield "y", self.y
        yield "height", self.height
        yield "width", self.width
        yield "image", self.image
        yield "vel", self.vel
  • You can put all attributes into a `list` or `dict`. – Jerry Sep 29 '22 at 14:07
  • I would create a `Player.getPacked()` member function that uses the python struct module ( https://docs.python.org/3/library/struct.html ) to pack the relevant parts into a `bytearray` which will be of a known size. Then transmit that block over the socket. Because it's of a known size, you can easily wait for the correct amount of bytes to arrive at the other socket before trying to unpack it. – Kingsley Oct 04 '22 at 00:42

0 Answers0