<>我有问题让球弹出墙壁和矩形放在中间,我尝试使用if语句,但不能让它工作,任何帮助都会被赏识,或者如果有其他错误,可以被修正,以进一步优化代码,这将是极大的赞赏。p>
import pygame, random
pygame.init()
screen = pygame.display.set_mode([700,500])
# Set up global variables
class Ball():
x = y = xspeed = yspeed = colour = rad = 0
class rec():
x = y = w = h = colour = 0
w = screen.get_width()
h = screen.get_height()
rec.x = w/2
rec.y = h/2
rec.w = w/7
rec.h = h/5
# Create a list of balls
balls = []
# Create ball and include in the list of balls
for i in range(1):
ball = Ball()
ball.x = random.randint(0,w-ball.rad-ball.rad)
ball.y = random.randint(0,h-ball.rad-ball.rad)
ball.xspeed = random.randint(-2,2)
ball.yspeed = random.randint(-2,2)
while ball.xspeed == 0 or ball.yspeed == 0:
ball.xspeed = random.randint(-2,2)
ball.yspeed = random.randint(-2,2)
ball.rad = random.randint(5,30)
ball.colour = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
if ball.x + ball.rad <= w and ball.y + ball.rad <= h:
balls.append(ball)
#Game loop
while True:
# ===================== HANDLE EVENTS (DO NOT EDIT) ===================== #
done = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
done = True
break
if done == True:
break
# ============================== MOVE STUFF ============================= #
for ball in balls:
ball.x = ball.x + ball.xspeed
ball.y = ball.y + ball.yspeed
# ============================== COLLISION ============================== #
for ball in balls:
if ball.x - ball.rad <= 0 :
ball.xspeed = ball.xspeed * -1
elif ball.x + ball.rad >= w:
ball.xspeed = ball.xspeed * -1
elif ball.y - ball.rad<= 0 :
ball.yspeed = ball.yspeed * -1
elif ball.y + ball.rad >= h:
ball.yspeed = ball.yspeed * -1
elif ball.x + ball.rad <= rec.x or ball.x - ball.rad >= rec.x + rec.w:
ball.xspeed = ball.xspeed * -1
elif ball.y + ball.rad <= rec.y or ball.y - ball.rad <= rec.y + rec.h:
ball.yspeed = ball.yspeed * -1
elif ball.x + ball.rad == rec.x + rec.w:
ball.xspeed = ball.xspeed * -1
elif ball.x + ball.rad == rec.x:
ball.xspeed = ball.xspeed * -1
elif ball.y +ball.rad == rec.y + rec.h:
ball.yspeed = ball.yspeed * -1
elif ball.y + ball.rad == rec.y:
ball.yspeed = ball.yspeed * -1
# ============================== DRAW STUFF ============================= #
screen.fill ((255,255,255))
for ball in balls:
pygame.draw.circle (screen, (ball.colour), (ball.x,ball.y), ball.rad)
pygame.draw.rect(screen, (0,255,0), (rec.x, rec.y, rec.w, rec.h))
# ====================== PYGAME STUFF (DO NOT EDIT) ===================== #
pygame.display.flip()
pygame.time.delay(20)
Tags:
计算球中心到障碍物中心的距离
在检测到碰撞后,将球移动到与球员接触但不与球员相交的位置。仅当球的运动矢量指向球的“反”方向时,才反映球的运动。球可以用^{} 反射到障碍物上:
另见How do I avoid an glitchy collision between circle and rectangle in PyGame?
最简单的例子:
相关问题 更多 >
编程相关推荐