简体   繁体   English

有没有办法每 x 秒运行一个函数? (DPS)

[英]Is there a way to run a function every x seconds? (DPS)

My original Solution was from this Comment on a similar question.我原来的解决方案是从这个评论对类似的问题。 However, if I do that and implement this into different parts of my code, it stops counting up the in-game Counter of CASH.但是,如果我这样做并将其实现到我的代码的不同部分,它会停止计算 CASH 的游戏内计数器。

CASH = 0
DPS = 5
HPofMonster = 10
starttime=time.time()

def handle_monster():
    global HPofMonster, CASH
    if pygame.mouse.get_focused():
        event = pygame.event.poll()
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
            HPofMonster -= 1
            print('click')
            pass
        else:
            print('Not Pushed OR not on Monster')
            pass
    else:
        print('Mouse not focused')
        pass
    if HPofMonster < 0:
        CASH += 5
        HPofMonster = 10
        print('reset')

def handle_dps():
    global HPofMonster
    HPofMonster -= DPS
    print("tick")
    time.sleep(1.0 - ((time.time() - starttime) % 1.0))


def game_loop():
    while True:
        handle_dps()
        handle_monster()
        update_text()
        handle_events()



def main():
    pygame.display.set_caption('Clicker')
    game_loop()


main()

When I don´t move my Mouse, my console looks like this:当我不移动鼠标时,我的控制台看起来像这样:

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

reset重启

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

reset重启

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

tick打钩

Not Pushed OR not on Monster不推或不在怪物上

reset重启

Mouse not focused鼠标未聚焦

Process finished with exit code 0进程以退出代码 0 结束

Here is the entire code:这是整个代码:

import pygame, threading, time

from threading import Event, Thread
from pygame.locals import *


pygame.init()

WIDTH = 800
HEIGHT = 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
CASH = 0
DPS = 5
HPofMonster = 10
BACKGROUND_COLOR = (0, 0, 0)
BUTTON_COLOR = (0, 255, 0)
starttime=time.time()

FONT = pygame.font.SysFont('monospace', 15)

# Main Screen for drawing buttons
DRAW_SCREEN = pygame.Surface((WIDTH, HEIGHT))
DRAW_SCREEN.fill(BACKGROUND_COLOR)

# Buttons
GEN1 = pygame.draw.rect(DRAW_SCREEN, BUTTON_COLOR, pygame.Rect(200, 200, 200, 200), 1)
GEN1_LABEL = FONT.render('Defeat the Monster', 1, (255, 255, 0))


def handle_monster():
    global HPofMonster, CASH
    if pygame.mouse.get_focused():
        event = pygame.event.poll()
        mouse_x, mouse_y = pygame.mouse.get_pos()
        if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
            HPofMonster -= 1
            print('click')
            pass
        else:
            print('Not Pushed OR not on Monster')
            pass
    else:
        print('Mouse not focused')
        pass
    if HPofMonster < 0:
        CASH += 5
        HPofMonster = 10
        print('reset')


def handle_events():
    event_dict = {
        pygame.QUIT: exit,
    }
    for event in pygame.event.get():
        if event.type in event_dict:
            event_dict[event.type]()


def update_text():
    global CASH_LABEL, DPS_LABEL, GEN1_LABEL, DPS, CASH
    WINDOW.blit(DRAW_SCREEN, (0, 0))
    WINDOW.blit(GEN1_LABEL, (10, 108))
    CASH_LABEL = FONT.render('Total Cash: ${}'.format(CASH), 1, (255, 255, 0))
    DPS_LABEL = FONT.render('Total DPS: ${}'.format(DPS), 1, (255, 65, 0))
    WINDOW.blit(CASH_LABEL, (0, 0))
    WINDOW.blit(DPS_LABEL, (0, 20))
    pygame.display.flip()


def handle_dps():
    global HPofMonster
    HPofMonster -= DPS
    print("tick")


def game_loop():
    while True:
        handle_dps()
        handle_monster()
        update_text()
        handle_events()



def main():
    pygame.display.set_caption('Clicker')
    game_loop()


main()

Do not use time.sleep() in a event-driven program.不要在事件驱动程序中使用time.sleep() It blocks the event-loop, and on some systems the window manager or outlying operating system will consider the program to have stopped and/or crashed.它会阻止事件循环,并且在某些系统上,窗口管理器或外围操作系统会认为程序已停止和/或崩溃。 The program must continually process incoming events.程序必须不断地处理传入的事件。

An easy way to do this in pygame is to use the real-time system clock function pygame.time.get_ticks() which returns the number of milliseconds since the program started, and it keeps increasing forever .在 pygame 中执行此操作的一种简单方法是使用实​​时系统时钟函数pygame.time.get_ticks() ,它返回自程序启动以来的毫秒数,并且它会永远增加。 If you want something to trigger in the future, set a timestamp like:如果您希望将来触发某些事情,请设置一个时间戳,例如:

future_timestamp = pygame.time.get_ticks() + 15000   # 15 seconds from now

...

# somewhere else in the code, maybe in the main loop
time_now = pygame.time.get_ticks()
if ( future_timestamp < time_now ):
    # do the thing that had to happen
    do_that_thing()
    # re-set the timer for next time
    future_timestamp = time_now + 15000

Another simple way to implement something that happens periodically is to setup a pygame timer:实现定期发生的事情的另一种简单方法是设置一个 pygame 计时器:

pygame.time.set_timer( pygame.USEREVENT + 1, 3500 )   # Cash every 3500 milliseconds

# Main Loop 
while not exiting:
    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
           done = True
        elif ( event.type == pygame.USEREVENT + 1 ):
           CASH += 1   
           # reset the event-timer
           pygame.time.set_timer( pygame.USEREVENT + 1, 3500 )

Instead of time.sleep use pygame.time.delay() or pygame.time.wait() .取而代之的time.sleep使用pygame.time.delay()pygame.time.wait()

Here is the link of official pygame time events: https://www.pygame.org/docs/ref/time.html这里是官方pygame时间事件的链接: https : //www.pygame.org/docs/ref/time.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM