Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to move a rectangle in a pygame socket program

Good day, I am writing a pygame program that uses sockets. Right now I am just trying to get the rectangles to move in the x-axis and I keep getting this error
"self.rect.x += self.dx
AttributeError: ‘tuple’ object has no attribute ‘x’ ".

My goal is just to move the rect left and right. using the move method below.

import pygame
class Player():
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect((x, y, width, height))
        self.vel = 3
        self.dx = 0
        self.dy = 0
        self.jump = False


    def draw(self, win):
        pygame.draw.rect(win, self.color, self.rect)

    def move(self, screen_width, screen_height):
        SPEED = 10
        dx = 0
        dy = 0
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.dx = -SPEED

        if keys[pygame.K_RIGHT]:
            self.dx = SPEED

        self.update()

    def update(self):
        # update player position
        self.rect.x += self.dx
        self.rect.y += self.dy
        self.rect = (self.x, self.y, self.width, self.height)
        self.dx = 0
        self.dy = 0

any help is appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I see that you already created a pygame.Rect object and updated it correct, why recreate that object?
Change this:

def update(self):
    # update player position
    self.rect.x += self.dx
    self.rect.y += self.dy
    self.rect = (self.x, self.y, self.width, self.height)
    self.dx = 0
    self.dy = 0

To:

def update(self):
    # update player position
    self.rect.x += self.dx
    self.rect.y += self.dy
    self.dx = 0
    self.dy = 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading