Timer in python reset [duplicate] - python

This question already has answers here:
How to run multiple while loops at a time in Pygame
(1 answer)
Issues with pygame.time.get_ticks() [duplicate]
(1 answer)
Closed 1 year ago.
Hey i am trying to get a timer for my game how do i reset this
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
thank you all for helping =)

Your timer starts at the time stored in the variable start_ticks. If you want to rest the timer, you must therefore set a new value for the start_ticks variable. Assign the current time (pygame.time.get_ticks()) to start_ticks when the timer needs to be reset:
start_ticks = pygame.time.get_ticks()
while mainloop:
seconds = (pygame.time.get_ticks() - start_ticks)/1000
if seconds > 10:
start_ticks = pygame.time.get_ticks()

Related

Why is the explosion showing immediately? [duplicate]

This question already has answers here:
How to wait some time in pygame?
(3 answers)
Closed 18 days ago.
I am trying to handle the collision with shot and asteroid, but after the collision I want to add an explosion.
I added a timer so the explosion is going to show on the screen after some time, but the the explosion shows immediately, and I dont see the problem. This is the function with the problem in my code.
def handle_collision_with_shot_asteroid(self):
for asteroid_rect in self.asteroid_list:
for shot_rect in self.shots:
# check for collision
if asteroid_rect.colliderect(shot_rect):
# remove the shot and the asteroid from the screen
self.asteroid_list.remove(asteroid_rect)
self.shots.remove(shot_rect)
# create an effect after the asteroid get shot
explosion_rect = self.explosion_big.get_rect(center=(asteroid_rect.x+29, asteroid_rect.y+29))
# record the time the explosion started
self.explosion_start_time = pygame.time.get_ticks()
try:
if pygame.time.get_ticks() - self.explosion_start_time > 1000:
# show the explosion
screen.blit(self.explosion_big, explosion_rect)
# Reset the explosion start time so it doesn't show again
self.explosion_start_time = 0
except:
pass
I believe that you should be doing something like
if pygame.time.get_ticks() - self.explosion_start_time > 2000:
Also check if the api for ticks() returns what you expect it to.
i fix it with this code:
def handle_collision_with_shot_asteroid(self):
for asteroid_rect in self.asteroid_list:
for shot_rect in self.shots:
# check for collision
if asteroid_rect.colliderect(shot_rect):
# remove the shot and the asteroid from the screen
self.asteroid_list.remove(asteroid_rect)
self.shots.remove(shot_rect)
# record the time the explosion started
self.explosion_start_time = pygame.time.get_ticks()
# defined the x,y of the explosion
self.x,self.y = asteroid_rect.x-20, asteroid_rect.y+15
if self.explosion_start_time:
if pygame.time.get_ticks() - self.explosion_start_time > 200:
# show the explosion
screen.blit(self.explosion_big, (self.x,self.y))
# Reset the explosion start time so it doesn't show again
self.explosion_start_time = 0

How to make countdown timer in Python without input?

Iv'e been trying to create a countdown timer for a game in python however i'm not sure how to code it without including the input question for the time at the beginning of the code.
So far the code looks like this
import time
import datetime
# Create class that acts as a countdown
def countdown(s):
# Calculate the total number of seconds
total_seconds = s
# While loop that checks if total_seconds reaches zero
# If not zero, decrement total time by one second
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
# Prints the time left on the timer
print(timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("You have been caught.")
# Inputs for hours, minutes, seconds on timer
s = input("Enter the time in seconds: ")
countdown(int(s))
exit()
I want to make the code so it has an automatic countdown for 10 seconds as soon as the user presses enter. Any ideas?
If I understand your question correctly you just want the user to press the enter key instead of actually inputing a number? then you can just hard code the time value and call the function with that value, while using an empty input call to wait for a keypress.
input("Press enter to continue...")
countdown(10)
exit()
here you're not storing the value from input anywhere and just using the input function to block until the user presses enter.
You could do it this way:
import time
def countdown(time_sec):
while time_sec:
minutes, secs = divmod(time_sec, 60)
time_format = f'{minutes}:{secs}'
print(time_format, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)

Python how to freeze program? [duplicate]

This question already has an answer here:
How to start/stop a Python function within a time period (ex. from 10 am to 12:30pm)?
(1 answer)
Closed 2 years ago.
Note: read my comments on the provided answer, it doesn't work
I have a python program which runs every 5 seconds like this:
def main():
start_time = time.time()
while True:
if not execute_data():
break
time.sleep(5.0 - ((time.time() - start_time) % 5.0))
The question is how can I make it run from 7:00 to 23:00 only? I don't want to use my computer resources at times where I'm sure my program won't be helpful...
You can use datetime.datetime.strptime() and datetime.datetime.strftime():
from datetime import datetime
import time
def str_to_time(string):
return datetime.strptime(string, "%H:%M")
def main():
start = '7:00'
end = '23:00'
while True:
now = str_to_time(datetime.now().strftime("%H:%M"))
if str_to_time(end) > now > str_to_time(start) or str_to_time(end) < now < str_to_time(start):
print('Working...')
time.sleep(5)
main()

Implementing a timer(countdown) that runs pararell with the game logic [duplicate]

This question already has answers here:
How to set time limit on raw_input
(7 answers)
Closed 6 years ago.
I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.
At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.
Here is an idea with pseudo code:
if (answer = wrong || time = 0)
lost...
if you want to check if the user took to long when he answered you can use the time module to calculate the diffrence:
start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
lose()
if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:
timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
lose()

pygame: current time millis and delta time

As you can see in the below code I have a basic timer system
done = False
clock = pygame.time.Clock()
# Create an instance of the Game class
game = space_world.SpaceWorld()
# Main game loop
while not done:
# Process events (keystrokes, mouse clicks, etc)
done = game.process_events()
# Update object positions, check for collisions...
game.update()
# Render the current frame
game.render(screen)
# Pause for the next frame
clock.tick(30)
My question is, how can I get the current time milli seconds and how do I create delta time, so I can use it in the update method ?
ms = clock.tick(30)
The function returns milliseconds since the previous call.
From the documentation: pygame.time.Clock.get_time will return the number of milliseconds between the previous two calls to Clock.tick.
There is also pygame.time.get_ticks which will return the number of milliseconds since pygame.init() was called.
Delta-time is simply the amount of time that passed since the last frame, something like:
t = pygame.time.get_ticks()
# deltaTime in seconds.
deltaTime = (t - getTicksLastFrame) / 1000.0
getTicksLastFrame = t

Categories

Resources