python - 在 Pygame 中删除对象?
问题描述
大家好,我只是想做一些很酷的事情,但我不知道如何在 pygame 中删除绘制的 OBJ 我在使用 remove() 和 Delete() 时出错
这是代码:
import pygame
pygame.init()
VEL = 5
SCREEN = pygame.display.set_mode((800,600))
pygame.display.set_caption("The test")
Clock = pygame.time.Clock()
Rect = pygame.Rect(500,300,30,30)
Rect1= pygame.Rect(300,300,30,30)
Run = True
def Collide() :
if Rect1.colliderect(Rect):
Rect.delete()
while Run :
Clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
Run = False
SCREEN.fill((83,83,83))
P1 = pygame.draw.rect(SCREEN,(0,255,0),Rect)
P2 = pygame.draw.rect(SCREEN,(255,0,0),Rect1)
KEY_PRESSED = pygame.key.get_pressed()
if KEY_PRESSED[pygame.K_RIGHT] and Rect.x+VEL+ Rect.height<800:
Rect.x +=VEL
if KEY_PRESSED[pygame.K_LEFT] and Rect.x-VEL>0:
Rect.x -=VEL
if KEY_PRESSED[pygame.K_UP] and Rect.y-VEL>0:
Rect.y -=VEL
if KEY_PRESSED[pygame.K_DOWN] and Rect.y+VEL+ Rect.height<600:
Rect.y +=VEL
Collide()
pygame.display.flip()
pygame.quit()
等待一些答案。
解决方案
您不能“删除”分别在 Surface 屏幕上绘制的内容。Surface 仅包含按行和列组织的一堆像素。如果你想“删除”一个对象,那么你一定不能绘制它。
例如:
def Collide():
global collided
if Rect1.colliderect(Rect):
collided = True
collided = False
while Run :
# [...]
Collide()
SCREEN.fill((83,83,83))
if not collided:
pygame.draw.rect(SCREEN,(0,255,0),Rect)
pygame.draw.rect(SCREEN,(255,0,0),Rect1)
pygame.display.flip()
推荐阅读
- javascript - 错误:对象作为反应子无效
- r - 从R中的JPG URL链接中提取JPG名称
- splunk - Splunk:过滤表数据
- java - 如何将此代码转换为我更熟悉的更简单的代码?
- python - 我没有得到我错的地方
- arrays - F#:如何以函数方式遍历字符串数组列表(字符串 [] 列表)
- excel - 目标文件夹未正确设置
- ruby-on-rails - 如何在 Rails 中为一篇文章添加多个类别
- python - Flask 应用程序返回 json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)
- javascript - Efficient Javascript Code: better to pass variables as arguments in a function, or to replicate the variables?