0

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
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
coldflows
  • 3
  • 2
  • rect is a tuple, it does not have `x` and `y` fields. did you mean `self.x` and `self.y`? – Anton Jan 04 '23 at 14:44
  • sorry if it wasn't clear, I meant x and y from "self.rect = pygame.Rect((x, y, width, height))". I am trying to update x in order to move the rectangle in the x-axis – coldflows Jan 04 '23 at 14:51

1 Answers1

0

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

Also you might want to remove this as it doesn't do anything:

self.x = x
self.y = y

Unless you need the position where it was first created

YoutuberTom
  • 56
  • 1
  • 2
  • No, Python does not automatically round, it automatically truncates. That is something different. – Rabbid76 Jan 04 '23 at 15:04
  • 1
    You should also mention that `self.x` and _`self.y` are superfluous in your solution and do not state the actual position of the object. – Rabbid76 Jan 04 '23 at 15:09