r/pygame • • Sep 17 '26

pygame functions not working inside a class

I'm working on a simple street fighter style game, and none of my pygame functions are working inside my player1 class

#fight 2p
import pygame
import sys
import random


pygame.init()


screen = pygame.display.set_mode((300, 200), pygame.SCALED | pygame.RESIZABLE)
clock = pygame.time.Clock()


colors = ["#db0050"]


class player1():
    def __init__(self):
        self.x = 10
        self.y = 10
        self.xvel = 0
        self.yvel = 0
        self.gravity = 3
        self.color = colors[0]
        self.rect = pygame.Rect(self.x, self.y, 20, 30)
        pass
    def get_moved(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            self.yvel += -20
        if keys[pygame.K_a]:
            self.xvel -= 2
        if keys[pygame.K_d]:
            self.xvel += 2


        self.yvel += self.gravity


        self.x += self.xvel
        self.y += self.yvel


        if self.xvel > 20:
            self.xvel  = 20
        elif self.xvel < -20:
            self.xvel = -20


        if self.rect.bottom <= 200:
            self.rect.bottom = 200
        
        pass
    def draw(self):
        pygame.draw.rect(screen, self.color, self.rect)


p1 = player1()


running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    screen.fill((255, 255, 255))


    p1.get_moved
    p1.draw


    pygame.display.flip()
    clock.tick(60)


pygame.quit
sys.exit
4 Upvotes

8 comments sorted by

7

u/skepticalruby Sep 17 '26

You need parentheses to call the functions like everyone else said BUT even though you are updating self.x and self.y you need to also update self.rect because that’s actually not getting updated. The values self.rect has are static and were initialized with the class meaning it only has the initial position of x and y. At the bottom of your self.get_moved function, add self.rect.x = self.x and self.rect.y = y.

4

u/Status_Sample_2531 Sep 17 '26

this also made the program functional. thanks a lot to both of you.

2

u/skepticalruby Sep 18 '26

No problem! Glad to have helped! Good luck on your journey

15

u/SyKoHPaTh Sep 17 '26

call the functions with parenthesis:

p1.get_moved()

7

u/Zxqueb Sep 17 '26 edited Sep 17 '26

Seconded.  This is the issue.  Also p1.draw()

Edit:  ...and while you are at it:

pygame.quit()  sys.exit()

All functions / methods need () at the end of their name to let the program recognize that they are, in fact, functions that should be run.

4

u/Status_Sample_2531 Sep 17 '26

thanks, this helped a ton.

-5

u/Syntax-Tactics Sep 17 '26

I'm no Python programmer (thankfully), but it would appear to me you actually have to pass "self" into the get_moved() and draw() functions functions.

4

u/Zxqueb Sep 17 '26

In p1.get_moved(), p1 is the self that shows up in the class.  OP just needs the ()