删除矩形(吃苹果)

deleting rectangles (eating apples)

我正在尝试制作一款游戏,其中玩家吃苹果并且在玩家与其发生碰撞后必须删除一个矩形,但我得到一个错误:AttributeError:'pygame.Rect' object has no attribute 'remove'

import pygame
import sys




player_pos=x,y,width,height=(0,0,50,50)
enemy_pos=e_x,e_y,e_width,e_height=(200,0,50,50)

pygame.init()
screen=pygame.display.set_mode((1000,440))
FPS=pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_UP:
                y-=25

            if event.key==pygame.K_DOWN:
                y+=25

            if event.key==pygame.K_RIGHT:
                x+=25

            if event.key==pygame.K_LEFT:
                x-=25


            if player1.colliderect(enemy1):
                enemy1.remove()

screen.fill((0,0,0))
player1=pygame.draw.rect(screen,(255,0,0),(x,y,width,height))
enemy1=pygame.draw.rect(screen,(0,0,255),(e_x,e_y,e_width,e_height))
pygame.display.update()
FPS.tick(120)

如果你想从场景中“移除”一个物体,你所要做的就是停止绘制它。
添加一个变量 draw_enemy 并将其初始化为 True。当玩家与敌人发生碰撞时,将变量设置为 False。根据draw_enemy的状态绘制敌人:

draw_enemy = True

while True:
    # [...]

    if player1.colliderect(enemy1):
        draw_enemy = False

    screen.fill((0,0,0))
    player1 = pygame.draw.rect(screen,(255,0,0),(x,y,width,height))

    if draw_enemy:
        enemy1 = pygame.draw.rect(screen,(0,0,255),(e_x,e_y,e_width,e_height))

    pygame.display.update()

或者在前面创建 pygame.Rect

player_rect = pygame.Rect(0, 0, 50, 50)
enemy_rect = pygame.Rect(200, 0, 50, 50)

检测到碰撞时创建对象的新随机位置:

if player_rect.colliderect(enemy_rect):
    enemy_rect.x = random.randrange(0, 975, 25)
    enemy_rect.y = random.randrange(0, 425, 25)

最小示例:

import pygame
import random
pygame.init()
screen = pygame.display.set_mode((1000,440))
clock = pygame.time.Clock()

player_rect = pygame.Rect(0, 0, 50, 50)
enemy_rect = pygame.Rect(200, 0, 50, 50)

while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            exit()

        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_UP:
                player_rect.y -= 25
            if event.key==pygame.K_DOWN:
                player_rect.y += 25
            if event.key==pygame.K_RIGHT:
                player_rect.x += 25
            if event.key==pygame.K_LEFT:
                player_rect.x -= 25
    
    if player_rect.colliderect(enemy_rect):
        enemy_rect.x = random.randrange(0, 975, 25)
        enemy_rect.y = random.randrange(0, 425, 25)

    screen.fill((0,0,0))
    pygame.draw.rect(screen, (255,0,0), player_rect)
    pygame.draw.rect(screen, (0,0,255), enemy_rect)
    pygame.display.update()
    clock.tick(120)