Markus121 Markus121 - 1 month ago 4
Python Question

How to change variables inside a class at runtime?

Follow-up question on my previous question.

After I got the circle to show up properly, I wish to be able to move that circle now with keyboard input.

Since it is a class I am trying to change I must have an instance so that I change the same instance of the class all the time, and I do have one.

import pygame
pygame.init()

#Colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

#Display
display_width, display_height = 800, 600
screen_center = int(display_width * 0.5), int(display_height * 0.5)
screen = pygame.display.set_mode((display_width, display_height))

#Clock
clock = pygame.time.Clock()

class Player():
def __init__(self):
self.xPos = int(display_width * 0.5)
self.yPos = int(display_height * 0.5)
self.color = blue
self.radius = 15
self.width = 0

pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)

def game_loop():
player = Player() #PLAYER CLASS INSTANCE

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

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.color = blue # THESE COLORS ARE MAINLY HERE FOR DEBUGGING
if event.key == pygame.K_RIGHT:
player.color = red # THESE COLORS ARE MAINLY HERE FOR DEBUGGING

if event.key == pygame.K_UP:
pass
if event.key == pygame.K_DOWN:
pass

#Background
screen.fill(white)

#Draw everything in order, each drawn object will be drawn beneath the next drawn object.
player

#Update
pygame.display.update()
clock.tick(60)

game_loop()


So whenever I press the left key for example, the xPos inside the class must change so that my circle moves.

Answer

You could try changing your player class to make it have a separat emethod for drawing itself:

class Player():
    def __init__(self):
        self.xPos = int(display_width * 0.5)
        self.yPos = int(display_height * 0.5)
        self.color = blue
        self.radius = 15
        self.width = 0

    def draw(self):
        pygame.draw.circle(screen, self.color, (self.xPos, self.yPos), self.radius, self.width)

Then inside your main loop, call player.draw() after you've done the screen fill:

#Background
screen.fill(white)

#Draw everything in order, each drawn object will be drawn beneath the next drawn object.
player.draw()

Now the player object wont draw itself when it's created, instead it will be drawn during every iteration of your main loop.