首先,我对编码非常陌生,所以如果我的代码看起来很糟糕,那就是为什么
我正在尝试使用PyGame生成10个在随机位置生成并沿随机矢量移动的球。当每个球击中屏幕边缘时,它都会反弹回来。
我下面的代码存在的问题是,球确实可以很好地产卵,球确实可以从窗口弹回,但是球仅沿x轴(左右)移动,但在y轴(上下)。我不知道为什么会这样。
我的代码如下:
from random import randint, choice
import pygame
pygame.init()
## -- set constants
white = [255, 255, 255]
black = [0, 0, 0]
grey = [255/2, 255/2, 255/2]
ball_fill = white # colour of balls or circle objects
ball_line_colour = ball_fill # border and fill of same colour
n_balls = 10 # number of balls on a window
ball_radius = 12 # size of balls in pixels
velocity = vel = {
"x": randint(-2, 3),
"y": randint(-2, 3)
} # must range from -a to +b; otherwise will only move rightward and upward
## -- set display window
win_width = 800 # pixels; width of screen
win_height = 600
## -- Define the boundaries, that is, the points at which the balls would bounce back without going out of the window
boundary_location = ['up', 'down', 'left', 'right']
boundary_coord = [ball_radius, (win_height - ball_radius),
ball_radius, (win_width - ball_radius)]
boundary = dict(zip(boundary_location, boundary_coord))
## -- Define balls
class Ball():
def __init__(self):
self.x = 0
self.y = 0
self.change_x = 0
self.change_y = 0
def make_ball():
"""
Function to make a new circle or ball
"""
ball = Ball()
# spawn points of balls, so that the balls do not overlap when they spawn
x = randint(boundary["left"], boundary["right"])
ball.x = choice([n for n in range(int(boundary["left"]), int(boundary["right"]))
if n not in range(x - ball_radius, x + ball_radius)])
y = randint(boundary["up"], boundary["down"])
ball.y = choice([n for n in range(int(boundary["up"]), int(boundary["down"]))
if n not in range(y - ball_radius, y + ball_radius)])
# Speed and direction of rectangle
ball.change_x = vel["x"]
ball.change_y = vel["y"]
return ball
# Set the height and width of the screen
win_dimen = [win_width, win_height]
win = pygame.display.set_mode(win_dimen)
pygame.display.set_caption("Multiple Object Tracking")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
ball_list = []
for i in range(n_balls):
ball = make_ball()
ball_list.append(ball)
i -= 1
# -------- Main Program Loop -----------
while not done:
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
# Space bar or esc to exit
if event.key == pygame.K_SPACE or event.key == pygame.K_ESCAPE:
done = True
# --- Logic
for ball in ball_list:
# Move the ball's positions
ball.x += ball.change_x
ball.y += ball.change_y
# Bounce the ball if needed
if ball.y > boundary["up"] or ball.y < boundary["down"]:
ball.change_y *= -1
if ball.x > boundary["right"] or ball.x < boundary["left"]:
ball.change_x *= -1
# Set the screen background
win.fill(grey)
# Draw the balls
for ball in ball_list:
pygame.draw.circle(win, white, [ball.x, ball.y], ball_radius)
clock.tick(60)
# Update the screen
pygame.display.flip()
# Close everything down
pygame.quit()
我的下一步是使球彼此反弹,以防万一有人想知道
答案 0 :(得分:0)
检查上/下边界的逻辑是相反的,因此会发生振动,因为这些球不断超出范围并且每帧的y速度都反转。如果您更改行:
if ball.y > boundary["up"] or ball.y < boundary["down"]:
收件人:
if ball.y < boundary["up"] or ball.y > boundary["down"]:
你会很好的。