2015-11-03 87 views
2

我想讓我的代碼有10個隨機放置和大小的矩形出現在整個屏幕上,但即使我的循環我沒有得到10,只有一個。我很確定我的問題是我將循環中的內容附加到my_list的方式,但我不確定。追加一個變量到列表中創建10個矩形

我知道這可能是一個簡單的解決方案,但我無法弄清楚,謝謝你的幫助提前。

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() 
+0

嘗試寫在打印語句在for循環,看看會發生什麼。此外,在任何其他定義之前將屏幕大小保存爲全局常量「SIZE =(700,500)」,並用它來創建self.x和-self.y,線。編輯:另外,您的Rectangle.move()和Rectangle.draw()不在Rectangle類中。把它調高一點,也許就是這個問題。 –

回答

2

你只畫一個矩形。這:

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) 
+0

呵呵,謝謝! – Sarah