使图像随机出现并在一定时间后消失

时间:2016-12-15 17:56:24

标签: python pygame

我对如何解决这个问题感到非常困惑,我无法让它发挥作用。所以,如果你曾经玩蛇,你会记得在某些时候会出现一个图像,如果你吃了它,你会获得更多的分数,但是如果你错过它,它就会消失(即不会永远呆在那里直到你抓住它。 )

我编写的代码与时间一致(允许你激活一个盾牌),如下所示:

if (count % 35 == 0):

    ang = random.choice(angles)
    particles.append(Particle(red, 5, ang, user))
    score += 10
    score_graphic = font.render("Score " + str(score), 1, white)

    total_shields += 1

    if total_shields > 10:
        total_shields = 10

count += 1

curr_time = time.time()

if space_press:
    if (curr_time - new_time) > 0.3:
        new_time = time.time()
        total_shields -= 1

    shield_on = total_shields > 0

如何在pygame中实现消失的图像? 我知道这是非常规的,但如果你能提供帮助,我会很感激,因为我在过去的一小时里一直无法做到这一点。

最佳, 赛义德

1 个答案:

答案 0 :(得分:0)

使用时间为start showingend showing的变量。

控制游戏中不同元素的流行方法。

import pygame
import random

# - init -

pygame.init()

screen = pygame.display.set_mode((800, 600))

# - objects -

display_apple = False
start_showing = None
end_showing = None

current_time = pygame.time.get_ticks()

# show first time 
start_showing = current_time + random.randint(1,5)*1000

# - mainloop -

clock = pygame.time.Clock()

running = True

while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # - updates -

    current_time = pygame.time.get_ticks()

    if display_apple:
        # is it time to hide ?
        if end_showing and current_time >= end_showing:
            # hide it
            display_apple = False
            end_showinge = False
            # set time when to show
            start_showing = current_time + random.randint(1,5)*1000
    else:
        # is it time to show ?
        if start_showing and current_time >= start_showing:
            # show it
            display_apple = True
            start_showing = False
            # set time when to hide
            end_showing = current_time + random.randint(1,5)*1000

    # - draws -

    screen.fill((0,0,0))

    if display_apple:
        pygame.draw.rect(screen, (255,0,0), (0,0,100,100))

    pygame.display.flip()

    # - FPS -

    clock.tick(30)

# - end -

pygame.quit()