python - 在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])
解决方案
这只是一个理论上的例子,因为片段本身不能工作,我将向您展示如何实现删除对象的示例。
因此,如果您想在飞船到达屏幕边缘时将其移除,您可以按照这些思路进行操作。
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])
因此,您需要一个标志或某些要检查的条件,这将决定您是否绘制对象。
推荐阅读
- c# - Blazor-Server 如何使用动态 linq 创建 ValueExpression
- kotlin - 使用 kotlin 发送集成在应用程序中的附件
- python - Python Flask validate_on_submit() https 错误
- matlab - 如何在 MATLAB App 中显示计算正在进行
- google-analytics-api - 从 Google_Service_AnalyticsReporting (google/apiclient SDK) 切换到 BetaAnalyticsDataClient (google/analytics-data SDK)
- flask - 在“app”heroku 中找不到属性“run”
- postgresql - Rspec 数据库视图为空
- python - Python - 将包含 NULL 值的数据从 Oracle 移动到 PostgreSQL 数据库
- pytorch - 火炬填充的工作原理
- rust - 使用字符串键从结构中获取数据,并从结构中获取数据到数组