我试图让我的代码有 10 个随机放置和大小的矩形出现在整个屏幕上,但即使使用我的循环我也没有得到 10 个,只有一个。我很确定我的问题是我将循环中的内容附加到 my_list 的方式,但我不确定。
我知道这可能很容易解决,但我就是想不通,感谢您提前提供帮助。
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
class Rectangle():
def __init__(self):
self.x = random.randrange (0, 700)
self.y = random.randrange (0, 500)
self.height = random.randrange (20, 70)
self.width = random.randrange (20, 70)
self.change_x = random.randrange (-3, 3)
self.change_y = random.randrange (-3, 3)
def move(self):
self.x += self.change_x
self.y += self.change_y
def draw(self, screen):
pygame.draw.rect(screen, GREEN, [self.x, self.y, self.height, self.width])
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
my_list = []
for i in range(10):
my_object = Rectangle()
my_list.append(my_object)
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Drawing code should go here
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
my_object.move()
my_object.draw(screen)
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
pygame.quit()
请您参考如下方法:
您只绘制了一个矩形。这:
while not done:
[..]
# --- Drawing code should go here
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
my_object.move()
my_object.draw(screen)
应该更像这样:
while not done:
[..]
# --- Drawing code should go here
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
for my_object in my_list:
my_object.move()
my_object.draw(screen)
