如何使用数组制作矩形,以便我可以在屏幕上同时显示多个?

时间:2017-12-02 22:09:03

标签: python arrays pygame rectangles

标题非常自我解释。我正试图找出如何在python中为这个俄罗斯方块游戏制作一个带阵列的矩形。

以下是代码:

screen = pygame.display.set_mode((400,800))

#Rectangle Variables
x = 200
y = 0
width = 50
height = 50
thickness = 5
speed = 1
#Colors
red = (255,0,0)
white = (255,255, 255)
green = (0,255,0)
blue = (0,0,255)
while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit (); sys.exit ();
    #These lines ^ make the user able to exit out of the game window
    y = y+1
    pygame.draw.rect((screen) , red, (x,y,width,height), thickness)
    pygame.display.update() 

2 个答案:

答案 0 :(得分:0)

如果您只想将矩形添加到数组中,您可以这样做:

rectangles = []
while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit (); sys.exit ();
    #These lines ^ make the user able to exit out of the game window
    y = y+1
    rectangles.append(pygame.draw.rect((screen) , red, (x,y,width,height), thickness))
    pygame.display.update() 

答案 1 :(得分:0)

如果您有包含位置的列表,请使用for循环绘制它。

此处位置以像素为单位

# --- constants --- (UPPER_CASE_NAMES)

WIDTH = 50
HEIGHT = 50 
RED = (255,0,0)

# --- main ---

rectangles_XY = [ (0, 0), (50, 0), (100, 0) ]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            # PLEASE, don't put all in one line 
            # it makes code less readable.
            pygame.quit()
            sys.exit ()

    for x, y in rectangles_XY:
        pygame.draw.rect(screen, RED, (x, y, WIDTH, HEIGHT), 0)

    pygame.display.update() 

此处位置位于单元格位置(列,行)

# --- constants --- (UPPER_CASE_NAMES)

WIDTH = 50
HEIGHT = 50 
RED = (255,0,0)

# --- main ---

rectangles = [ (0, 0), (1, 0), (2, 0) ]

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            # PLEASE, don't put all in one line 
            # it makes code less readable.
            pygame.quit()
            sys.exit ()

    for column, row in rectangles:
        x = column * WIDTH
        y = row * HEIGHT
        pygame.draw.rect(screen, RED, (x, y, WIDTH, HEIGHT), 0)

    pygame.display.update()