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 = 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
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. 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. 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.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().
Here is the link of official pygame time events: https://www.pygame.org/docs/ref/time.html
Related
def playermove(self,dice_status):
self._position += dice_status
'''i want to Add some pauses at each step so
it doesn't look like it flashed past'''
def playerlocate(self,screen):
if self._position <= 19:
screen.blit(self._image, mapCoordinate[self._position])
elif 19 < self._position <= 30:
screen.blit(pygame.transform.rotate(self._image,-90),mapCoordinate[self._position])
elif 30 < self._position <= 48:
screen.blit(pygame.transform.rotate(self._image, -180), mapCoordinate[self._position])
elif 48 < self._position <= 54:
screen.blit(pygame.transform.rotate(self._image, -270), mapCoordinate[self._position])
else:
screen.blit(pygame.transform.rotate(self._image, -270), mapCoordinate[self._position-55])
self._position -= 55
mapCoordinate=[[1184,773],[971,873],...] #I have 55 map grids
#self._position is a attribute of the player,It corresponds to the serial number of each grid on the map.And I also have a function to convert _position to coordinates and draw the player on the map.
I tried to add some time control but I don't know how to do it.Please
If you want to control something over time in Pygame you have two options:
Use pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.
e.g.:
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_step_time = 0
while run:
# [...]
current_time = pygame.time.get_ticks()
if current_time > next_step_time :
next_step_time += time_interval
# move object
player.playermove(dice_status)
Use the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.
e.g.:
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
while run:
for event in pygame.event.get():
if event.type == timer_event:
# move object
player.playermove(dice_status)
See also Spawning multiple instances of the same object concurrently in python
Minimal examples:
Example 1:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 200))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 80, 40, 40)
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_step_time = 0
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
current_time = pygame.time.get_ticks()
if current_time > next_step_time :
next_step_time += time_interval
rect.x += 40
if rect.x >= 400:
rect.x = 0
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
clock.tick(100)
pygame.quit()
exit()
Example 2:
import pygame
pygame.init()
window = pygame.display.set_mode((400, 200))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 80, 40, 40)
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == timer_event:
rect.x += 40
if rect.x >= 400:
rect.x = 0
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
clock.tick(100)
pygame.quit()
exit()
One way would be to keep a counter in the loop, and based on the value of the counter you can update the position of the object. This can effectively slow down the movement of the object.
You can do this by defining a counter variable at the beginning - before the loop.
Then update the value of the counter in every iteration.
After that, in the place where you update the position of the object, check for the value of the counter.
For example:-
if counter > 5: #you can increase or decrease the value... here I have taken 5
self.position += dice_status
counter = 0
You also have to change the value of the counter back to zero in the 'if' block.
Instead of 5 if you take a greater value, it will make the object even more slower.
I've been trying to make a Chrome Dino Game, however, I'm struggling with this problem:
On every frame, it should draw a new one at the new position and delete the previous one to make it look as if it's moving. HOWEVER, it remains at its previous position and a new image appears on its next position. I did write the pygame.display.update() code at the end of my maintop.
In the last time I ran into a similar problem, I managed to make it work by drawing a background image, but this time, it doesn't work.
following are my codes:
import pygame
import os
from random import randint
import schedule
pygame.init()
assets = os.path.join(os.path.dirname(__file__), "Assets")
screen_size = (screen_width, screen_height) = (1280, 720)
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
fps = 120
bg = pygame.image.load(os.path.join(assets, "IMG_15.png"))
ground = 700
running = True
spacebaridx = 0
gamestart = False
tick_on_start = 0
obs1 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs1, (100, 200))
obs2 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs2, (120, 200))
obs3 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs3, (150, 200))
ls_obs = []
def create_obs():
k = randint(1, 3)
if k == 1:
info = {"type":1, "img":obs1, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
if k == 2:
info = {"type":2, "img":obs2, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
else:
info = {"type":3, "img":obs3, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
schedule.every(3).seconds.do(create_obs)
while running:
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()
This issue is occurring because you aren't clearing the display within each frame. In pygame, in order to clear the display, we need to use the fill method. So in your code, at the top of your game loop before the event loop, add screen.fill((0, 0, 0)). This will fill your screen in the color black. Don't worry, the black won't be shown if you draw the background on top of it. Now, when you add a new image, the previous images won’t be displayed.
Modified Game Loop
while running:
screen.fill((0, 0, 0))
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()
I'm trying to do a small school project it's very simple and basically, all you do is click on randomly appearing donuts on the screen each click gives a point and everything is ok up until there, I tried to do a timer that will reset when you click on a donut each time so basically, you have around 1.5 seconds between each click and if you run out of time you lose a life but I can't figure out how to implement a timer that will run between clicks on the donut and reset each time you click, I searched all across the internet and found nothing can someone please help.
donut_width, donut_height = 110, 95
score = 0
lives = 4
class Donut:
def __init__(self, x, y):
self.donut_original = pygame.image.load(os.path.join('icon.png'))
self.donutImg = pygame.transform.scale(self.donut_original, (donut_width, donut_height))
self.donut = self.donutImg.get_rect()
self.donut.x = x
self.donut.y = y
def draw(self):
screen.blit(self.donutImg, self.donut)
def collision(donut1, mouse):
return donut1.collidepoint(mouse)
donut = Donut(width//2, height//2)
def graphics():
screen.fill(uwred)
donut.draw()
text_score = pygame.font.SysFont('comicsans', 80).render('SCORE: ' + str(score), True, white)
screen.blit(text_score, (0, 0))
run = True
out_of_time = False
while run:
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if collision(donut.donut, mouse_pos) and event.type == pygame.MOUSEBUTTONDOWN:
donut.donut.x = random.randint(donut_width * 2, width - donut_width * 2)
donut.donut.y = random.randint(donut_height * 2, height - donut_height * 2)
score += 1
graphics()
pygame.display.update()
pygame.quit()
You can try using the time.time() method:
import pygame
from time import time
pygame.init()
wn = pygame.display.set_mode((600, 600))
class Button:
def __init__(self):
self.rect = pygame.Rect(250, 250, 100, 100)
self.color = (255, 0, 0)
def clicked(self, pos):
return self.rect.collidepoint(pos)
def draw(self):
pygame.draw.rect(wn, self.color, self.rect)
button = Button()
score = 0
t = time()
while True:
if time() - t > 1.5:
score -= 1
t = time()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button.clicked(event.pos):
score += 1
t = time()
wn.fill((255, 255, 255))
button.draw()
pygame.display.update()
print(score)
Explanation:
Import the necessary modules and function:
import pygame
from time import time
Initialize the pygame module and create a pygame window:
pygame.init()
wn = pygame.display.set_mode((600, 600))
Define the most basic Button class as an example for the object to click:
class Button:
def __init__(self):
self.rect = pygame.Rect(250, 250, 100, 100)
self.color = (255, 0, 0)
def clicked(self, pos):
return self.rect.collidepoint(pos)
def draw(self):
pygame.draw.rect(wn, self.color, self.rect)
Create a Button from the class defined above:
button = Button()
Define a variable, t, to be the score, and a variable, score, to be the current time in seconds:
score = 0
t = time()
In the while loop, check if the current time during that iteration of the while loop is more than 1.5 seconds greater than the t variable defined. If so, decrement 1 from the score variable and reset the t variable to be the current time:
while True:
if time() - t > 1.5:
score -= 1
t = time()
Use a for loop to loop over the pygame events to check for an exit event:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
If the button is clicked, increment the score variable by 1 and reset the t variable to be the current time:
elif event.type == pygame.MOUSEBUTTONDOWN:
if button.clicked(event.pos):
score += 1
t = time()
Finally, draw the button, and print the score to see it working:
wn.fill((255, 255, 255))
button.draw()
pygame.display.update()
print(score)
Use pygame.time.get_ticks to get the number of milliseconds since pygame.init() was called.
Set the start time when a new donut appears. Calculate the difference between the current time and the start time. Decrease the number of lives if the difference exceeds the limit:
lives = 4
start_time = pygame.time.get_ticks()
run = True
while run:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and collision(donut.donut, event.pos) and :
donut.donut.x = random.randint(donut_width * 2, width - donut_width * 2)
donut.donut.y = random.randint(donut_height * 2, height - donut_height * 2)
score += 1
start_time = current_time
delta_time = current_time - start_time
if delta_time > 1500: # 1.5 sceonds
lives -= 1
start_time = current_time
print("lives:", lives)
graphics()
pygame.display.update()
This question already has answers here:
Countdown timer in Pygame
(8 answers)
How do I use a PyGame timer event? How to add a clock to a pygame screen using a timer?
(1 answer)
How do I continuously trigger an action at certain time intervals? Enemy shoots constant beam instead of bullets in pygame [duplicate]
(1 answer)
How can one continuously generate and track several random objects with a time delay in pygame? [duplicate]
(1 answer)
Closed 4 years ago.
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.
Images
Current Code
class for boss
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
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.
Example 1 - delta time:
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()
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
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
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)
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)
I started using pygame and I want to do simple game. One of the elements which I need is countdown timer.
How can I do the countdown time (eg 10 seconds) in PyGame?
Another easy way is to simply use pygame's event system.
Here's a simple example:
import pygame
pygame.init()
screen = pygame.display.set_mode((128, 128))
clock = pygame.time.Clock()
counter, text = 10, '10'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.SysFont('Consolas', 30)
run = True
while run:
for e in pygame.event.get():
if e.type == pygame.USEREVENT:
counter -= 1
text = str(counter).rjust(3) if counter > 0 else 'boom!'
if e.type == pygame.QUIT:
run = False
screen.fill((255, 255, 255))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
pygame.display.flip()
clock.tick(60)
On this page you will find what you are looking for http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks
You download ticks once before beginning the countdown (which can be a trigger in the game - the key event, whatever).
For example:
start_ticks=pygame.time.get_ticks() #starter tick
while mainloop: # mainloop
seconds=(pygame.time.get_ticks()-start_ticks)/1000 #calculate how many seconds
if seconds>10: # if more than 10 seconds close the game
break
print (seconds) #print how many seconds
In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:
timer_interval = 500 # 0.5 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event , timer_interval)
Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
To disable the timer for an event, set the milliseconds argument to 0.
Receive the event in the event loop:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == timer_event:
# [...]
The timer event can be stopped by passing 0 to the time parameter.
See the example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 10
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
pygame.display.flip()
pygame.time.Clock.tick returns the time in milliseconds since the last clock.tick call (delta time, dt), so you can use it to increase or decrease a timer variable.
import pygame as pg
def main():
pg.init()
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 40)
gray = pg.Color('gray19')
blue = pg.Color('dodgerblue')
# The clock is used to limit the frame rate
# and returns the time since last tick.
clock = pg.time.Clock()
timer = 10 # Decrease this to count down.
dt = 0 # Delta time (time since last tick).
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
timer -= dt
if timer <= 0:
timer = 10 # Reset it to 10 or do something else.
screen.fill(gray)
txt = font.render(str(round(timer, 2)), True, blue)
screen.blit(txt, (70, 70))
pg.display.flip()
dt = clock.tick(30) / 1000 # / 1000 to convert to seconds.
if __name__ == '__main__':
main()
pg.quit()
There are several ways you can do this- here's one. Python doesn't have a mechanism for interrupts as far as I know.
import time, datetime
timer_stop = datetime.datetime.utcnow() +datetime.timedelta(seconds=10)
while True:
if datetime.datetime.utcnow() > timer_stop:
print "timer complete"
break
There are many ways to do this and it is one of them
import pygame,time, sys
from pygame.locals import*
pygame.init()
screen_size = (400,400)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("timer")
time_left = 90 #duration of the timer in seconds
crashed = False
font = pygame.font.SysFont("Somic Sans MS", 30)
color = (255, 255, 255)
while not crashed:
for event in pygame.event.get():
if event.type == QUIT:
crashed = True
total_mins = time_left//60 # minutes left
total_sec = time_left-(60*(total_mins)) #seconds left
time_left -= 1
if time_left > -1:
text = font.render(("Time left: "+str(total_mins)+":"+str(total_sec)), True, color)
screen.blit(text, (200, 200))
pygame.display.flip()
screen.fill((20,20,20))
time.sleep(1)#making the time interval of the loop 1sec
else:
text = font.render("Time Over!!", True, color)
screen.blit(text, (200, 200))
pygame.display.flip()
screen.fill((20,20,20))
pygame.quit()
sys.exit()
This is actually quite simple. Thank Pygame for creating a simple library!
import pygame
x=0
while x < 10:
x+=1
pygame.time.delay(1000)
That's all there is to it! Have fun with pygame!
Another way to do it is to set up a new USEREVENT for a tick, set the time interval for it, then put the event into your game loop
'''
import pygame
from pygame.locals import *
import sys
pygame.init()
#just making a window to be easy to kill the program here
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("tick tock")
#set tick timer
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
if event.type == tick:
## do whatever you want when the tick happens
print('My tick happened')