如何在pygame的while循环中更改/获取矩形的值

时间:2019-05-08 00:19:16

标签: python python-3.x pygame

在我的游戏中,我试图使放置的矩形在三个列表中具有随机生成的颜色,并且每次生成一个新的矩形时,颜色会随机更改为其中的三个名单。使用我现在拥有的代码,它可以在三种颜色之间快速循环,而又不会停止。我还想弄清楚如何获取块的任何颜色并使去掉相同颜色的相邻块,但是我没有运气尝试对此进行编码。

我尝试将颜色设置为while循环之外的变量,但是它只从列表中随机选择一次颜色,并且不会再次更改。

1 个答案:

答案 0 :(得分:1)

矩形列表不足。您还需要颜色列表。

colors = [red,green,blue]
colorChoice = random.choice(colors)
player = pygame.Rect(x,y,width,height)
copylist = []
colorList = []

每次生成新块时,都必须将当前颜色添加到颜色列表中,并将当前矩形添加到块列表中。此外,必须设置新的随机颜色。
创建一个完成任务的函数,并使用global statement在全局范围内设置变量:

def newBlock():
   global player, copylist, colorList, colorChoice

   copylist.append(player.copy())
   colorList.append(colorChoice)
   player.y = 50 
   colorChoice = random.choice(colors)

调用newBlock以生成一个新块并以其颜色绘制ech块:

while run:    

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == moveDownEvent:
            if player.y >= 390 or player.move(0, vel).collidelist(copylist) >= 0:
                newBlock() # <--- spawn new block
            else:
                player.y += vel
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player.x > 168 and player.move(-vel, 0).collidelist(copylist) < 0:
        player.x -= vel
    if keys[pygame.K_RIGHT] and player.x < 330 and player.move(vel, 0).collidelist(copylist) < 0:
        player.x += vel
    if keys[pygame.K_DOWN] and player.y < 390:
        if player.move(0, vel).collidelist(copylist) >= 0:
            newBlock() # <--- spawn new block
        else:
            player.y += vel

    win.fill((128,128,128))

    pygame.draw.line(win,(0,0,0),(148,100),(148,410),2)
    pygame.draw.line(win,(0,0,0),(350,100),(350,410),2)
    pygame.draw.line(win,(0,0,0),(148,410),(350,410),2)

    for i in range(len(copylist)):    
        pygame.draw.rect(win, colorList[i], copylist[i]) # <--- draw block with its color

    pygame.draw.rect(win, colorChoice, player)
    pygame.display.update()
    clock.tick(24)
pygame.quit()