如何在 pygame 中连续生成和跟踪多个具有时间延迟的随机对象? [复制]

Posted

技术标签:

【中文标题】如何在 pygame 中连续生成和跟踪多个具有时间延迟的随机对象? [复制]【英文标题】:How can one continuously generate and track several random objects with a time delay in pygame? [duplicate] 【发布时间】:2020-01-10 05:34:09 【问题描述】:

我想知道如何以 2 秒延迟/冷却在随机位置生成对象(如敌人)。

我知道如何在随机坐标上生成它们。但我想知道的是,我如何能够生成多个对象,并且仍然跟踪其他已经在移动的对象,就像你在射击子弹时所做的那样一个游戏。

我可以通过使用pygame.time.get_ticks() 来解决时间延迟/冷却。所以我的主要问题是如何生成多个对象并使用 hitboxes 跟踪它们(我已经做了)

这是本例中生成小行星的基本部分。

class Enemy:
    asteroids = [pygame.image.load('rock0.png'), pygame.image.load('rock1.png'), pygame.image.load('rock2.png'),
                 pygame.image.load('rock3.png'), pygame.image.load('rock4.png')]

    def __init__(self, y, width, height):
        self.width = width
        self.height = height
        self.vel = 1.5
        self.x = random.randrange(screen_width - self.width * 2)
        self.y = y
        self.asteroid = random.choice(self.asteroids)

    def draw(self, win):
        self.move()
        win.blit(self.asteroid, (self.x, self.y))

    def move(self):
        self.y = self.y + self.vel

这里是所有需要它的人的完整代码。

import pygame

import random

pygame.init()

screen_width = 500
screen_height = 500
win = pygame.display.set_mode((screen_width, screen_height))
walk_left = [pygame.image.load('sprite_5.png'), pygame.image.load('sprite_6.png')]
walk_right = [pygame.image.load('sprite_3.png'), pygame.image.load('sprite_4.png')]
standing = [pygame.image.load('sprite_0.png'), pygame.image.load('sprite_1.png'), pygame.image.load('sprite_2.png')]


class Player:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 4
        self.left = False
        self.right = False
        self.standing = True
        self.walk_count = 0
        self.hitbox = (self.x + 2, self.y + 26, 123, 45)

    def draw(self, win):
        if self.walk_count + 1 >= 12:
            self.walk_count = 0

        if not self.standing:
            if self.left:
                win.blit(walk_left[self.walk_count // 6], (self.x, self.y))
                self.walk_count += 1
            elif self.right:
                win.blit(walk_right[self.walk_count // 6], (self.x, self.y))
                self.walk_count += 1
        else:
            win.blit(standing[self.walk_count // 4], (self.x, self.y))
            self.walk_count += 1
        self.hitbox = (self.x + 2, self.y + 26, 123, 45)
        pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)


def move():
    if keys[pygame.K_LEFT] and man.x > man.vel or keys[pygame.K_a] and man.x > man.vel:
        man.x -= man.vel
        man.left = True
        man.right = False
        man.standing = False

    elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:
        man.x += man.vel
        man.left = False
        man.right = True
        man.standing = False

    else:
        man.standing = True


class Enemy:
    asteroids = [pygame.image.load('rock0.png'), pygame.image.load('rock1.png'), pygame.image.load('rock2.png'),
                 pygame.image.load('rock3.png'), pygame.image.load('rock4.png')]

    number = [0, 1, 2, 3, 4]

    def __init__(self, y, width, height):
        self.width = width
        self.height = height
        self.vel = 1.5
        self.x = random.randrange(screen_width - self.width * 2)
        self.y = y
        self.index = random.choice(self.number)
        self.hitbox = (self.x, self.y, self.width, self.height)

    def draw(self, win):
        self.move()
        win.blit(self.asteroids[self.index], (self.x, self.y))
        if self.index == 0:
            self.hitbox = (self.x + 68, self.y + 68, self.width - 10, self.height - 14)
            pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
        elif self.index == 1:
            self.hitbox = (self.x + 38, self.y + 47, self.width + 20, self.height - 5)
            pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
        elif self.index == 2:
            self.hitbox = (self.x + 18, self.y + 12, self.width + 32, self.height + 30)
            pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
        elif self.index == 3:
            self.hitbox = (self.x + 20, self.y + 32, self.width + 16, self.height + 5)
            pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)
        else:
            self.hitbox = (self.x + 4, self.y + 7, self.width - 24, self.height - 31)
            pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)

    def move(self):
        self.y = self.y + self.vel

class Projectile:
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.vel = 5

    def draw(self, win):
        pygame.draw.rect(win, self.color, (self.x, self.y, self.height, self. width))


class Unit:
    def __init__(self):
        self.last = pygame.time.get_ticks()
        self.cooldown = 200

    def fire(self):
        now = pygame.time.get_ticks()
        if now - self.last >= self.cooldown:
            self.last = now
            spawn_bullet()


def spawn_bullet():
    if keys[pygame.K_SPACE]:
        bullets.append(Projectile((man.x + man.width // 2), (man.y - 7), 7, 3, (255, 0, 0)))


def re_draw():
    win.fill((0, 0, 0))
    asteroid.draw(win)
    man.draw(win)
    for bullet in bullets:
        bullet.draw(win)
    pygame.display.update()


delay = Unit()
man = Player(186, 400, 128, 128)
bullets = []
asteroid = Enemy(10, 64, 64)

run = True
clock = pygame.time.Clock()
while run:
    last = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    for bullet in bullets:
        if 0 < bullet.y < 500:
            bullet.y -= bullet.vel
        else:
            bullets.pop(bullets.index(bullet))

    keys = pygame.key.get_pressed()
    move()
    delay.fire()
    clock.tick(60)
    re_draw()

pygame.quit()

【问题讨论】:

【参考方案1】:

我建议使用计时器事件。使用pygame.time.set_timer() 在事件队列上重复创建事件。 使用pygame.sprite.Group 并从pygame.sprite.Sprite 派生Enemy 来管理多个敌人。请注意,在 sprite 中使用属性 .image.rect 很重要。例如:

class Enemy(pygame.sprite.Sprite):
    asteroids = [pygame.image.load('rock0.png'), pygame.image.load('rock1.png'), pygame.image.load('rock2.png'),
                 pygame.image.load('rock3.png'), pygame.image.load('rock4.png')]

    def __init__(self, y, width, height):
        super().__init__() 

        self.width = width
        self.height = height
        self.vel = 1.5
        x = random.randrange(screen_width - self.width * 2)
        self.image = random.choice(self.asteroids)
        self.rect = self.image.get_rect(center = (x, y))

    def move(self):
        self.rect.y += self.vel
enemies = pygame.sprite.Group()

my_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(my_event_id, 2000) # 2000 milliseconds = 2 seconds

run = True
while run:
    last = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        elif event.type == my_event_id:

            # spawn new enemy
            enemies.add(Enemy(10, 64, 64))

    # [...]

    for e in enemies:
        e.move()

    # [...]

    enemies.draw(win)

如果您将Projectile 设为pygame.sprite.Sprite,则可以使用bulletspygame.sprite.Group,然后您可以使用pygame.sprite.spritecollide()pygame.sprite.groupcollide() 来查找命中并杀死敌人。例如:

class Projectile(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color):
        super().__init__()

        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect(center = (x, y))
        self.vel = 5

    def move(self):
        self.rect.y -= self.vel

bullets = pygame.sprite.Group()

def spawn_bullet():
    if keys[pygame.K_SPACE]:
        bullets.add(Projectile((man.x + man.width // 2), (man.y - 7), 3, 7, (255, 0, 0)))
def re_draw():
    win.fill((0, 0, 0))
    enemies.draw(win)
    man.draw(win)
    bullets.draw(win)
    pygame.display.update()
while run:

    # [...]

   for e in enemies:
        e.move()
        if e.rect.y > 500:
            e.kill()
    for b in bullets:
        b.move()
        if 0 > b.rect.y or b.rect.y > 500:
            b.kill()

    pygame.sprite.groupcollide(bullets, enemies, True, True)

完整代码:

import pygame
import random

pygame.init()

screen_width = 500
screen_height = 500
win = pygame.display.set_mode((screen_width, screen_height))
walk_left = [pygame.image.load('sprite_5.png'), pygame.image.load('sprite_6.png')]
walk_right = [pygame.image.load('sprite_3.png'), pygame.image.load('sprite_4.png')]
standing = [pygame.image.load('sprite_0.png'), pygame.image.load('sprite_1.png'), pygame.image.load('sprite_2.png')]


class Player:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 4
        self.left = False
        self.right = False
        self.standing = True
        self.walk_count = 0
        self.hitbox = (self.x + 2, self.y + 26, 123, 45)

    def draw(self, win):
        if self.walk_count + 1 >= 12:
            self.walk_count = 0

        if not self.standing:
            if self.left:
                win.blit(walk_left[self.walk_count // 6], (self.x, self.y))
                self.walk_count += 1
            elif self.right:
                win.blit(walk_right[self.walk_count // 6], (self.x, self.y))
                self.walk_count += 1
        else:
            win.blit(standing[self.walk_count // 4], (self.x, self.y))
            self.walk_count += 1
        self.hitbox = (self.x + 2, self.y + 26, 123, 45)
        pygame.draw.rect(win, (255, 0, 0), self.hitbox, 2)


def move():
    if keys[pygame.K_LEFT] and man.x > man.vel or keys[pygame.K_a] and man.x > man.vel:
        man.x -= man.vel
        man.left = True
        man.right = False
        man.standing = False

    elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:
        man.x += man.vel
        man.left = False
        man.right = True
        man.standing = False

    else:
        man.standing = True


class Enemy(pygame.sprite.Sprite):
    asteroids = [pygame.image.load('rock0.png'), pygame.image.load('rock1.png'), pygame.image.load('rock2.png'),
                 pygame.image.load('rock3.png'), pygame.image.load('rock4.png')]

    def __init__(self, y, width, height):
        super().__init__() 

        self.width = width
        self.height = height
        self.vel = 1.5
        x = random.randrange(screen_width - self.width * 2)
        self.image = random.choice(self.asteroids)
        self.rect = self.image.get_rect(topleft = (x, y))

    def move(self):
        self.rect.y += self.vel

class Projectile(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color):
        super().__init__()

        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft = (x, y))
        self.vel = 5

    def move(self):
        self.rect.y -= self.vel

my_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(my_event_id, 2000) # 2000 milliseconds = 2 seconds


class Unit:
    def __init__(self):
        self.last = pygame.time.get_ticks()
        self.cooldown = 200

    def fire(self):
        now = pygame.time.get_ticks()
        if now - self.last >= self.cooldown:
            self.last = now
            spawn_bullet()


def spawn_bullet():
    if keys[pygame.K_SPACE]:
        bullets.add(Projectile((man.x + man.width // 2), (man.y - 7), 3, 7, (255, 0, 0)))


def re_draw():
    win.fill((0, 0, 0))
    enemies.draw(win)
    man.draw(win)
    bullets.draw(win)
    pygame.display.update()


delay = Unit()
man = Player(186, 400, 128, 128)

bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()

run = True
clock = pygame.time.Clock()
while run:
    last = pygame.time.get_ticks()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == my_event_id:

            # spawn new enemy
            enemies.add(Enemy(10, 64, 64))

    for e in enemies:
        e.move()
        if e.rect.y > 500:
            e.kill()
    for b in bullets:
        b.move()
        if 0 > b.rect.y or b.rect.y > 500:
            b.kill()

    pygame.sprite.groupcollide(bullets, enemies, True, True)

    keys = pygame.key.get_pressed()

    move()
    delay.fire()
    clock.tick(60)
    re_draw()

pygame.quit()

【讨论】:

你能添加一个完整的代码,以便我可以复制并粘贴它只是为了尝试它是否有效? @DenFulaAnkungen 我没有完整的代码。我可以给你一些建议来解决你的问题。这不是代码编写服务。 好的,非常感谢。只是在尝试使用您的代码时,.append 出现了一些错误。我想也许我做错了什么,但我不知道是什么。您对可能出现的问题有什么建议吗? 非常感谢。我希望我能找到我做错了什么。祝你有美好的一天!很高兴看到像你这样乐于助人的人

以上是关于如何在 pygame 中连续生成和跟踪多个具有时间延迟的随机对象? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在pygame中制作具有透明背景的表面

如何获取具有实际输入值的磁盘 IO 跟踪?

如何在 Pygame 中围绕偏离中心的枢轴旋转图像

Nhibernate id 具有连续一步递增的 id(HiLo 的替代品)

如何在一个表面上为 pygame 提供多个输入框并将这些输入存储在变量中? [复制]

OpenGL - 如何跟踪移动的物体? [关闭]