N
N
Nikita Vezhlivtsev2021-07-16 09:21:09
pygame
Nikita Vezhlivtsev, 2021-07-16 09:21:09

I am learning python and pygame. Why does an object in the game move by pressing the left and right arrows, but immediately returns to the center of the screen?

import sys
import pygame
from pygame import image
from pygame.constants import QUIT

def screen2():
    while True:
        screen =  pygame.display.set_mode((1200, 800))
        black = [255, 255, 255]
        screen.fill(black)
        screen_rect = screen.get_rect()
        image =  pygame.image.load('images/ship.png')
        screen_rect = screen.get_rect()
        rect = image.get_rect()
        rect.midbottom = screen_rect.midbottom
        x  = float(rect.x)
        moving_right = False
        moving_left = False
        ship_speed = 1
        
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    moving_right = True
                elif event.key == pygame.K_LEFT:
                    moving_left = True 
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    moving_right = False
                elif event.key == pygame.K_LEFT:
                    moving_left = False
            elif event.type == pygame.QUIT:
                sys.exit()        

        
        if moving_right:
            if moving_right and rect.right < screen_rect.right:
                x += ship_speed
                rect.x = x
        if moving_left:
            if moving_left and rect.left > 0:
                x -= ship_speed
                rect.x = x        
        
        screen.blit(image, rect)
        pygame.display.flip()
        
screen2()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2021-07-16
@Burzumm

Why do you initialize the display and load the picture on each iteration? That's why it's coming back because you're bringing it back.
The problem is that you are using code that you don't understand. Maybe you should start learning with simple algorithms, and then include concepts such as animation, framebuffer, and so on?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question