如何使每隔X秒随机发生的事情?

时间:2019-05-17 14:49:26

标签: python python-3.x pygame

我制定了一些代码,每当玩家在一定范围内时,敌人就会射击,但我不喜欢它的工作方式。现在,我正在尝试使其随机以(1,10)/ s的速度发生。

我知道这与导入时间有关。但是我被困在那里。有人能帮忙吗?

clock = pygame.time.Clock()
class Enemy1():
    global win
    def __init__(self,x,y,end,width = 30,height = 30,color = (220,100,100)):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.end = end
        self.path = [self.x, self.end]
        self.speed = 2     
        self.hitbox = [self.x, self.y,self.width,self.height]
        self.health = 300
        self.alive = True


    def draw(self, win):
            self.movement()
            pygame.draw.rect(win,self.color,(self.hitbox))

    def movement(self):

        if self.speed > 0:
            if self.hitbox[0] < self.path[1]+ self.speed:
                self.hitbox[0] += self.speed
                self.x += self.speed
            else:
                self.speed = self.speed * -1
                self.hitbox[0] += self.speed
                self.x += self.speed
        else:
            if self.hitbox[0]> self.path[0] - self.speed:
                self.hitbox[0] += self.speed
                self.x += self.speed
            else:
                self.speed = self.speed * -1
                self.hitbox[0] += self.speed
                self.x += self.speed
    def hit(self):

        if self.health > 0:
            if self.health - 15 >= 0:
                self.health -= 15
            else:
                self.health = 0
        else:
            self.alive = False

    def enemyhealth(self):
        myfont = pygame.font.SysFont('Arial', 15)
        text = myfont.render('Enemy Health: {}'.format(str(round(self.health))), 0, (255, 255, 255))
        win.blit(text,(10,10))

class EnemyShots():
    def __init__(self,x,y,radius,color):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color
        self.speed = 30
    def draw(self,win):
        pygame.draw.circle(win,self.color, (self.x, self.y), self.radius)

灌肠= =]

在主循环中:

clock.tick(27)
    if enemy1.x >= player.x - 10 and enemy1.x <= player. x + 40:
        if len(enemybullets) < 1:
            enemybullets.append(EnemyShots(round(enemy1.x+ 15), round(enemy1.y + 35),3,(255,0,0)))

3 个答案:

答案 0 :(得分:0)

您可以像这样在update()类中添加到Enemy例程中:

class Enemy():
    self.FramesUntilNextShot = random(1,10)
    def update():
        self.FramesUntilNextShot -=1
        if(self.FramesUntilNextShot <= 0):
            self.FramesUntilNextShot = random(1,10)
            self.ShootANewBullet()

假设您具有恒定的FPS(可能足以满足您的目的),则可以以1/FPS为单位FramesUntilNextShot中测量到下一次随机拍摄的时间。然后,当它达到0时,您进行拍摄并将其再次设为随机数。

答案 1 :(得分:0)

在游戏循环中使用time.sleep()将使其失去作用。

您可以记住下一张照片的时间,并在这段时间过去时进行拍摄,然后创建一个新的照片:

from random import randint
from datetime import datetime, timedelta

def shoot(now):
    print("BOING:", now)


# demonstation purpose game loop, runs until 3 shots are fired
def gameloop():  
    next_shot = datetime.now()
    i = 3
    # runs until i == 0
    while i:
        # do stuff 
        # do more stuff 
        # check if we need to shoot again
        if datetime.now() > next_shot:
            shoot(next_shot)
            i -= 1
            # create next shoot time using now() + 1 to 10 seconds
            next_shot = datetime.now() + timedelta(seconds=randint(1,10))

gameloop() 

输出:

BOING: 2019-05-17 15:12:03.074492
BOING: 2019-05-17 15:12:09.074579
BOING: 2019-05-17 15:12:18.074620

这具有不需要恒定FPS的魅力-一旦经过下一个拍摄时间,下一个镜头就会被发射。

答案 2 :(得分:0)

您可以使用任何计时器:

import time
import random
timer1sec = 0

def myfunc():
    # your code here
    global timer1sec 
    timer1sec = time.time()  # reset our timer

# main pygame loop
while True:
    if time.time() - timer1sec >= random.randint(0,10):   # if RANDOM seconds passed
        myfunc()

    # rest of pygame code here