如何在一个函数上添加多个矩形?

2024-04-20 00:10:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我用pygame创建了一个游戏,在这个游戏中你可以建造一座塔,我做了一些代码,每次我按C键时都会在玩家的位置上建造一座塔。我注意到如果我按C键来建造一座塔,然后再建造另一座塔,我造的第一座塔就消失了。你能帮我解决这个问题吗

towerstate = 'unbuilt'
towx = 0
towy = 200
towers = 0

def player_towers(xx, yy):
    global towerstate

    towerstate = 'built'

    pygame.draw.rect(screen, (255, 100, 0), (xx, yy, 30, 30))





def game():
    global towx, towy, towerstate

    x = 15
    y = 200

    vel = 5

    on = True
    while on:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

        lol = pygame.image.load('lol.png')
        screen.blit(lol, (0, 0))
        z = 0
        for layer in tiles:
            t = 0
            for tile in layer:
                 if tile == 'g':
                     screen.blit(gr, (t * 30, z * 30))
                 else:
                     screen.blit(W, (t * 30, z * 30))
                t += 1
            z += 1

    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        y -= vel
    elif keys[pygame.K_s]:
        y += vel
    elif keys[pygame.K_a]:
        x -= vel
    elif keys[pygame.K_d]:
        x += vel

    pl = pygame.draw.rect(screen, (190, 130, 0), (x, y, 30, 30))

    if keys[pygame.K_c]:
        towx = x
        towy = y
        player_towers(towx, towy, )
        towerstate = 'built'

    if towerstate == 'built':
        player_towers(towx, towy, )
        towerstate = 'built'

    if x <= 1:
        x = 0
    elif x >= 570:
        x = 570
    elif y <= 1:
        y = 0
    elif y >= 445:
        y = 445

    pygame.display.update()

on = True
while on:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            on = False
    game()

    pygame.display.update()

Tags: ineventforifonkeysscreenpygame
1条回答
网友
1楼 · 发布于 2024-04-20 00:10:08

从你的代码中不太清楚,但我认为问题是由重新绘制屏幕背景引起的。这将删除任何现有的矩形,并且代码不记得以前绘制的矩形,因此它们将消失。你知道吗

解决这个问题的一种方法是简单地创建一个先前三角形的列表。每次画一个,只要记住这一点。你知道吗

towerstate = 'unbuilt'
rectlist   = []         # remember all rectangles placed
towx = 0
towy = 200
towers = 0

def player_towers(xx, yy):
    global towerstate, rectlist

    towerstate = 'built'

    new_rect = pygame.Rect( xx, yy, 30, 30 )
    rectlist.append( new_rect )
    #pygame.draw.rect(screen, (255, 100, 0), new_rect )  #<  don't do here

然后在主循环中,在重新绘制背景后,重新绘制所有矩形。你知道吗

# ...  (near the end of main loop)
# Draw all the player's rectangles
for r in rectlist:
    pygame.draw.rect(screen, (255, 100, 0), r )

pygame.display.update()

显然,这是一个简单的实现为一个单一的塔。买你可以有列表的列表,或者做一个class让塔把所有的矩形放在一个单独的位置,等等

相关问题 更多 >