I'm working on a game that is sort of like a simple Galaga-esk game. Although, they only move once in a while (something else I can't get working, but that's something different). So, since they don't move on their own, I want a way to add a timer to the game, but I can't seem to find anything on this. Here's what I have for my timer and the surrounding code to reset for each level so far. Will something like this work where I have it?
from livewires import games, color, random, time
start = time.time()
for items in enemies:
items.destroy()
if Enemy_amount > 0:
display_balloons()
elif Enemy_amount == 0 and (time.time() - start <= 120):
start = time.time()
level += 1
Enemy_amount = load_enemies()
#Just telling the code to load the next group of enemies.
The value of start is going to be a number like 1398354442, which is the number of seconds that have passed since January 1, 1970.
If you want to figure out the elapsed time between two events, you'll need to subtract. Perhaps something like this?
elif Enemy_amount == 0 and (time.time() - start <= 120):
start = time.time() # update start variable to the current time
Related
If the pygame program is just a basic entity you can move normally with arrow keys, how could i make it so that if space is pressed, based on the arrow key that was being held at the moment of pressing, a player dashes slightly to the specified direction? My idea is that when the space is pressed, program checks if other keys are being held down and based on that it rapidly increases the x and/or y coordinate and then stops at specific time, but I don't know how to make it stop as all of this is happening inside a main game loop. Any insight is highly appreciated.
You can use time.perf_counter.
So for using that function you will need to import module time
import time
And now you can store the value of time.perf_counter in a variable when space is pressed.
import time
jumping = False
start_time = 0
while True:
if ("space is pressed"): # Replace condition with what you want
jumping = True
start_time = time.perf_counter()
# Add your code here
if jumping:
# change of x, y and other jumping mechanism code here
if jumping and time.perf_counter() - start_time > 1: # Replace 1 with the amount you want this if condition to trigger, also add value in seconds
jumping = False
I'm not sure what your code is like, but this is how I'd go about it:
def dash(self):
keys = pygame.keys.get_pressed()
if keys[pygame.K_SPACE] and not self.dashing and self.jumping:
# ^^ Can be any key
if self.facing_right:
self.x += 20
if self.facing_left:
self.x -= 20
self.dashing = True
Make sure that when you hit the ground it does self.dashing = False else you will be able to dash forever.
Just put this function in the player class if you are doing it OOP.
Else if you are not using classes, put it anywhere in the file and take out all self..
I am trying to make a alarm like app where I want a list of things to happen when its time. But I am facing a bug. Time keeps waiting for previous time instead of going to next time in list.
t1 = dt.time(hour=17,minute=8)
t2 = dt.time(hour=18,minute=48)
timetable = [t1, t2]
for elt in timetable:
i_time = elt
#i_minute = i.minute
while True:
if i_time == dt.datetime.now().time():
#if i_hour == dt.datetime.now().hour and i_minute == dt.datetime.now().minute:
#current_time = tk.Label(text = dt.datetime.now())
#current_time.pack()
#playsound('media/ClassAlarm.mp3')
print("Its time")
break
The function works fine when it comes to t1 but if t1 is passed and current time is higher that t1 it should go to t2 and ring alarm. But it keeps waiting for t1 which will happen next day. it doesn't read t2 unless t1 is processed.
Ex. Current time 1:30 while t1 is 1:25 and t2 is 1:35. It doesn't ring at t2 but keeps waiting for t1 to happen again which has already happened.
I have tried to execute for loop in different way
for elt in timetable:
time = dt.datetime.now().time()
if time - elt < 0:
break
while(True):
if time == elt:
print("you did it")
I have also tried any() method. Which isn't helping exactly as well
current_hour = dt.datetime.now().hour
current_min = dt.datetime.now().minute
alarm = any(i.hour == current_hour and i.minute == current_min for i in timetable)
print(alarm)
I have tried posting question previously but wasn't able to explain properly. Hope this helps
Using == Operator To Compare Time Is Risky, Logically It Should Work But Somehow It's Better To Use <= Operator Which Eventually Compare If Your Time Is Greater Than The One Recorded In List! This Is Lot Safer Than Equality Which Trigger Only Once And Has No Guarantee To Work For A Split
-->Note: I Believe Those Function Generated Timestamp Of Different Format, Although They Represent Time And Are Useful But Since They Are In Different Format You Ain't Getting Equality Operator To Work (Bcz Even for Same Time And Date, Your Timestamp Gonna Be Different Although They Represent Same). To confirm this behavior you can write print variables of t1 and datetime.now and see if they are same.
Regarding Your Second Question You Can Have if/else statements to check for which time has been occured and most last time which has just been crossed, or you can run loop in reverse and check for timer (assuming late timers are in end of loop)
Sample Code:
for elt in timetable.reverse():
i_time = elt
while True:
if i_time <= dt.datetime.now().time():
print("Its time")
break
first time poster here, so I hope you guys can help me :)
I'm working on a project in which I want to play a game of SET. It all works (JEEJ), however I want to be able to use some sort of time function. This will do the following:
at start of game the time starts running
if x:
y
reset timer to zero
elif not x and time == 30:
do some action
I tried a lot of things; using time.time(), but this cannot be reset as far as I know; I found a few stopwatch like classes which I tried using, but they were slow (?); I tried perf_counter()... But now I'm at loss, so I hope any of you may know what to do...
Note that I want to "play" the game and do actions while the time runs...
Many thanks in advance!
There are a few ways to solve this problem. One is using time:
import time
timer_start = time.time()
if x:
y
timer_start = time.time()
if not x and time.time() >= timer_start + 30:
do some action
Note that I use >= because the time is highly unlikely to be exactly 30.0, better to fire it the first time after.
Another way is to use pygame.time.set_timer():
pygame.time.set_timer(pygame.USEREVENT, 30000) #milliseconds
# You cal also use USEREVENT+1, USEREVENT+2 etc. if you want multiple timers
if x:
pygame.time.set_timer(pygame.USEREVENT, 30000) #milliseconds
for event in pygame.event.get(): #merge this with your actual event loop
if event.type == pygame.USEREVENT:
if not x:
y
# reset the timer since it repeats by default
pygame.time.set_timer(pygame.USEREVENT, 0)
In an MMO game client, I need to create a loop that will loop 30 times in 30 seconds (1 time every second).
To my greatest disappointment, I discovered that I can not use time.sleep() inside the loop because that causes the game to freeze during the loop.
The loop itself is pretty simple and the only difficulty is how to delay it.
limit = 31
while limit > 0 :
print "%s seconds remaining" % (limit)
limit = limit -1
The python libs exist in the client as .pyc files in a separate folder and I'm hoping that I can avoid messing with them.
Do you think that there is any way to accomplish this delay or is it a dead end?
Your game has a main loop. (Yes, it does.)
Each time through the loop when you go to check state, move the players, redraw the screen, etc., you check the time left on your timer. If at least 1 second has elapsed, you print out your "seconds remaining" quip. If At least 30 seconds has elapsed, you trigger whatever your action is.
You can't do it without blocking or threading unless you are willing to lose precision...
I'd suggest sometime like this, but threading is the correct way to do this...
import time
counter = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### When 1 sec or more has elapsed...
if time.time() - start > 1:
start = time.time()
counter = counter - 1
### This will be updated once per second
print "%s seconds remaining" % counter
### Countdown finished, ending loop
if counter <= 0:
break
or even...
import time
max = 31
start = time.time()
while True:
### Do other stuff, it won't be blocked
time.sleep(0.1)
print "looping..."
### This will be updated every loop
remaining = max + start - time.time()
print "%s seconds remaining" % int(remaining)
### Countdown finished, ending loop
if remaining <= 0:
break
I have created a simple score system for my pygame. but it's pausing the game. I know it's because of time.sleep but I don't how to sort it out.
The score system is to +100 every 5 seconds while start is true, code:
while start == True:
time.sleep(5)
score = score + 100
Full code with indentation: http://pastebin.com/QLd3YTdJ
code at line : 156-158
Thank you
Instead of using sleep, which stalls the game until time has elapsed, you want to count up an internal timer with the number of seconds which have passed. When you hit 5 seconds, increment the score and then reset the timer.
Something like this:
scoreIncrementTimer = 0
lastFrameTicks = pygame.time.get_ticks()
while start == True:
thisFrameTicks = pygame.time.get_ticks()
ticksSinceLastFrame = thisFrameTicks - lastFrameTicks
lastFrameTicks = thisFrameTicks
scoreIncrementTimer = scoreIncrementTimer + ticksSinceLastFrame
if scoreIncrementTimer > 5000:
score = score + 100
scoreIncrementTimer = 0
This could easily be improved (what if your frame rate is so low there's more than 5 seconds between frames?) but is the general idea. This is commonly called a "delta time" game timer implementation.
If i understand you correctly you dont want the while True: score += 100 loop to block your entire program?
You should solve it by moving the score adding to a seperate function
and use the intervalfunction of APScheduler http://packages.python.org/APScheduler/intervalschedule.html
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Schedule job_function to be called every 5 seconds
#sched.interval_schedule(seconds=5)
def incr_score():
score += 100
This will result in APScheduler creating a thread for you running the function every 5 seconds.
you might need to do some changes to the function to make it work but it should get you started at least :).