pygame中屏幕边缘的弹跳球(乒乓球游戏)

时间:2021-05-30 12:00:58

标签: python pygame

import pygame
pygame.init()


FPS=50
fpsClock=pygame.time.Clock()
screenh=500
screenw=300

screen=pygame.display.set_mode((screenh,screenw))


paddle1=pygame.image.load('paddle1.png')
rect=paddle1.get_rect()

p1x=130
p1y=10

paddle2=pygame.image.load('paddle2.png')
rect=paddle2.get_rect()
p2x=130
p2y=465
 
*the ball* 
ball=pygame.image.load('player.png')
ballrect=ball.get_rect()
ball_speed=1
ballx=250
bally=150

*ball moving*

def ball_move():
    global ballx, bally
    bally+=ball_speed
    ballx-=ball_speed

***# this is the problem am facing the ball wont bounce of the screenw***
def ball_collide():
    global ballx,bally
    if bally >= screenw:
        print('hello')
        bally *= -ball_speed
    




running=True
while running:

    screen.fill((255,255,0))

    screen.blit(paddle2, (p2y,p2x))
    
    screen.blit(paddle1, (p1y,p1x))
    
    screen.blit(ball, (ballx,bally))

    ball_collide()

    ball_move()

    pygame.display.update()

    fpsClock.tick(FPS)

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
*the key press movement is handdled here*
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_q:
                p1x-=10 
            if event.key==pygame.K_a:
                p1x+=10
            if event.key==pygame.K_UP:
                p2x-=10
            if event.key==pygame.K_DOWN:
                p2x+=10
    

pliz 帮忙解决这个问题,因为我没有时间完成这个 我不知道,但球不会从屏幕上弹起 *如果有其他技术可以解决这个问题,请帮助我,因为每当球超过屏幕时,它都会显示你好,但不会逆转球的运动,这让我很难受 所以我意识到我的问题是屏幕的球弹跳,我的代码没有问题,我只是 python pygame 的初学者,所以真的需要你的帮助 *

1 个答案:

答案 0 :(得分:1)

你只需要改变

    if bally >= screenw:
        print('hello')
        bally *= -ball_speed

    if bally >= screenw:
        print('hello')
        ball_speedx *= -1

现在你可以看到你实际上需要2个速度变量;一个用于 x 方向,一个用于 y 方向。所以这个:

ball_speed=1

应该

ball_speedx=1
ball_speedy=1

还有这个:

    bally+=ball_speed
    ballx-=ball_speed

应该

    bally+=ball_speedy
    ballx-=ball_speedx