how to fix a random choice generator? - python

My python game isn't working, the sequences beginning with:
if int(total_time) > 10:
isn't triggering, but when I press D, C or W I am getting the 'you opened something' text though. The code there is right as far as I know, it's just not working. I used the or prevtime to allow you to do it the first time.
import random, time, pygame, sys
from pygame.locals import *
total_time = time.clock()
pygame.init()
XQR_prevtime = 0
ppayh_prevtime = 0
pu_ekaw_prevtime = 0
diff = 1
windowSurface = pygame.display.set_mode((400,400),0,32)
time.sleep(3)
XQR_awakened = False
ppayh_awakened = False
pu_ekaw_awakened = False
if int(total_time) > 10:
if int(XQR_prevtime) > (12 - diff) or int(XQR_prevtime) == 0 or XQR_awakened == True:
if XQR_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a mystery came in")
time.sleep(2)
sys.exit()
if random.randint(0,diff) == 1:
print(3)
XQR_prevtime = time.clock()
door_opening.play()
XQR_awakened = True
if int(ppayh_prevtime) > (12 - diff) or int(ppayh_prevtime) == 0 or ppayh_awakened == True:
if ppayh_awakened == True:
print("You left something open...")
time.sleep(2)
print("And a friend came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
ppayh_prevtime = time.clock()
closet_opening.play()
ppayh_awakened = True
if int(pu_ekaw_prevtime) > (12 - diff) or int(pu_ekaw_prevtime) == 0 or pu_ekaw_prevtime == True:
if ekaw_up_awakened == True:
print("You left something open...")
time.sleep(2)
print("And an answer came in")
time.sleep(2)
sys.exit()
if randint(0,diff) == 1:
print(3)
pu_ekaw_prevtime = time.clock()
window_opening.play()
pu_ekaw_awakened = True

total_time never changes, so you can never reach your condition.
The line
total_time = time.clock()
assigns a numeric value (a float) to total_time. There is no reference back to the time.clock() function, the function returns just a normal float object, not a timer object.
And normal float values don't change, they are immutable. The total_time value is not going to change as you game runs.
If you want to measure elapsed time, just keep calling time.clock():
if time.clock() > 10:
You don't need to convert a float value to int here, comparisons with integers just work.

Related

Can you perform an action for a specific amount of time in pygame

I'm trying to perform something for 4 seconds. How would that work?
yes = True
while True:
if yes:
print('yes')
if [4 seconds pass]:
yes = False
elif not yes:
print('No')
I tried
seconds = pygame.time.get_ticks()
yes = input('True or False: ')
while True:
if yes:
print('yes')
time = int((pygame.time.get_ticks - seconds)/ 1000)
if time == 4:
yes = False
elif not yes:
print('no')
But it didn't work
n pygame the system time can be obtained by calling pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. See pygame.time module.
Get the current time before the loop and compute the point in time until the action needs to be performed. Get the current time in the loop and compare it to the computed time:
end_time = pygame.time.get_ticks() + 4000
while True:
current_time = pygame.time.get_ticks()
if yes:
If current_time < end_time:
# do something
# [...]
else:
yes = False
else:
# [...]

How would you count time elapsedsince first execution of the loop until ended by user in Python?

I'm new to programming in general and this is my first post here, so please explain like I'm five.
This is a random string combination generator (sorry if I don't know how to call it properly) and I want to make the program start counting time since A key is first pressed until Q is pressed, without counting repeats caused by pressing A.
I also know that this might come handy, but I don't really know how to make it work.
Here's the code:
import random
import os
print('hello world')
while True:
while True:
key = msvcrt.getch().lower()
if key == b'a':
os.system('cls')
alpha = random.randint(1, 2)
bravo = random.randint(1, 2)
if alpha == 1:
print('foo')
elif alpha == 2:
print('bar')
if bravo == 1:
print('spam')
elif bravo == 2:
print('eggs')
elif key == b'q':
os.system('cls')
print('elapsed time: mm:ss') #this is where i want to have shown time elapsed from pressing A for the first time until pressing Q
break
We create start uninitialized (as None) outside the loop
When a is pressed, we check if start is uninitialized (if start is None)
2.1. If it is uninitialized. we initialize with current time
When q is pressed
3.1. We check if start is initialized (if start is not None), (to cover the case that q is the first input so we won't do the next step if start is uninitialized)
3.2. If start is initialized we print elapsed time
import random
import os
from timeit import default_timer as timer
print('hello world')
start = None
while True:
while True:
key = msvcrt.getch().lower()
if key == 'a':
# If start time is uninitialized
if start is None:
# Initialize start time
start = timer()
os.system('cls')
alpha = random.randint(1, 2)
bravo = random.randint(1, 2)
if alpha == 1:
print('foo')
elif alpha == 2:
print('bar')
if bravo == 1:
print('spam')
elif bravo == 2:
print('eggs')
elif key == 'q':
os.system('cls')
if start is not None:
end = timer()
print(f'elapsed time: {end - start}')
break

Pause and Continue a Loop When Press Key in Python

Who can help me on this?
Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.
Thanks
from multiprocessing import Process
import keyboard
import time
def countdown_1():
i=6
j=40
k=0
while True:
a = keyboard.read_key()
if(str(a) != "p"):
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j))
else:
print(str(k)+str(i)+":"+str(k)+str(j))
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("END")
time.sleep(1)
countdown_1()
I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')
I have modified your code to make a working version, I slightly change it to match my taste.
from multiprocessing import Process
import keyboard
import time
def countdown_1():
pause_keyboard = False # I use a bolean as a state is clearer for me
i = 6 # minutes
j = 40
k = 0 # represent 0 we will instead use code format
while True:
starting_time = time.time()
while True: # this loop wait one second or slightly more
if time.time() - starting_time >= 1: # a second or more
break
if keyboard.is_pressed('p'):
pause_keyboard = True
elif keyboard.is_pressed('s'):
pause_keyboard = False
if pause_keyboard:
continue
if (j == -1): ## here we adjust the count when we changes minutes
j = 59 # 59 secondes
i -= 1 # one minutes less
if(j > 9): ## in order to pretty print
print("{}{}:{}".format(0, i, j)) # you can direclty use 0 instead of k.
else:
print("{}{}:{}{}".format(0, i, 0, j))
j -= 1
if(i==0 and j==-1): # we finish the counter
break
if(i==0 and j==-1):
print("END")
time.sleep(1) # wait a last second
countdown_1()
EDIT: Use time.time() instead of sleep to be able to catch signals.

Escape Sequences in Python Not Working in CMD

import time
listy = ['timer','stopwatch']
def intro():
print("This is a program which contains useful tools")
print(listy)
def timer():
x = int(input("How long Seconds ?"))
while x > 0:
print(x)
time.sleep(1)
x -= 1
def stopwatch():
verif = input("Do you want to start y/n \n")
if verif == 'y':
x = 0
while True:
print(x, end = "\b"*5)
time.sleep(1)
x += 1
def main():
intro()
decider = input("Which Program?")
if decider.lower() == 'timer':
timer()
elif decider.lower() == 'stopwatch':
stopwatch()
main()
in this code i dont know why the \b escape sequence isnt working in cmd or in idle, can anyone explain why? Is it because of a logic error?
A flush may be required. How about...
print("{0}{1}".format("\b"*5, x), end="", flush=True)

printing out letter every min Python

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()

Categories