Search code examples
pythonpygamepong

How to make objects go to the end of the screen in Pygame?


I'm pretty new to Python and Programming overall.I'm making a Pong game on Pygame but have problems with the pongs (bars) going off the screen. Here's the code:

    if Move_Down:
        pong1_posY += 10
    if Move_Up:
        pong1_posY -= 10
    if Move_Down2:
        pong2_posY += 10
    if Move_Up2:
        pong2_posY -= 10

    if pong1_posY + pong_size[1] >= ScreenH:
        pong1_posY -= 10
    elif pong1_posY <= 0:
        pong1_posY += 10
    if pong2_posY + pong_size[1] >= ScreenH:
        pong2_posY -= 10
    elif pong2_posY <= 0:
        pong2_posY += 10

Note that every variable that has a "2" on it refers to the right pong. If it has nothing refers to the pong on the left.

The code works fine. The pongs don't go off the screen but neither do they hit the end of the screen.enter image description here

This is as far as the bars will go. Why is this and how can I make them go all the way to the top or bottom of the screen?


Solution

  • I had a similar issue with a space invaders type game. It seems like you're skipping the pixels on the edge of the screen because you're changing the paddle's position 10 pixels at a time. Try:

    if pong1_posY + pong_size[1] >= ScreenH:
       pong1_posY = ScreenH - pong_size[1]
    elif pong1_posY <= 0:
       pong1_posY = 0
    if pong2_posY + pong_size[1] >= ScreenH:
       pong2_posY = ScreenH - pong_size[1]
    elif pong2_posY <= 0:
       pong2_posY = 0
    

    This is assuming the paddle's coordinate is the top left of the paddle image