首页 > 解决方案 > 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帮助解决这个问题,因为我没有多少时间来完成这个我不知道,但是球不会从屏幕上反弹w *如果有其他技术可以解决这个问题 pliz帮助因为它给我带来了困难,因为每当球超过屏幕时它打印你好,但不反转球运动所以我意识到我的问题是屏幕的球弹跳,我的代码没有问题,我只是 python pygame 的初学者,所以真的需要你的帮助 *

标签: pythonpygame

解决方案


你只需要改变

    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

推荐阅读