如何在pygame中实现增长条?

2024-06-16 10:04:14 发布

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

我在试着做一个加热棒,每次我按“x”键都会变大,我不知道怎么做。我能做什么?在

heatBar = [45, 30]

elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_x:
                for pos in heatBar:
                    pygame.draw.rect(DISPLAYSURF, GREEN,(pos[0],pos[1],10,50))

Tags: keyinposrecteventforiftype
1条回答
网友
1楼 · 发布于 2024-06-16 10:04:14

您可以将area参数传递给^{}area必须是rect或rect样式的元组(x_坐标、y坐标、宽度、高度),并允许您控制曲面的可见区域。因此,如果有一个150像素宽的曲面,并传递一个宽度为100的矩形,则该曲面将仅渲染到100像素的边界。在

现在只需使用heat值(图像宽度的百分比)来计算当前宽度heat_rect.w/100*heat,并将其传递给blit方法。在

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)

HEAT_BAR_IMAGE = pg.Surface((150, 20))
color = pg.Color(0, 255, 0)
# Fill the image with a simple gradient.
for x in range(HEAT_BAR_IMAGE.get_width()):
    for y in range(HEAT_BAR_IMAGE.get_height()):
        HEAT_BAR_IMAGE.set_at((x, y), color)
    if color.r < 254:
        color.r += 2
    if color.g > 1:
        color.g -= 2


def main():
    clock = pg.time.Clock()
    heat_rect = HEAT_BAR_IMAGE.get_rect(topleft=(200, 100))
    # `heat` is the percentage of the surface's width and
    # is used to calculate the visible area of the image.
    heat = 5  # 5% of the image are already visible.
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        keys = pg.key.get_pressed()
        if keys[pg.K_x]:
            heat += 4  # Now 4% more are visible.

        heat -= 1  # Reduce the heat every frame.
        heat = max(1, min(heat, 100))  # Clamp the value between 1 and 100.

        screen.fill(BG_COLOR)
        screen.blit(
            HEAT_BAR_IMAGE,
            heat_rect,
            # Pass a rect or tuple as the `area` argument.
            # Use the `heat` percentage to calculate the current width.
            (0, 0, heat_rect.w/100*heat, heat_rect.h)
            )

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()

相关问题 更多 >