如何在时间限制后生成精灵以及如何显示计时器 pygame [英] how to spawn a sprite after a time limit and how to display a timer pygame

查看:79
本文介绍了如何在时间限制后生成精灵以及如何显示计时器 pygame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在经过一段时间或产生 x 数量的怪物后产生一个老板"精灵,我如何在屏幕上显示计时器.

i would like to spawn a 'boss' Sprite after a certain time has passed or x amount of mobs have spawned and how could i display the timer on the screen.

图片

当前代码

给老板上课

class Boss(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.transform.scale(boss_img, (150, 200))
    self.image.set_colorkey(Black)
    self.rect = self.image.get_rect()
    self.rect.center = ((Width / 2, -70))
    self.speedy = 1
    self.shoot_delay = 250
    self.last_shot = pygame.time.get_ticks()
    self.hp = 150
    self.dead = False

def update(self):
    if self.hp <= 25:
        self.speedy = 3
    if self.rect.top > Height + 10:
        player.lives = 0

推荐答案

在 pygame 中有多种实现计时器的方法.您可以使用 pygame.Clock.tick 返回的时间来增加或减少计时器变量,使用 pygame.time.get_ticks 计算时间差或使用自定义事件与 pygame.time.set_timer 结合使用.

There are several ways to implement a timer in pygame. You can use the time that pygame.Clock.tick returns to increase or decrease a timer variable, calculate the time difference with pygame.time.get_ticks or use a custom event in conjunction with pygame.time.set_timer.

示例 1 - 增量时间:

import sys
import random
import pygame as pg


class Block(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((40, 40))
        self.image.fill(pg.Color('sienna1'))
        self.rect = self.image.get_rect(topleft=pos)


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    all_sprites = pg.sprite.Group()
    # Delta time is the time that has passed since clock.tick
    # was called the last time.
    dt = 0
    # We'll subtract dt (delta time) from this timer variable.
    timer = 1  # 1 means one second.

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        # Decrease timer to get a countdown.
        timer -= dt
        # When the timer is below or equal to 0, we spawn
        # a new block.
        if timer <= 0:
            all_sprites.add(Block((random.randrange(600),
                                  random.randrange(440))))
            # Reset the countdown timer to one second.
            timer = 1
        all_sprites.update()
        screen.fill(pg.Color('gray15'))
        all_sprites.draw(screen)
        timer_surface = font.render(
            str(round(timer, 3)), True, pg.Color('yellow'))
        screen.blit(timer_surface, (20, 20))

        pg.display.flip()
        # dt = time in seconds that passed since last tick.
        # Divide by 1000 to convert milliseconds to seconds.
        dt = clock.tick(30) / 1000


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()

如果你想生成 1 个精灵,你可以添加另一个变量,如 boss_spawned = False 并仅在 Boss 没有生成时更改计时器:

If you want to spawn exactly 1 sprite, you can add another variable like boss_spawned = False and change the timer only if the boss hasn't spawned:

if not boss_spawned:
    timer -= dt
    if timer <= 0:
        all_sprites.add(Block((random.randrange(600),
                               random.randrange(440))))
        boss_spawned = True

或者在生成后将计时器设置为 0,并且仅在 != 0 时才减少计时器.

Or set the timer to exactly 0 after the spawn and only decrease the timer if it's != 0.

if timer != 0:
    timer -= dt
    if timer <= 0:
        all_sprites.add(Block((random.randrange(600),
                               random.randrange(440))))
        timer = 0

示例 2 - pygame.time.get_ticks(替换上面的 main 函数):

Example 2 - pygame.time.get_ticks (replace the main function above):

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    all_sprites = pg.sprite.Group()
    # Start time.
    now = pg.time.get_ticks()
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        # If the time difference is greater than 1000
        # milliseconds, spawn a block.
        time_difference = pg.time.get_ticks() - now
        if time_difference >= 1000:
            all_sprites.add(Block((random.randrange(600),
                                  random.randrange(440))))
            # Reset the start time.
            now = pg.time.get_ticks()
        all_sprites.update()
        screen.fill(pg.Color('gray15'))
        all_sprites.draw(screen)
        timer_surface = font.render(
            str(time_difference/1000), True, pg.Color('yellow'))
        screen.blit(timer_surface, (20, 20))

        pg.display.flip()
        clock.tick(30)

如果您只想计算击杀数或生成的怪物,您可以增加一个计数器变量,然后在超过某个限制时生成敌对 Boss.以下示例仅计算鼠标点击次数并在点击 3 次后生成一个块.

If you just want to count the kills or spawned mobs, you can increment a counter variable and then spawn the enemy boss when it exceeds some limit. The following example just counts the mouse clicks and spawns a block after 3 clicks.

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    all_sprites = pg.sprite.Group()
    # We'll just count mouse clicks in this example.
    # You can replace it with the kill count in your game.
    clicks = 0
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                clicks += 1

        if clicks >= 3:
            all_sprites.add(Block((random.randrange(600),
                                   random.randrange(440))))
            clicks = 0
        all_sprites.update()
        screen.fill(pg.Color('gray15'))
        all_sprites.draw(screen)
        clicks_surface = font.render(str(clicks), True, pg.Color('yellow'))
        screen.blit(clicks_surface, (20, 20))

        pg.display.flip()
        clock.tick(30)

这篇关于如何在时间限制后生成精灵以及如何显示计时器 pygame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆