如何使用此程序在Python中绘制10个矩形?

时间:2015-12-23 22:08:37

标签: python list loops pygame

  

我试图让它编程打印出10个矩形   使用for循环移动。我在下面打印出来的只是它   打印出1个移动的矩形。我相信我的问题在于一致   67-70?有谁知道如何打印出这个程序10   矩形?

import pygame
from random import randrange 

#Colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)

pygame.init()

#Set width and height of screen
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Classes")

class Rectangle():

    def __init__(self):
        self.x = 0
        self.y = 0
        self.change_x = 0
        self.change_y = 0
        self.width = 0
        self.height = 0
        self.color = [0, 255, 0]
    def draw(self, screen):
        pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height])
    def move(self):
        self.x = self.x + self.change_x
        self.y = self.y + self.change_y     


#Loop until user clicks close
done = False

#Manage how fast screen updates
clock = pygame.time.Clock()

my_list = []
for i in range(10):

    my_object = Rectangle()
    my_object.x = randrange(0, 701)
    my_object.y = randrange(0, 501)
    my_object.change_x = randrange(-3, 3)
    my_object.change_y = randrange(-3, 3)
    my_object.width = randrange(20, 71)
    my_object.height = randrange(20, 71)
    my_object.color = [0, 255, 0]
    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 goes here

    #Screen clearing code or background image goes here
    screen.fill(black)

    #drawing code goes here
    for i in range(len(my_list)):
        my_object.draw(screen)
        i = i + 1
    my_object.move()

    #update and display drawn screen
    pygame.display.flip()

    #limit to 60 frames per second
    clock.tick(60)

#close the window and quit
pygame.quit()

1 个答案:

答案 0 :(得分:3)

更改绘图代码循环
for i in range(len(my_list)):
    my_object.draw(screen)
    i = i + 1
my_object.move()

for my_object in my_list
    my_object.draw(screen)
    my_object.move()

在这段代码中,for my_object in my_list部分遍历" my_list"中的对象,一次一个,并命名为" my_object"。您需要绘制每个对象,并移动每个对象,因此必须从循环内调用绘制和移动。如果你从循环外部调用它们,它只会发生一次。