微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在按键单击时绘制矩形

如何解决在按键单击时绘制矩形

我想通过单击按钮绘制一个矩形,但问题是每次循环都会更新显示显示填充了一种颜色 所以矩形只能看到很短的一段时间。 如何解决这个问题。

while not run:
    
    display.fill((130,190,255) )
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
                 
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 30
                
            if event.key == pygame.K_p:
                p_x += 30
            
            if event.key == pygame.K_g:
                
                pygame.draw.rect(display,(0,0),((p_x + 25),1309,20,30))

解决方法

您必须在应用程序循环中绘制矩形。例如,当按下 g 时,将一个新矩形添加到列表中。在应用程序循环中绘制列表中的每个矩形

rectangles = []

exit_game = False
while not exit_game:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
                
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 30
            if event.key == pygame.K_p:
                p_x += 30
            if event.key == pygame.K_g:
                rectangles.append((p_x + 25,1309,20,30))

    display.fill((130,190,255))
     
    pygame.draw.rect(display,(0,0),(p_x + 25,30),1)
    for rect in rectangles:
        pygame.draw.rect(display,rect)

    pygame.display.update()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。