这并不是说它不起作用,而是它真的命中或未命中。用于查找球是否在球拍x内的代码非常有效,但它们y不起作用。我认为这与球拍或球的边缘有关,它从球拍区域外进入球拍,但请帮忙,或者至少不要对我大喊大叫,说我愚蠢,谢谢!
import pygame,sys,time,random
pygame.init()
width,height =1000,600
win = pygame.display.set_mode((width,height))
pygame.display.set_caption("Hello World")
p1 = 40
p1width = 100
p1score = 0
p2 = 560
p2width = 100
p2score = 0
speed = 4
ballvx=random.randint(1,2)
ballvy=random.randint(1,2)
ballx=300
bally=50
font = pygame.font.Font('CursedTimerUlil-Aznm.ttf', 100)
p1text = font.render(str(p1score), True,(255,255,255))
p1textRect = p1text.get_rect()
p1textRect.center = (width/2/2, 250)
p2text = font.render(str(p1score), True,(255,255,255))
p2textRect = p2text.get_rect()
p2textRect.center = (width/2+(width/2/2), 250)
while True:
win.fill((0,0,0))
#line
pygame.draw.rect(win, (40,40,40), pygame.Rect(width/2-2, 0, 4, 600))
#p1
pygame.draw.rect(win, (255,255,255), pygame.Rect(p1, 550, p1width, 10))
#p2
pygame.draw.rect(win, (255,255,255), pygame.Rect(p2, 550, p2width, 10))
#ball
pygame.draw.rect(win, (255,255,255), pygame.Rect(ballx, bally, 20, 20))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and p1-speed>=0:
p1-=speed
if keys[pygame.K_d] and p1+speed<=width/2-p1width-2:
p1+=speed
if keys[pygame.K_LEFT] and p2-speed>=width/2+2:
p2-=speed
if keys[pygame.K_RIGHT] and p2+speed<=width-p2width:
p2+=speed
ballx+=ballvx
bally+=ballvy
if ballx+ballvx>=width-20:
ballvx*= -1
ballx+=0.1
bally+=0.1
if ballx+ballvx<=0:
ballvx *= -1
ballx+=0.1
bally+=0.1
if bally+ballvy>=height-20:
print(width/2)
print(ballx)
if ballx <= width/2:
p2score+=1
print("score")
else:
p1score+=1
print("is this even running???")
bally = 50
ballx = random.randint(200,800)
ballvx=random.randint(1,2)
ballvy=random.randint(1,2)
if bally+ballvy<=0:
ballx+=0.1
ballvy*=-1
bally+=0.1
if ballx+ballvx in range(p1,p1+p1width) and bally+20 + ballvy >=550 :
ballvy*=-1
ballx+=0.1
bally+=0.1
if ballx+ballvx in range(p2,p2+p2width) and bally+20 + ballvy >=550:
ballvy*=-1
ballx+=0.1
bally+=0.1
time.sleep(0.01)
p1text = font.render(str(p1score), True,(255,255,255))
p1textRect = p1text.get_rect()
p1textRect.center = (width/2/2, 250)
win.blit(p1text, p1textRect)
p2text = font.render(str(p2score), True,(255,255,255))
p2textRect = p2text.get_rect()
p2textRect.center = (width/2+(width/2/2), 250)
win.blit(p2text,p2textRect)
pygame.display.update()
ballx+ballvx in range(p1,p1+p1width)
不会执行您期望的操作。range
函数产生一系列整数值。因此,x in range(a, b)
检查x
是否正是范围[a, b)
中的整数之一。如果x
是一个浮点数,则它不是该范围内的整数。
例如:CCD_ 7生成序列CCD_。整数6
在这个序列中。然而,浮点数6.5
不在此序列中。
如果要检查浮点数x
是否在[a, b]
范围内,则必须使用比较运算符(例如a <= x <= b
(:
while True:
# [...]
if p1 <= ballx+ballvx <= p1+p1width and bally+20 + ballvy >=550:
ballvy*=-1
ballx+=0.1
bally+=0.1
if p2 <= ballx+ballvx <= p2+p2width and bally+20 + ballvy >=550:
ballvy*=-1
ballx+=0.1
bally+=0.1