I just started programming python for GCSE and made a program called do not press the button, it is going good, but at the end there is the part where you need to try to click the enter button(which is impossible on purpose) Does anyone know how to stop it after 10seconds and continue with the program? (I used sources from everywhere the internet, myself and friends, dont get disturbed by the #'s)
print("##############################")
print("DO NOT PRESS THE ENTER BUTTON!")
print("##############################")
a = input("")
b = input("Hello?")
name = input("What is your name?\n")
d = input("Aha, you know " + str(name) + " you are very anoying!")
e = input("Stop it!")
f = input("I hate you soooo much")
g = input("I am sure you don't have friends")
h = input("BECAUSE ANOYING PEOPLE DON'T HAVE FRIENDS!!!")
i = input("I just won't answer anymore")
j = input("you will get bored")
k = input(".")
l = input("..")
m = input("...")
n = input("....")
o = input(".....")
p = input("STOOOOOOPPPP!!!!!")
q = input("You know what, i will lock me in with a code HA!")
import time
import random
import sys
print("Here you go, locked... you only have 5 tries, its between 1 and
20, and if you fail, I WILL SHUT DOWN YOUR COMPUTER, NO ENTER BUTTON
PRESSING THEN HAHAHA!!!\n")
#sets initial values
the_number = random.randint(1,20)
guess = int(input("Take a guess: "))
tries = 1
guesses = 5
#guessing loop
while guess != the_number:
tries += 1
guesses -= 1
if guesses == 0:
print("Computer getting shut down in,")
print("!3!")
time.sleep(1)
print("!2!")
time.sleep(1)
print("!1!")
time.sleep(5)
print("Just joking haha, but this is still finished.\n\n")
print("cOmMANd ENTER BUTTON bLOcKed!")
time.sleep(2)
print("##########")
print("YOU LOSE!!")
print("##########")
time.sleep(2)
sys.exit("Error message")
break
elif guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input()
#number guesser from internet changed slightly
print("aha, i see you unlocked me, you are so vexatious...")
r = input("...")
s = input("TAKE YOUR DIRTY FINGERS OFF ME!!!")
t = input("Man you are so anoying, by the way, ure you don't even know
what vexatious means, haha")
u = input("I will just move away, try pressing me know:")
time.sleep(4)
#Button game from internet
from tkinter import *
from random import *
def do_event(event):
print("{},{}".format(event.x,event.y))
def jump(event):
app.hello_b.place(relx=random(),rely=random())
class App:
def __init__(self,master):
frame = Frame(master)
master.geometry("500x500")
master.title("You will never catch me!")
master.bind("<Button-1>",do_event)
master.bind("<Button-1>",do_event)
frame.pack()
self.hello_b = Button(master,text="Enter
Button",command=sys.exit)
self.hello_b.bind("<Enter>",jump)
self.hello_b.pack()
root = Tk()
app = App(root)
root.mainloop()
#here i don't know how to end it, i want it to end after 10sec and
#continue with that
print("ahhh you got me...")
Try this timeout script written in bash.
#!/bin/sh
timeout 15 ./test.sh
status=$?
if[$status -eq 124] #time out
then
exit 0
fi
exit $status
Related
I am creating a 2 player number guessing game in python 3.8. I want a countdown timer to run in the background so that the program is terminated when time runs out, but its not working. I have tried using a solution I found online but the program does not get terminated.
declaring all the variable and modules
import random
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
from time import *
import threading
The solution that I found online
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
main program
while my_timer>0:
if SingleOrDouble=="Single":
while answer=="yes" or answer=="Yes":
while lives!=0 and n!=guess:
guess = int(input("Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+ str(lives) +" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives) +" lives left.")
else:
print("You guessed it!")
print("You won with "+ str(lives) +" lives left.")
break
print("Game over, the number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
else:
lives=16
while answer=="yes"or answer=="Yes":
while lives!=0 and n!=guess:
if lives%2==0:
guess = int(input("Player 1 please Enter an integer from 1 to 99: "))
else:
guess = int(input("Player 2 please Enter an integer from 1 to 99: "))
if guess < n:
print("guess is low")
lives-=1
print("You have "+str(lives//2)+" lives left.")
elif guess > n:
print ("guess is high")
lives-=1
print("You have "+ str(lives//2) +" lives left.")
else:
if lives%2==0:
print("Player 1 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=2
else:
print("Player 2 guessed it!")
print("You won with "+ str(lives//2) +" lives left.")
Gamewinner=1
break
if Gamewinner>0:
print("Game Over! Player "+str(Gamewinner)+"the number was "+ str(n))
else:
print("Game Over! The number was "+ str(n))
answer = input("Do you want to play again?")
if answer=="yes" or answer=="Yes":
lives=8
sleep(1)
if my_timer==0:
break
The code for the countdown timer is working just fine. What you could do is - Use a system exit when the timer hits zero so that you could stop the execution of your program.
You would need to use os._exit(1) to terminate your Python program. The modified code would look something like this -
from time import *
import os
import random
import threading
guess=""
Gamewinner=0
n = random.randint(1, 99)
lives = 8
answer = "yes"
print("You have a total of 8 lives. A wrong guess would result in one less life.")
SingleOrDouble=input("Do you want single player or double player?")
def countdown():
global my_timer
my_timer=5
for x in range(5):
my_timer=my_timer-1
sleep(1)
print("Out of time")
os._exit(1)
countdown_thread=threading.Thread(target=countdown)
countdown_thread.start()
I would put the game in a function called game and run it in a daemon thread so that it terminates when the main thread terminates. If N_SECONDS is the number of seconds allotted to the game then the main thread becomes simply:
from threading import Thread
import sys
N_SECONDS = some_value
t = Thread(target=game)
t.daemon = True
t.start()
t.join(N_SECONDS) # block for N_SECONDS or until the game ends by returning
if t.is_alive(): # the game has not returned and is still running
print('Out of time!')
sys.exit(0) # exit and the thread terminates with us
No additional timing is required!
i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)
When I have a line that has input() on it, the input() line after the first won't work when both are after each other. Here is my code.
from random import randint
you = 100
troll = 50
sword = randint(5,20)
goblin_attack = randint(25,50)
heal = you + 25
t_f = randint(1,2)
print("______________________")
print("WELCOME TO DRAGON GAME")
print("WRITE YOUR NAME......")
x = input()
print("Hello,")
print(x)
print("Lets begin....")
print("______________________")
print("You are in a troll cave")
print("A troll attacks!")
print("Quick, Dodge or attack,type D or A ")
print("______________________")
if input() == "D":
print("You attempt to dodge out of it's swing!")
if t_f == 1:
print("You dodge and attack!")
print("You hit the troll for")
print(sword)
print("damage")
print("It has")
print(troll - sword)
print("health left!")
if t_f == 2:
print("You trip! you got hit for")
print(goblin_attack)
print("damage!")
print("You have")
print(you - goblin_attack)
you2 = you- goblin_attack
print("Health left!")
if input() == "A":
print("You hit the troll for")
print(sword)
print("damage")
print("It has")
print(troll - sword)
print("health left!")
When I press A and hit enter, Nothing happens. But when I press D, it works. The first one always works no matter what I change the input to. Anyone have any idea how I can make both inputs work?
Each input call waits for a keyboard input, so when you call input() twice, you're asking for two keyboard inputs.
To fix, change your code to something like so:
user_input = input()
if user_input == 'D':
# go through the "dodge" scenario
elif user_input == 'A':
# go through the "attack" scenario
I've been making game which is called the riddle game it works semi perfect on pycharm, because the code os.system("clear") doesn't work, but it does work on terminal, but there is slightly a problem it return with a a error "Non ASCII" i couldn't understand. How can i fix this?
Either way I try to make the code as simple as possible can anyone check it and if it's too big give me a suggestion to change a rewrite the code please.
import random
import sys
import time
riddle1 = "You’re running a race and pass the person in second place. What place are you in now?"
riddle2 = "Imagine you are in a dark room. How do you get out?"
riddle3 = "David's father has three sons : Snap, Crackle and _ _ _ ?"
riddle4 = "You answer me, but I never ask you a question. What am I?"
riddle5 = "The more you take, the more you leave behind. What am I?"
riddle6 = "What comes once in a minute, twice in a moment, but never in a thousand years?"
riddle7 = "What room that ghosts can't get in?"
riddle1_Ans = "You’re in second place. You didn't pass the person in first"
riddle2_Ans = "Stop imagining"
riddle3_Ans = "David"
riddle4_Ans = "A telephone"
riddle5_Ans = "Footsteps"
riddle6_Ans = "m"
riddle7_Ans = "The living room"
riddles_lists = [riddle1, riddle2, riddle3, riddle4, riddle5, riddle6, riddle7]
random_list = random.choice(riddles_lists)
# Welcoming the user
def welcome():
print("")
print("\033[1;31;0m", " Welcome to RIDDLES")
print("\033[1;33;0m", " ")
answer = input(" Do you want to play the game?Y/N:")
if answer in ("yes", "y"):
Introductin()
else:
print("Bye....")
sys.exit()
# RESTART GAME
def restart():
print(" ")
ask = input("Do you want to Try? if you say yes the game will restart"
" if you say no there answer of the riddle will be shown:")
if ask in ("yes", "y"):
print("Restarting game.....")
time.sleep(1)
play_game()
if ask in ("no", "n"):
print("The question was:")
print(" ")
print("\033[1;32;0m", random_list)
print(" ")
time.sleep(4)
print("\033[1;35;0m", "The answer is:")
print(" ")
time.sleep(1)
print(".........")
if random_list == riddle1:
print(riddle1_Ans)
if random_list == riddle2:
print(riddle2_Ans)
if random_list == riddle3:
print(riddle3_Ans)
if random_list == riddle4:
print(riddle4_Ans)
if random_list == riddle5:
print(riddle5_Ans)
if random_list == riddle6:
print(riddle6_Ans)
if random_list == riddle7:
print(riddle7_Ans)
print(".........")
# The Game
def Introductin():
print(" ")
print("\033[1;36;0m", "Hello there, I'm Zelandini the host of the game. You will be guessing the answer of the " \
"coming riddles"
", you have 20 second to guess. Once the time ran out you have the chance to see the answer.")
print(" ")
game_start = input("Ready?Y/N:")
if game_start in ("yes", "y"):
play_game()
def play_game():
sec = 1
print(" ")
while sec != 4:
print("Game starts in", sec)
time.sleep(1)
sec += 1
if sec == 4:
Game_Start()
def Game_Start():
minutes = 1
print(" ")
print("\033[1;32;0m BEGIN!")
print("..............")
print("\033[1;32;0m ", "The riddle is", random_list)
print("..............")
while minutes != 21:
print(">>>>", minutes, "seconds")
time.sleep(1)
minutes += 1
if minutes == 21:
print(" ")
print("\033[1;34;0m", "TIMES OUT!")
break
restart()
welcome()
Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)