首页 > 解决方案 > 在pygame中绘制后如何删除形状?

问题描述

我正在pygame中制作游戏。我使用“激光”作为玩家发射的弹丸。我目前使用一个系统,当某个条件为真时,我将激光的颜色更改为红色。但是,这不适用于 collidirect。当“激光”与实体发生碰撞时,Collidirect 会立即“激活”。激光是在我的代码的最后一行绘制的。

这是代码:

import pygame
import sys
# Creating a loop to keep program running
    while True:
       
        # --- Event Processing and controls
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    spaceship_x_change = 10
                elif event.key == pygame.K_LEFT:
                    spaceship_x_change = -10
                elif event.key == pygame.K_UP:
                    red = (255, 0, 0)
            elif event.type == pygame.KEYUP:
                red = (0, 0, 0)
                spaceship_x_change = 0

        spaceship_x += spaceship_x_change

        # Preventing the ship from going off the screen
        if spaceship_x > display_width - 140:
            spaceship_x -= 10
        if spaceship_x < 1:
            spaceship_x += 10

        pygame.draw.rect(game_display, red, [spaceship_x + 69, 70, 4, 310])

标签: pythonpygame

解决方案


这只是一个理论上的例子,因为片段本身不能工作,我将向您展示如何实现删除对象的示例。

因此,如果您想在飞船到达屏幕边缘时将其移除,您可以按照这些思路进行操作。

import pygame
import sys
# Creating a loop to keep program running

draw_spaceship = True

    while True:
       
        # --- Event Processing and controls
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    spaceship_x_change = 10
                elif event.key == pygame.K_LEFT:
                    spaceship_x_change = -10
                elif event.key == pygame.K_UP:
                    red = (255, 0, 0)
            elif event.type == pygame.KEYUP:
                red = (0, 0, 0)
                spaceship_x_change = 0

        spaceship_x += spaceship_x_change

        # Preventing the ship from going off the screen
        if spaceship_x > display_width - 140:
            draw_spaceship = False
        elif spaceship_x < 1:
            draw_spaceship = False
        else:
            # spaceship is within the screen bounds
            draw_spaceship = True

        if draw_spaceship:
            # this doesnt actually draw the spaceship,
            # but you would put the equivalent code here that did that.
            pygame.draw.rect(game_display, red, [spaceship_x + 69, 70, 4, 310])

因此,您需要一个标志或某些要检查的条件,这将决定您是否绘制对象。


推荐阅读