I am just getting started with pygame. My Player instances position does not update on the surface even though it's x value is changed accordingly.
'''__main__.py'''
import script
if __name__ == '__main__':
script.setup()
script.update()
-
'''script.py'''
import pygame
from player import Player
from enemy import Enemy
from ball import Ball
def setup():
global window, player, enemy, ball
pygame.init()
pygame.display.set_caption('Pong')
window = pygame.display.set_mode((800, 600))
player = Player(40, window.get_height() / 2 - 100 / 2, 20, 100)
enemy = Enemy(window.get_width() - 40 - 20, window.get_height() / 2 - 100 / 2, 20, 100)
def draw():
player.update()
enemy.update()
pygame.display.update()
player.draw(window)
enemy.draw(window)
def update():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.up = True
if keys[pygame.K_DOWN]:
player.down = True
if not keys[pygame.K_UP]:
player.up = False
if not keys[pygame.K_DOWN]:
player.down = False
draw()
pygame.quit()
-
'''player.py'''
import pygame
class Player:
'''Player'''
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = (255, 255, 255)
self.rect = (self.x, self.y, self.width, self.height)
self.vel = 10
self.up = False
self.down = False
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
def update(self):
if self.up:
self.x -= self.vel
if self.down:
self.x += self.vel
The instance's x value changes when I press up or down, but for some reason it does not get drawn on screen. I have tried moving the draw method and the player.update method but can't seem to get it to work properly.