0

所以我正在编写一个代码,其中有一堆圆圈穿过屏幕。当它碰到屏幕边缘时,它们必须弹回并朝相反的方向移动。尽管从某种意义上说它不起作用,但我只是得到一个空白屏幕,上面什么都没有。

我的代码:

import random
import pygame
pygame.init()
from pygame.locals import *
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("THING")
blue = (0,0,255)
black = (0,0,0)
listy = []
x = 25
y = 25

clock = pygame.time.Clock()
class Circle:
    def __init__(self,radius,x,y,color):
        self.radius = radius
        self.x = x
        self.y = y
        self.color = color
    def draw_circle(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius,3)
for thingamabobber in range(1,4,1):
    x = 25
    for loop in range(1,11,1):
        circleobj = Circle(25,x,y,blue)
        listy.append(circleobj)
        x = x + 50
    y = y + 50
        
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    clock.tick(60)
    screen.fill(black)
    for circleobj in listy:
        circleobj.draw_circle()
        thingymabobber = random.randint(1,5)
        circleobj.x = circleobj.x + thingymabobber
        if circleobj.x >= 475: #Detecting if hitting edge of screen
            while True:
                circleobj.x = circleobj.x - 1 #Making it bounce back
    pygame.display.update()

我会很感激一个固定的代码和错误是什么。谢谢!

4

1 回答 1

1

当is时,内部while True循环将阻塞应用程序。circleobj.x >= 475True

你根本不需要内在while loop。但是您需要在Circle类中添加一个属性来确定当前的移动方向,例如dx水平移动:

class Circle:
    def __init__(self,radius,x,y,color):
        self.radius = radius
        self.x = x
        self.y = y
        self.color = color
        self.dx = 1  # initial moving direction horizontally
    def draw_circle(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius,3)

然后改写while loop如下:

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    clock.tick(60)
    screen.fill(black)
    for circleobj in listy:
        thingymabobber = random.randint(1,5)
        # change circle object moving direction if it hits boundaries
        if circleobj.x <= 25:
            circleobj.dx = 1
        elif circleobj.x >= 475:
            circleobj.dx = -1
        # move the circle object
        circleobj.x += circleobj.dx * thingymabobber
        circleobj.draw_circle()
    pygame.display.update()
于 2021-11-15T08:03:50.493 回答