im trying to start and end the while loop with a time difference.
At first Im getting the current time with date time.now
in my def I want to create a time difference. This should be 10 seconds.
The function should give a False, if the seconds were expired and the current time is equal to the previous time (current time + 10s). Otherwise it should give me a True return.
After this im setting the "Zeit" variable to True, so the while loop can start.
In the while loop im starting the "fkt_Zeit", to change the "Zeit" condition at the while loop to False, after the 10 seconds expire.
So that's my plan, but its not working. The "Zeit" variable never changes to False.
Can you please help me finding my mistake?
And sorry for my bad english...
akt_zeit = datetime.now()
timedelta = timedelta(seconds=10)
def fkt_Zeit(akt_zeit, timedelta):
off_time = akt_zeit + timedelta
while(True):
if(akt_zeit < off_time):
return True
else:
return False
Zeit = True
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
In this code
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
you call the function fkt_zeit, but notice that the time delta is computed inside this function. That means that every time you call fkt_zeit you reset the time needed for fkt_zeit to return false. That's why your function is never returning false. I'd suggest moving the off_time computation outside of the fkt_zeit function. For example:
def fkt_Zeit(akt_zeit, timedelta):
while(True):
if(akt_zeit < off_time):
return True
else:
return False
Zeit = True
off_time = akt_zeit + timedelta # so the off_time doesn't keep resetting
while(Zeit == True):
Zeit = fkt_Zeit(akt_zeit, timedelta)
Hope this helps.
Related
if keyboard.h and start == False:
start = True
print("hello?")
dotty_move()
if keyboard.h and start == True:
start = False
print("bye")
dot1.pos = x, y
dot2.pos = xi, yi
def dotty_move():
global speed, speedi, start
if start == True:
animate(dot1, duration = speedi, pos = (xi, 0), on_finished = dot_move())
animate(dot2, duration = speed, pos = (x, 0), on_finished = dot_move())
def dot_move():
global speed, speedi, start, x, y, xi, yi, dot1
if start == True:
animate(dot1, pos=(0, 425), on_finished = dotty_move())
print("test")
animate(dot2, duration = speed, pos = (x, 425), on_finished = dotty_move())
dot_move()
Hello! Everything before the dotty_move() subroutine (I have really bad names for my subroutines haha) is in the update() subroutine.
I am trying to have the input of the key "h" only happen once, but it seems to input 3 times if I press it for a split second. I think this is because it's in the update class, but I couldn't find another way to check for the key press.
This code is meant to make two dots in pre-set x coordinates move up and down over and over with a defined speed whenever you press "h". If you press "h" again it is supposed to stop this. The reason I think this isn't working at the moment is because of the issue I stated earlier: it's turning on and off so it never does anything.
But I don't know. If anyone can help it, would be really appreciated. Thanks :)
The issue is here:
if keyboard.h and start == False:
start = True
print("hello?")
dotty_move()
if keyboard.h and start == True:
start = False
print("bye")
Execute this code in your mind:
Is keyboard.h is pressed and start = false (yes it is!)
start := true
And then straight away immediately after:
Is keyboard.h is pressed and start = true (yes, we just set it above!)
start := false
So as soon as start is set, it becomes un-set.
Probably just an "else-if" (elif:) will fix it.
if keyboard.h and start == False:
start = True
print("hello?")
dotty_move()
elif keyboard.h and start == True:
start = False
print("bye")
Because only one of the logical expressions will match.
You may also have timing related issues, where your program is running so fast, it still turns off straight after turning on. To handle this, maybe measure the time between on/off with something like pygame.time.get_ticks().
next_click_time = 0 # time [h] can be pressed again
# ...
if keyboard.h:
time_now = pygame.time.get_ticks()
if ( time_now > next_click_time ):
next_click_time = time_now + 300 # milliseconds in the future
start = not start # invert start
if ( start ):
# turning on
print("hello?")
dotty_move()
else:
# turning off
print("end")
I know the title is not very clear, but I don't know what else I can say.
I have a player attacking, and when he is done attacking, I start a timer for 1 second, so we have to wait one second before attacking again. It wasn't working (we could attack only once) and I didn't know why, so I added print(self.between_two_attacks())and everything worked fine, I could attack, wait one second and attack again.
Here is the program, I don't know if it is enough because I have no idea where the bug comes from.
def between_two_attacks(self):
if self.after_attack_max == 0:
self.after_attack_max = pg.time.get_ticks() + 1000
print("set timer")
else:
after_attack = pg.time.get_ticks()
print("start timer")
if after_attack >= self.after_attack_max:
print("can attack again")
self.can_attack = True
self.after_attack_max = 0
def draw(self, win):
print(self.between_two_attacks())
if (self.attackcount + 1) >= 5:
self.attackcount = 0
self.between_two_attacks()
self.action = STAND_UP
self.arme = LIGHTSABER_OUT
self.stops_attacking = True
self.can_attack = False
if self.action == ATTACKING:
win.blit...
Run = True
While Run:
for event in pg.event.get():
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE and player.can_attack == True:
player.action = ATTACKING
If anything isn't clear in this part of the program, just tell me and I'll try to explain. Thanks for your help :)
The method between_two_attacks has to be invoked, before the state of self.can_attack is retrieved. self.can_attack is set in between_two_attacks. If the method is not called, the self.can_attack will never become True.
When you do print(self.between_two_attacks()), the self.between_two_attacks() is called.
Furthermore, the method can be simplified:
self.can_attack has to be set if self.after_attack_max == 0 or if the current time is greater than self.after_attack_max.
If self.can_attack is set then compute the restart the timer. If it is not set then it has to be evaluated. Initially self.after_attack_max is 0. If the current time is greater than self.after_attack_max, attacks have to be allowed and the timer has to be started again:
def between_two_attacks(self):
current_time = pg.time.get_ticks()
if self.can_attack:
self.after_attack_max = current_time + 1000
elif current_time > self.after_attack_max:
self.can_attack = True
self.after_attack_max = current_time + 1000
Note, self.after_attack_max is only set in between_two_attacks, do not reset it anywhere else.
When you print self.between_two_attacks() the self function gets called and executed. Now, if you added the whole line it means that this function was not executed at this point before and now it is, so if you remove print and left only function at the same location you should get the same behaviour.
I do not know if I manage to explain my thought so here as a quick example:
x = 5
def change_x():
global x
x+=10
print(x)
print(change_x())
print(x)
if you remove print() you will get same result.
I am trying to switch on and off the LED based on a set set_car_id returning some value within a time interval. If the set returns some value, i want the LED to be brighter for 8 seconds. In the code shown below, once the set returns a value, the LED is switched on for 8 seconds. But, if the set returns a value at 5 second (within the 8 sec), then the LED won't be switched on till next 13 sec, it will be on for 3 more seconds and then suddenly switches off. I am showing only smaller part of the code. Any suggestions to solve?
last_bright_time = None
last_dim_time = None
new_action = -1
def LED_control(set_car_id):
global last_bright_time
global last_dim_time
curr_time = time.time()
should_remain_bright = False
should_remain_dim = False
if (new_action == 0): #new_action ==0 corresponds to set_car_id returning some value
if last_bright_time == None:
last_bright_time = time.time()
if (curr_time - last_bright_time) < 8:
should_remain_bright = True
if ((len(set_car_id) > 0) or should_remain_bright = True):
car_light(1) # function to bright the LED
last_dim_time = None
else:
car_light(0) # function to dim the LED
last_bright_time = None
Try this:
import time
while True:
brighten()
time.sleep(8)
dim()
time.sleep(8)
If you want something more precise:
import time
def sleep():
time_start = time.time()
while time.time() < time_start + 8000:
pass
while True:
brighten()
sleep()
dim()
sleep()
In the pieces of code above, you have to define the brighten and dim functions.
I have this following code and am stuck in the while loop
I know there is a problem with the while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)): line.
Can anyone help please ?
nodes_with_scanner = []
wait_time = 60
while datetime.datetime.now() < (datetime.datetime.now() + datetime.timedelta(minutes=wait_time)):
nodes_with_scanner = get_nodes_with_scanner_in_dps(self.node_names, scanner_id, username=self.users[0].username)
log.logger.debug("Number of pre-defined {0} scanners detected in DPS: {1}/{2}".format(scanner_type, len(nodes_with_scanner), len(self.node_names)))
if state == "create":
if len(self.node_names) == len(nodes_with_scanner):
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully created in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
elif state == "delete":
if len(nodes_with_scanner) < 1:
log.logger.debug("All {0} pre-defined scanners with id '{1}' have been successfully deleted in DPS for nodes '{2}'".format(scanner_type, scanner_id, ", ".join(self.node_names)))
return
log.logger.debug("Still waiting on some {0} pre-defined scanners to '{1}' in DPS; sleeping for 1 minute before next check".format(scanner_type, state))
time.sleep(60)
You are asking if the current time is smaller than the current time plus a delta. Of course that's going to be true each and every time, the future is always further away into the future.
Record a starting time once:
start = datetime.datetime.now()
while datetime.datetime.now() < start + datetime.timedelta(minutes=wait_time)):
If wait_time doesn't vary in the loop, store the end time (current time plus delta):
end = datetime.datetime.now() + datetime.timedelta(minutes=wait_time))
while datetime.datetime.now() < end:
It may be easier to just use time.time() here:
end = time.time() + 60 * wait_time
while time.time() < end:
You use datetime.datetime.now() in your while loop, what means each iteration you check if the time now is lower then the time now + delta.
That logically wrong, because it will be True forever as the time now will be always lower than the time now plus delta.
You should change it to this:
time_to_start = datetime.datetime.now()
while datetime.datetime.now() < (time_to_start + datetime.timedelta(minutes=wait_time)):
print "do something"
so i am trying to figure this out for school. Im trying to print x out every minute and every ten min it will print on a new line. so far i cant get the "printing x" every min down. can someone please help.
this is my code
import time;
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
print (time.time())
def tenMin(oldTime):
newTime = time.time()
if ((newTime - oldTime)>= 25):
return True
else:
False
while (True):
if (tenMin==True):
print ("x")
newTime = time.time()
oldtime = time.time()
else:
oldTime = time.time()
continue
Your first problem is in the line
if (tenMin==True):
You compare a function reference to a boolean, clearly the answer would be False. You have to pass a parameter
if (tenMIn(oldTime)):
...
First you have some issues with you code:
else:
False - This is not true syntax in python.
If you want timer, why are you asking the user for input?
You have a logic problem:
inTime = float(input("type in how many second"))
oldTime = time.time()-inTime
time.time is float yes, but can a user really know what to print in UnixTime?
I'll suggest a simple solution it's not the very best but it works.
It will print "x" every 1 Min and after 10 Min it will print "\n" (new line)
import time
def main():
#both timers are at the same start point
startTimerTen = time.time()
startTimerMin = startTimerTen
while True:
getCurrentTime = time.time()
if getCurrentTime - startTimerTen >= 600:
# restart both parameters
startTimerTen = getCurrentTime
startTimerMin = getCurrentTime
print "This in 10 min!\n"
if getCurrentTime - startTimerMin >= 60:
# restart only min parameter
startTimerMin = getCurrentTime
print "x"
#end of main
if __name__ == "__main__":
main()