I am trying to create a little game with python. I already set everything but I would like to set a time limit. I found something on the internet but it is not working with this project but it works with another project.
c.create_text(450, 20, text = 'Time', fill = 'red')
c.create_text(650, 20, text = 'Score', fill = 'red')
time_text = c.create_text(450, 20, text = 'Time', fill = 'red')
score_text = c.create_text(650, 20, text = 'Score', fill = 'red')
def print_score(score) :
c.itemconfig(score_text, text = str(score))
def print_time(time) :
c.itemconfig(time_text, text = str(time))
ENNEMY_CHANCE = 10
TIME_LIMIT = 30
SCORE_BONUS = 1000
score = 0
bonus = 0
end = time() + TIME_LIMIT
#Main
while True :
if randint(1, ENNEMY_CHANCE) == 1:
create_ennemy()
move_ennemies()
hide_ennemies()
score += ennemy_kill()
if(int(score/SCORE_BONUS)) > bonus:
bonus += 1
end += TIME_LIMIT
print_score(score)
print_time(int(end - time()))
window.update()
But I get this:
end = time() + TIME_LIMIT
TypeError: 'int' object is not callable
If you know an easier way to set a time limit that would be super.
Did you import time? I think you used the "time" name as an integer variable somewhere in your code and you have ambiguous code. Try this to get current time:
import time as time_module
now = time_module.time()
Try this
import time
start = time.time() #the variable that holds the starting time
elapsed = 0 #the variable that holds the number of seconds elapsed.
while elapsed < 30: #while less than 30 seconds have elapsed
elapsed = time.time() - start #update the time elapsed
Related
I tried these codes.
x = 6
while 1:
if x < 0.999:
break
#execute you function after 6 seconds.
x -= 0.01
sleep(0.01)
But i need to execute on a particular time . So i tried this:
if (self.is_hour_between("09:55:00", "11:20:00")) == True:
#your function
else:
#your function
def time_between(self, start, end):
# Time Now
now = datetime.now().time()
# Format the datetime string
time_format = "%H:%M:%S"
# Convert the start and end datetime to just time
start = datetime.strptime(start, time_format).time()
end = datetime.strptime(end, time_format).time()
is_between = False
is_between |= start <= now <= end
is_between |= end <= start and (start <= now or now <= end)
return is_between
i wanted to run the function at exactly 10 Am and 11Am .If its not the time then wait for it.else if its the time then go for it without waiting
Anwser :
import datetime
import time
while True:
current_dt = datetime.datetime.now()
time_a = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 9, 55)
time_b = datetime.datetime(current_dt.year, current_dt.month, current_dt.day, 11, 20)
if (time_a<current_dt) and (time_b > current_dt):
print('ok')
else:
time.sleep(60)
I have a problem with function time.time().
I've written a code, which has 3 different hash functions and then it counts how long does they execute.
start_time = time.time()
arr.add(Book1, 1)
end_time = time.time()
elapsed_time = start_time - end_time
print(elapsed_time)
When I execute this in pycharm/IDLE/Visual it shows 0. When I do this in online compiler (https://www.programiz.com/python-programming/online-compiler/) it shows a good result. Why is that?
Here is the full code if needed.
import time
class Ksiazka:
def __init__(self, nazwa, autor, wydawca, rok, strony):
self.nazwa = nazwa
self.autor = autor
self.wydawca = wydawca
self.rok = rok
self.strony = strony
def hash_1(self):
h = 0
for char in self.nazwa:
h += ord(char)
return h
def hash_2(self):
h = 0
for char in self.autor:
h += ord(char)
return h
def hash_3(self):
h = self.strony + self.rok
return h
class HashTable:
def __init__(self):
self.size = 6
self.arr = [None for i in range(self.size)]
def add(self, key, c):
if c == 1:
h = Ksiazka.hash_1(key) % self.size
print("Hash 1: ", h)
if c == 2:
h = Ksiazka.hash_2(key) % self.size
print("Hash 2: ", h)
if c == 3:
h = Ksiazka.hash_3(key) % self.size
print("Hash 3: ", h)
self.arr[h] = key
arr = HashTable()
Book1 = Ksiazka("Harry Potter", "J.K Rowling", "foo", 1990, 700)
start_time = time.time()
arr.add(Book1, 1)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
start_time = time.time()
arr.add(Book1, 2)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
start_time = time.time()
arr.add(Book1, 3)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
I looks like 0 might just be a return value for successful script execution. You need to add a print statement to show anything. Also you might want to change the order of the subtraction:
start_time = time.time()
arr.add(Book1, 1)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time)
Edit b/c of updated questions:
If it still shows 0, it might just happen, that your add operation is extremely fast. In that case, try averaging over several runs, i.e. instead of your add operation use a version like this:
start_time = time.time()
for _ in range(10**6):
arr.add(Book1, 1)
end_time = time.time()
elapsed_time = end_time - start_time
print(elapsed_time) # indicates the average microseconds for a single run
The documentation for time.time says:
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
So, depending on your OS, anything that is faster than 1 second might be displayed as a difference of 0.
I suggest you use time.perf_counter instead:
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration.
I believe my program is freezing after:
if pressed(win.getMouse(), startImage):
task = 'start'
timeFormat()
Basically, what I'm trying to do is when the mouse point is on stopImage the timer will stop, and when the mouse click is on lapTimer, it will reset. When I take out
timeFormat()
the program will run through the while and then break. My stop and start button work, but not my lap button. How can i make it NOT stop the program after the stop button is pressed? So that I can hit start again or reset?
def pressed(pt, image):
width = image.getWidth()
height = image.getHeight()
anchor = image.getAnchor()
x1 = (anchor.getX()) - (.5 * width)
x2 = (anchor.getX()) + (.5 * width)
y1 = (anchor.getY()) - (.5 * height)
y2 = (anchor.getY()) + (.5 * height)
return(x1 <= pt.getX() <= x2 and y1 <= pt.getY() <= y2)
def timeFormat():
sec = 0
minute = 0
hour = 0
timeDisplay = "{0:02d}:{1:02d}:{2:02d}".format(hour, minute, sec)
timer.setText(timeDisplay)
while task == 'start':
task = 'start'
time.sleep(1)
sec += 1
if sec == 60:
sec = 0
minute += 1
if minute == 60:
sec = 0
minute = 0
hour += 1
timeDisplay = "{0:02d}:{1:02d}:{2:02d}".format(hour, minute, sec)
timer.setText(timeDisplay)
check = win.checkMouse()
if check != None:
if pressed(check, stopImage):
task = 'stop'
print('asd')
if pressed(check, startImage):
task = 'start'
if pressed(check, lapImage):
sec = 0
minute = 0
hour = 0
task = 'stop
def main():
while not pressed(win.getMouse(), startImage):
if task == 'stop':
break
if task == 'reset':
sec = 0
minute = 0
hour = 0
break
continue
timeFormat()
main()
Your timeFormat function never returns, so the calling code can't continue.
Your main loop has the condition while sec < 60, but every time sec is incremented to 60, it gets reset to zero again. This means the loop will never end.
It's not clear to me when you expect it to end, so I can't necessarily tell you how to fix the issue, but generally it's a bad idea when writing an interactive program to have multiple event loops unless you have a well defined structure for switching between them.
You have a lot of loops, and when one of them is running, all the others will necessarily be stuck waiting. Try moving some of the logic from separate loops into other functions that can be called from a single main loop.
All I had to do was switch some if statements around.
I am currently working on a small Python clock. The clock doesn't have anything to do with real time, it was just for a fun side project. After every second, the clock is supposed to save the hour, minute, second, time of day, and other information. It saves the information, but when I restart the program, it doesn't reuse the information. Here is my code:
#Importations
import jsonpickle
import os
import sys
import time
#Setups
SAVEGAME_FILENAME = 'time.json'
game_state = dict()
#Class
class clocktime(object):
def __init__(self, hour, minute, second, timeday, day):
self.hour = hour
self.minute = minute
self.second = second
self.timeday = timeday
self.day = day
#Load Program Save
def load_game():
"""This runs if a .json file IS found"""
with open(SAVEGAME_FILENAME, 'r') as savegame:
state = jsonpickle.decode(savegame.read())
return state
#Save Program to JSON
def save_game():
"""This saves the program to a .json file."""
global game_state
with open(SAVEGAME_FILENAME, 'w') as savegame:
savegame.write(jsonpickle.encode(game_state))
#Initialize Program
def initialize_game():
"""Runs if no AISave is found"""
hour = 1
minute = 0
second = 0
timeday = 1
day = ('am')
the_time = clocktime(hour, minute, second, timeday, day)
state = dict()
state['the_time'] = [the_time]
return state
#Clear Screen
def cls():
os.system('cls')
#Clock Program
def clock():
hour = 1
minute = 0
second = 0
timeday = 1
day = ('am')
global game_state
while True:
print ("The time is: %s" % hour + ":%s" % minute + ":%s" % second + " %s" % day)
print (" H M S")
print ("H = Hour, M = Minute, S = Second")
time.sleep(0.5)
cls()
second += 1
save_game()
if second == 60:
minute += 1
second = 0
if minute == 60:
hour += 1
minute = 0
if hour == 13:
hour = 1
timeday += 1
if timeday == 1:
day = ('am')
if timeday == 2:
day = ('pm')
if timeday == 3:
day = 0
game_state['the_time'][0].hour = hour
game_state['the_time'][0].minute = minute
game_state['the_time'][0].second = second
game_state['the_time'][0].timeday = timeday
#Main Program
def main():
"""Main function. Check if a savegame exists, and if so, load it. Otherwise
initialize the game state with defaults. Finally, start the game."""
global game_state
if not os.path.isfile(SAVEGAME_FILENAME):
game_state = initialize_game()
else:
game_state = load_game()
clock()
#Launch Code
if __name__ == "__main__":
isSaveOn = False
main()
You're overwriting game_state with initial hour/minute/second/timeday values ) at the end of the loop when you save them, and they are always 1/0/0/1 regardless of the game_state. So basically you load game_state and then overwrite it with default values. Replace initializations in clock function to something like this:
# ...
def clock():
# Change to this:
hour = game_state['the_time'][0].hour
minute = game_state['the_time'][0].minute
second = game_state['the_time'][0].second
timeday = game_state['the_time'][0].timeday
while True:
# (displaying time and incrementing values)
game_state['the_time'][0].hour = hour
game_state['the_time'][0].minute = minute
game_state['the_time'][0].second = second
game_state['the_time'][0].timeday = timeday
# Move save_game here (to the end of loop):
save_game()
What I am trying to accomplish is first text appears after 1 second. then 2, ect. till 10. then when time equals 10, the time decreases, so the text appears after 9 seconds, then 8 etc.
How could I fix this code so that it works properly?
The error:
Traceback (most recent call last):
File "C:/Users/Eric/Dropbox/time.py", line 13, in <module>
time.sleep(time)
AttributeError: 'int' object has no attribute 'sleep'
The code :
import time
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >=10:
time = t - 1
elif time <= 0:
time = t + 1
time.sleep(time)
Edit:
import time
x = 1
t = 1
time1 = 0
while x == 1:
if time1 == 10:
time1 = time1 - 1
elif time1 == 0:
time1 = time1 + 1
else :
time1 = time1 + 1
print time1
time.sleep(time1)
So I changed the program around abit, so I almost works correctly. What it does is count to 10, then 9 then back to 10.
ex. 1,2,3,4,5,6,7,8,9,10,9,10,9,10
how can I set it so that the program increases time to ten then decreases to zero then increases again?
You're overriding the imported time module (line 1) by your own time variable (line 4). You can:
rename your time variable to something else
import time
x = 1
t = 1
time_passed = t + 1 # use "time_passed" instead of "time" for example
while x == 1:
print time_passed
if time_passed >= 10:
time_passed = t - 1
elif time_passed <= 0:
time_passed = t + 1
time.sleep(time_passed)
alias the imported time module with import time as tm the use tm.sleep(time)
import time as tm # alias the time module as "tm" for example
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
tm.sleep(time) # use "tm" to refer to the module
only import sleep from time with from time import sleep and use sleep(time) instead
from time import sleep # only import "sleep" from time, not the whole module
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
sleep(time) # use "sleep" directly
After fixing this, you also need to somehow remember that you need to either increase or decrease the time at the next iteration. For example:
from time import sleep
x = 1
t = 1
time = t + 1
incr = True
while x == 1:
print time
if time >= 10:
time = 9
incr = False
elif time <= 0:
time = t + 1
incr = True
else:
if incr:
time = time + 1
else:
time = time - 1
sleep(time)
You're redefining 'time' after you import it...
Try using a different variable name.
Your time variable is conflicting with the module (time) that you imported. You could use curTime or myTime instead as your variable name.