I made a border in this pong game, but the paddles can cross it. How do I stop that?

前端 未结 2 1589
夕颜
夕颜 2020-12-07 03:19

I made a border in this pong game, and the paddles on the screen can cross it. I have done this before in another piece of code, but everything\'s different now. I have a ma

2条回答
  •  甜味超标
    2020-12-07 03:56

    PyGame has a feature that does exactly what you want it to do. Use pygame.Rect objects and pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():

    Returns a new rectangle that is moved to be completely inside the argument Rect.

    With this function, an object can be kept completely in the window. Get the window rectangle with get_rectand clamp the object in the window:

    while run:
        # [...]
    
        key = pygame.key.get_pressed()
        if key[pygame.K_w]:
            paddle1.rect.y += -paddle_speed
        
        # [...]
        
        winRect = win.get_rect()
        paddle1.rect.clamp_ip(winRect)
        paddle2.rect.clamp_ip(winRect)
        paddle3.rect.clamp_ip(winRect)
        paddle4.rect.clamp_ip(winRect)
    
        # [...]
    

提交回复
热议问题