本文介绍了如何在pygame中发生碰撞后删除图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python制作涉及加电的游戏。有一个随机产生的机会,它会在屏幕上使图像变白。一旦玩家的身体(在这种情况下为队长)与之碰撞,它就会从列表中随机选择一个能量道具。我正在检查图像位置(大小相同)处是否有矩形的碰撞,并尝试删除该矩形,并在发生碰撞后删除该图像。我怎样才能做到这一点?到目前为止,这是我的尝试,但是,我仍然收到错误:列表分配索引超出范围,并突出显示了以下行:del PowerYList [Spot]。有人可以告诉我我在做什么错吗?

I'm making a game involving powerups using python. There is a random chance of one spawning and it blits its image on the screen. it picks a random powerup from a list once the player's body (The captain in this scenario) collides with it. I'm checking the collision with a rectangle at the position of the image (Same size) and attempting to delete the rectangle, and the image once a collision happens. How can I do this? This is my attempt so far, however, I keep receiving the error: "List assignment index out of range" and it highlights the line: del PowerYList[Spot]. Can someone tell me what I'm doing wrong?

if random.randint(1,2500) == 2500:
            PowerY = random.randint(125,585)
            PowerRect = Rect(930, PowerY, 50,50)
            PowerYList.append(PowerY)
            PowerRects.append(PowerRect)


        for X in PowerYList:
            Screen.blit(PowerUp, (930, X))

        Radius = 0
        for X in PowerRects:
            if X.colliderect(Rect(942, CaptainY, 15, 30)) == True:
                Power = random.choice(PowerUps)
                Power = "Nuke"

                Spot = PowerRects.index(X)
                del X
                del PowerYList[Spot]

                if Power == "Health":
                    if Health <= 85:
                        Health += 15
                    else:
                        Health += 100-Health

                elif Power == "Nuke":
                    Radius = 0
                    for Y in range(1,50):
                        draw.circle(Screen, ORANGE, (500, 350), Radius+50)
                        draw.circle(Screen, RED, (500,350), Radius)
                        Radius += 5

                    Gigabits = []
                    Gigabits_Heads = []
                    Gigabit_Health = []
                    S_Gigabits = []
                    S_Gigabits_Heads = []
                    S_Gigabit_Health = []


推荐答案

以下是我构建的一个示例,用于演示与鼠标碰撞时的精灵移除。查看答案以了解其他方法

Here's an example I've constructed to demonstrate sprite removal upon collision with the mouse. See answers like this for other methods

import random
import pygame

screen_width, screen_height = 640, 480
def get_random_position():
    """return a random (x,y) position in the screen"""
    return (random.randint(0, screen_width - 1),  #randint includes both endpoints.
            random.randint(0, screen_height - 1))

def get_random_named_color(allow_grey=False):
    """return one of the builtin colors"""
    if allow_grey:
        return random.choice(all_colors)
    else:
        return random.choice(non_grey)

def non_grey(color):
    """Return true if the colour is not grey/gray"""
    return "grey" not in color[0] and "gray" not in color[0]

all_colors = list(pygame.colordict.THECOLORS.items())
# convert color dictionary to a list for random selection once
non_grey = list(filter(non_grey, all_colors))

class PowerUp(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        width, height = 12, 10
        self.color, color = get_random_named_color()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position by setting the values of rect.x and rect.y
        self.rect = self.image.get_rect().move(*get_random_position())

    def update(self):
        """move to a random position"""
        self.rect.center = get_random_position()

if __name__ == "__main__":
    pygame.init()
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Sprite Collision Demo')
    clock = pygame.time.Clock() #for limiting FPS
    FPS = 60
    exit_demo = False

    #create a sprite group to track the power ups.
    power_ups = pygame.sprite.Group()
    for _ in range(10):
        # create a new power up and add it to the group.
        power_ups.add(PowerUp())

    # main loop
    while not exit_demo:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_demo = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    exit_demo = True
                elif event.key == pygame.K_SPACE:
                    power_ups.update()
            elif event.type == pygame.MOUSEBUTTONUP:
                for _ in range(10):
                    power_ups.add(PowerUp())
        # check for collision
        for p in power_ups:
            if p.rect.collidepoint(pygame.mouse.get_pos()):
                power_ups.remove(p)
                print(f"Removed {p.color} power up")

        screen.fill(pygame.Color("black")) # use black background
        power_ups.draw(screen)
        pygame.display.update()
        clock.tick(FPS)
    pygame.quit()
    quit()

这篇关于如何在pygame中发生碰撞后删除图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:03