为什么我的Pygame乒乓球游戏中球不弹?
我正在用Pygame制作一个乒乓球游戏的克隆版。我对Python还比较陌生,现在遇到了一些问题。这个程序应该让两个挡板可以移动,并且让球在屏幕边缘反弹,但球却没有反弹。为什么会这样呢?
bif="bg.jpg"
import pygame, sys
from pygame.locals import *
pygame.init()
pygame.display.set_caption("Griffin West's Python Pong")
pygame.mixer.init()
sounda= pygame.mixer.Sound("Music.wav")
sounda.play()
screen=pygame.display.set_mode((1280,720),0,32)
background=pygame.image.load(bif).convert()
color1=(255,255,255)
color2=(255,255,0)
color3=(0,0,255)
color4=(0,255,0)
pos1=(640,0)
pos2=(640,720)
pos3=(640,360)
pos4=(0,360)
pos5=(1280,360)
radius=(100)
x1,y1=75,0
x2,y2=1175,0
x3,y3=0,0
clock=pygame.time.Clock()
speed=750
movex1, movey1=0,0
movex2, movey2=0,0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_w:
movey1=-2
elif event.key==K_s:
movey1=+2
if event.key==K_UP:
movey2=-2
elif event.key==K_DOWN:
movey2=+2
if event.type==KEYUP:
if event.key==K_w:
movey1=0
elif event.key==K_s:
movey1=0
if event.key==K_UP:
movey2=0
elif event.key==K_DOWN:
movey2=0
x1+=movex1
y1+=movey1
x2+=movex2
y2+=movey2
milli=clock.tick()
seconds=milli/1000.0
dm=seconds*speed
x3+=dm
y3+=dm
if x3>1280:
x3+=-dm
if y3>720:
y3+=-dm
if x3<0:
x3+=dm
if y3<0:
y3+=dm
screen.blit(background, (0,0))
screen.lock()
pygame.draw.line(screen, color1, pos1, pos2, 1)
pygame.draw.circle(screen, color1, pos3, radius, 1)
pygame.draw.circle(screen, color1, pos4, radius, 1)
pygame.draw.circle(screen, color1, pos5, radius, 1)
pygame.draw.rect(screen, color3, Rect((x1,y1),(30,100)))
pygame.draw.rect(screen, color2, Rect((x2,y2),(30,100)))
pygame.draw.circle(screen, color4, (int(x3),int(y3)), 15)
screen.unlock()
myfont = pygame.font.SysFont("Press Start 2P", 50)
label = myfont.render("Python", 1, (255,0,0))
screen.blit(label, (494, 115))
myfont = pygame.font.SysFont("Press Start 2P", 50)
label = myfont.render("Pong", 1, (255,0,0))
screen.blit(label, (544, 175))
pygame.display.update()
1 个回答
4
免责声明:我不是pyGame方面的专家。但我觉得这是个逻辑问题。
我猜现在的代码行为是,球从左上角(0,0)移动到右下角(1280,720),然后就停在那里了。
你需要确保球在碰到墙壁时能够改变方向,所以你需要为x和y分别设置不同的速度(这样以后当你想让球根据球拍的击打角度以不同的角度移动时,也会很有帮助)。然后,当球碰到墙壁时,你就改变它的移动方向。
把这个部分替换掉:
dm=seconds*speed
x3+=dm
y3+=dm
if x3>1280:
x3+=-dm
if y3>720:
y3+=-dm
if x3<0:
x3+=dm
if y3<0:
y3+=dm
换成类似这样的代码(记得适当初始化speedx和speedy):
dx=seconds*speedx
dy=seconds*speedy
x3+=dx
y3+=dy
if x3>1280:
x3+=-dx # get ball out of the wall
speedx = -speedx # change direction
if y3>720:
y3+=-dy
speedy = -speedy
if x3<0:
x3+=dx
speedx = -speedx
if y3<0:
y3+=dy
speedy = -speedy