First of all, I should say I'm brand new to PyGame and am pretty new to advanced Python. I'm trying to make a side-scrolling game but just making a sprite move back and forth with keyboard input is proving to be a problem. It appears that the loop is running really slowly, so when pygame.event.get() is called, it doesn't consistently "catch" any events, if that makes any sense. This is apparent when trying to close the window with the X button - it only closes if the button is clicked repeatedly. Here's the code:
import pygame, sys
from pygame.locals import *
from multiprocessing import Process
pygame.init()
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
MAXSCREEN_X = 400
MAXSCREEN_Y = 400
wasd = [False, False, False, False]
def keyUpdate():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_a:
wasd[1] = True
if event.key == K_d:
wasd[3] = True
if event.type == pygame.KEYUP:
if event.key == K_a:
wasd[1] = False
if event.key == K_d:
wasd[3] = False
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, direction, image, movespeed=40):
self.x = x
self.y = y
self.direction = direction
self.image = pygame.image.load(image)
self.movespeed = 40
self.canMoveLeft = True
self.canMoveRight = True
self.width = self.image.get_width()
self.height = self.image.get_height()
def update(self, timePassed):
if self.x + self.width >= MAXSCREEN_X:
self.canMoveRight = False
else:
self.canMoveRight = True
if self.x <= 0:
self.canMoveLeft = False
else:
self.canMoveLeft = True
if wasd[1] and not wasd[3] and self.canMoveLeft:
direction = -1
elif wasd[3] and self.canMoveRight:
direction = 1
else:
direction = 0
print(self.canMoveLeft, self.canMoveRight)
self.x += self.direction * timePassed * self.movespeed
screen.blit(self.image, (self.x, self.y))
player = Player(200, 200, 0, 'player.jpg')
while True:
screen.fill((255, 255, 255))
keyUpdate()
player.update(0.0333)
for event in pygame.event.get():
if event.type == QUIT:
break
pygame.event.pump()
pygame.display.update()
clock.tick(30)
pygame.quit()
sys.exit()
Like I said, I'm very new to this so I'm probably doing something really stupid. Any help here would be appreciated.