How to keep the sonic inside the screen ?, n coming out from the sides

0
import pygame as pg

pg.init()

display_width = 1000

display_height = 600

color_black =(0,0,0)

color_white = (255,255,255)

color_red = (255,0,0)
#tamanho da imagem
sonic_width = 71

window = pg.display.set_mode((display_width,display_height))

pg.display.set_caption('PyRun')

clock = pg.time.Clock()

sonic_img = pg.image.load('sonic1.1.right.png')

move the sonic

def sonic(x,y):

    window.blit(sonic_img,(x,y))

def game_loop():

    x = (display_width * 0.15)
    y = (display_height * 0.75)

    x_change = 0

    gameExit = False

    while not gameExit:

        for event in pg.event.get():
            if event.type == pg.QUIT:
                gameExit = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_LEFT:
                    x_change = -5
                if event.key == pg.K_RIGHT:
                    x_change = 5

            if event.type == pg.KEYUP:
                if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
                    x_change = 0

        x += x_change
        window.fill(color_white)
        sonic(x,y)




        pg.display.update()
        clock.tick(60)
game_loop()
pg.quit()
quit()
    
asked by anonymous 20.05.2018 / 06:27

1 answer

1

You will get the width of the screen, store it in a variable, and then use the IF to compare if the character has exceeded the width value. If you overtake, you get the character to receive a new location corresponding to the end of your screen. Example with your code:

 if x > display_width:
    window.blit(sonic_img,(display_width,y)) #Manter o personagem sempre antes da margem

 if x < 0:
    x = 0 #Manter o personagem sempre Depois da margem

In this way, it can never leave the edges of the screen.

    
04.10.2018 / 18:07