1
import pygame
import sys

def main():
    x=375
    y=400
    y_velocity = 0
    acceleration = 0.1
    bg_color=(183,255,183)
    shape_color=(0,255,255)
    x_minus = None
    pygame.init()
    DISPLAY = pygame.display.set_mode((800,800))
    icon = pygame.image.load("assets/firedash.ico")
    pygame.display.set_caption("pygame window")
    pygame.display.set_icon(icon)
    DISPLAY.fill(bg_color)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    y_velocity+=-5
        cube = pygame.draw.rect(DISPLAY,shape_color,(x,y,50,50))
        y+= y_velocity
        y_velocity+=acceleration
        if x_minus == None:
            x+=-2
        if x_minus == False:
            x+=2
        if x_minus == True:
            x+=-2
        if y > 800:
            y_velocity = -abs(y_velocity)
        if x < 0:
            x*=-1
            x_minus = False
        if x > 750:
            x*=-1
            x_minus = True
        pygame.time.delay(10)
        pygame.display.update()
        DISPLAY.fill(bg_color)
main()

Hi can someone tell me why my code isnt working well ? If i run it my cube will go to the left (which is what i want) and if it bump the left side it will bounce, and go to the right side but when it touches the right side the cube just disappear.. anyone has an idea on how to fix it ?

qwatz
  • 13
  • 3

1 Answers1

0

You wrote:

if x > 750:
    x*=-1
    x_minus = True

So if x is for example 755 you will switch it to -755 and start moving to the left. Next loop it will be < 0 so you will switch it to +755 plus something and start moving to the right... and so on. It will be always out of bounds!

To debug these kinds of issues it helps to write your variables to the console: a print(f"pos {x},{y}") at the end of your loop will help you see what happens.

That said, what you probably want is something like this:

if x > 750:
    x = 750 - (x - 750) # (x - 750) is how far you have gone off screen
    x_minus = True
rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • Thank you so much you just fixed my problem and i understand it now ! but why for the if x < 0 i don't have to do this thing with the - (x-750) ? – qwatz Oct 24 '22 at 07:51
  • 1
    @qwatz replace `750` by `0` in the formula : `x = 0 - (x-0)` => `x = -x`. – Alois Christen Oct 24 '22 at 07:53