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帮助解决这个问题,因为我没有多少时间来完成这个我不知道,但是球不会从屏幕上反弹w *如果有其他技术可以解决这个问题 pliz帮助因为它给我带来了困难,因为每当球超过屏幕时它打印你好,但不反转球运动所以我意识到我的问题是屏幕的球弹跳,我的代码没有问题,我只是 python pygame 的初学者,所以真的需要你的帮助 *
解决方案
你只需要改变
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
推荐阅读
- python - 如何从每个键及其所有单独的值中创建对列表
- python - 将标记放在特定的 x 值上
- apache-kafka-streams - 窗口存储 KSTREAM-FILTER-0000000001 的保留期不得小于其窗口大小加上宽限期
- sequelize.js - Sequelize - 模型定义中的变量“sequelize”
- react-native - 如何从数组中获取组件并在 react native 中更改其道具?
- kubernetes - 有没有办法通过字符串值过滤指标,其中一部分来自普罗米修斯查询中另一个查询的结果?
- cesium - 铯负载gltf不是正确的位置
- html - 如何将类选择器应用于元素?
- jenkins - 我可以访问 Jenkins 管道中的当前阶段 id 吗?
- ruby-on-rails - Rails Active Storage 不显示 @user.banner_image