MaxTriesToCode
MaxTriesToCode

Reputation: 45

Is there a reason this square is not moving?

Im pretty new to python especially PyGame and i have no clue whats going on here. My program will launch and will not crash but the red square will not move based on my key presses

I have used this same control system for something else I made and it worked fine so why wont it work now?

class Player:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = 10
        self.dir = ''

    def update(self):
        if self.dir == 'up':
            self.y -= self.speed
        elif self.dir == 'down':
            self.y += self.speed
        if self.dir == 'right':
            self.x += self.speed
        if self.dir == 'left':
            self.x -= self.speed

        pygame.draw.rect(gameDisplay, red, (self.x, self.y, 50, 50))

run = True

while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()


    for event in pygame.event.get():

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                man.dir = 'up'
            if event.key == pygame.K_s:
                man.dir = 'down'
            if event.key == pygame.K_d:
                man.dir = 'right'
            if event.key == pygame.K_a:
                man.dir = 'left'

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                man.dir = ''
            if event.key == pygame.K_s:
                man.dir = ''
            if event.key == pygame.K_a:
                man.dir = ''
            if event.key == pygame.K_d:
                man.dir = ''

    gameDisplay.fill(white)

    man.update()

    clock.tick(fps)
    pygame.display.update()

Upvotes: 1

Views: 220

Answers (1)

Rabbid76
Rabbid76

Reputation: 211239

You have 2 event loops in the main loop. The 1st loop get all the messages and remove them from the queue. The 2nd event loop will never run.
Since the keyboard events would be handled in the 2nd event loop, they are missed.
Remove the 2nd event loop and handel all events in the 1st event loop to solve the issue:

while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # for event in pygame.event.get():  <---- delete this

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                man.dir = 'up'
            if event.key == pygame.K_s:
                man.dir = 'down'
            if event.key == pygame.K_d:
                man.dir = 'right'
            if event.key == pygame.K_a:
                man.dir = 'left'

        # [...]

Upvotes: 2

Related Questions