OOP Pygame player_x variable changing but no changes happen in display

Viewed 39

Hi am pretty new to programming in general so this might be a pretty dumb problem. Am currently trying to learn more about OOP by making a game.

while the value of player_x is changing for some reasons its not moving as I expected.

main.py

import pygame, settings, obstacles, npc, player
from utils import *
pygame.init()

window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()

player = player.Player(window)

Loop

run = True

while run:
    FPS.tick(settings.FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                settings.PLAYER_X -= 5
                print(settings.PLAYER_X)

    pygame.display.update()

player.py

import pygame, settings
pygame.init()

class Player():
    def __init__(self, window) -> None:
        pygame.draw.rect(window, settings.OLIVE, (settings.PLAYER_X, settings.PLAYER_Y, settings.PLAYER_WIDTH, settings.PLAYER_HEIGHT)) # (x, y, width, height)
    
    def player_control(self):
        pass

settings.py

WIDTH = 1440
HEIGHT = 720
FPS = 60

PLAYER_X = 100
PLAYER_Y = 200
PLAYER_WIDTH = 50 
PLAYER_HEIGHT = 50

OLIVE = (136, 196, 23)
1 Answers

To move your player, you need to:

  • Render your player in every while-loop
  • Render your player with the updated PLAYER_X

And to achieve it, you need a few modification in your code:

  1. Create a function to render in your player.py and call it in the loop instead of render a player in __init__, which will only be called once.

  2. Reference settings.PLAYER_X only once in the __init__ in player.py and update the variable of the player object when key are pressed.

  3. At the end of every loop, render the player object.


player.py

import pygame, settings
pygame.init()

class Player():
    def __init__(self, window) -> None:
        self.window = window
        self.color = settings.OLIVE
        self.X = settings.PLAYER_X
        self.Y = settings.PLAYER_Y
        self.W = settings.PLAYER_WIDTH
        self.H = settings.PLAYER_HEIGHT
        self.render()
    
    def render(self):
        pygame.draw.rect(self.window, self.color, (self.X, self.Y, self.W, self.H)) 
        
    def player_control(self):
        pass

main.py

import pygame, settings, player
pygame.init()

window = pygame.display.set_mode((settings.WIDTH, settings.HEIGHT))
FPS = pygame.time.Clock()

player = player.Player(window)

run = True

while run:
    FPS.tick(settings.FPS)
    
    for event in pygame.event.get():
        
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                player.X -= 5
                print(player.X)
    window.fill((0, 0, 0))
    player.render()
    pygame.display.update()
Related