【问题标题】:How do I make a rectangle using arrays so that I can have multiple showing on the screen at once?如何使用数组制作一个矩形,以便一次在屏幕上显示多个?
【发布时间】:2017-12-02 22:09:02
【问题描述】:

标题很容易解释。我正在尝试找出如何在 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() 

【问题讨论】:

  • 请隔离您遇到的问题,而不是转储代码块并说如何执行此操作?
  • 没问题,我刚改了。
  • 您必须说明孤立的问题是什么。我们不会为您编写新代码,您会隔离问题/错误,我们会修复它。
  • 问题是我不知道该怎么做。到目前为止,我的代码有效,但我不知道如何包含一个数组以创建多个矩形。
  • 使用for循环从数组/列表中获取元素,并与draw.rect()一起使用

标签: python arrays pygame rectangles


【解决方案1】:

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

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

【讨论】:

  • 是的,我在现有代码的其他地方列出了维度和变量。我想知道如何用数组设置矩形,这样我就可以一次创建多个,
  • 您需要添加更多代码才能向我们展示。如果你在循环中迭代设置 X Y 线,你可以制作它们。
  • 我添加了我的变量
  • @SeanMalhotra 我更新了我的答案,以便它可能会有所帮助,你能解释一下你需要什么,因为它有点模棱两可吗?
【解决方案2】:

如果您有位置列表,则使用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() 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多