1

I'm a very new beginner coder and I don't know much yet. I am trying to create a guessing game, and I want to add a timer to the program. The way the timer would work would be that I set up a set amount of time i.e. 60 seconds and once the time has run out the program would stop and basically be like "sorry you ran out of time. Would you like to try again?"

I've already searched for some videos on YouTube and on Stackoverflow but I either don't understand it or I'm unable to do it.

https://www.youtube.com/watch?v=Mp6YMt8MSAU

I've watched this video like 4 times and still have no clue how to do it. So if anyone is willing to explain to me/show me how to add time that would be much appreciated

def main():
    import random
    n = random.randint(1, 99)
    chances = 5
    guess = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: " ))
    while n != "guess":
        chances -=1
        if chances ==0:
            print("out of chances, it is now player 2's turn to play. The number was", n)
            break
        if guess < n:
            print("guess is low you have",chances,"chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high you have",chances, "chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances, "chances left")
            break
            
        import random
    n1 = random.randint(1, 99)
    chances1 = 0
    guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
    while n1 != "guess":
        chances1 +=1
        if chances1 ==5:
            print("out of chances, the number was", n1)
            break
        if guess1 < n1:
            print("guess is low you have",chances1,"chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        elif guess > n1:
            print ("guess is high you have",chances1, "chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances1, "chances left")
            break
    retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
    if retry == "yes":
        main()
    elif retry == "no":
        print("Okay. have a nice day! :D ")
    else:
        print("Invalid input")
main()

This is my code. Any feedback would be appreciated.

OmniOwl
  • 5,477
  • 17
  • 67
  • 116

2 Answers2

0

(I don't know how much do you know about python and programming so I'll use a really simple language)

Well, if your game don't have to run while the timer is active you could use the sleep function of the time library, and writhing something like this:

import time

time.sleep("time amount")
print("I'me sorry but you run out of time!")
print("Do you wanna retry ?")

Whit the "command" time.sleep, python will stop the entire program for the amount of time you've selected

(So if you have to play the game while the timer is running don't use the time.sleep method)

Instead if the timer have to be active while you're playing the game you should use "threading". threading is a library that allows you to do really simple timers, but not only. Making a timer with threading it could be more complex for you but not really.

You have to write a function to call when the timer is over like that:

def time_over():
    print("I'm sorry but the time is over !")
    print("Do you want to play again ? ")

After that you have to create the timer:

timer_name = threading.timer("time amount", function) 

Eventually you have to start the timer writing:

timer_name.start()

In that way python will: 1 - Import the threading Library 2 - Create the timer whit the amount of time do you want 3 - Start the timer 4 - Activate the function you've wrote when the time will run out

If you need more info about one of these methods, write a comment and I will answer to your question as faster as I can.

Have a good day :)

Step
  • 36
  • 6
  • hi thr!! im rly rly rly noob at coding HAHA but your explanation seems somewhat understandable? Can i ask whr im supposed to put the def time over thingy at in my code? again thank you so much for the help! i rly appreciate it – tiger1234522 Jul 21 '20 at 10:43
  • So the "timer_end" thing is a function. You've to create a function to call when the timer runs out. So when the threading timer will end it will call automatically the function. You must do a function to run a threading timer. if you don't know what functions are or how they works i advise you to watch a really simple python tutorial like freeCodeCamp's ones. Here below I'll leave to you the link to their python course, that might help you, I hope I had helped: https://www.youtube.com/watch?v=rfscVS0vtbw (P.S. in the course they advise you to install an IDE, but it's not necessary) – Step Jul 21 '20 at 11:17
0

To solve your problem, you will have to use a Thread. I took your code I added the Thread at the beginning, try to have a look.

A Thread is an object that can execute a function (its run function) beside the main program. It is so-called Parallel Programming.
Here you need that because you want to:

  1. Check the Input of the player
  2. Count Down

I do not correct your code or rewrite it, I just added the Thread and make it work. It is pretty easy:

  1. I call sleep for a given amount of time (_TIME_LIMIT]
  2. Make a little noise when the timer ended.
  3. I set a variable to True, that means that the timer ended

With a bit of rewriting, you will be able to interrupt your main loop when the Thread change the variable. But that is out the scope of the initial question, feel free to improve your game.
For the moment, you need to enter a number to know if the time was ended or not. That is why I added the little noise (if not you would have no cue).

Please, be free to ask any questions.
Hope this will help you.


from threading import Thread
from time import sleep

import random


_TIME_OUT = [False, False]

_TIME_LIMIT = 1

class MyThread(Thread):
    def __init__(self, time_out, player):
        Thread.__init__(self)
        self.time_out = time_out
        self.player = player

    def run(self):
        sleep(self.time_out)
        _TIME_OUT[self.player - 1] = True
        print('\a', end="") # Make a noise

def main():
    _TIME_OUT[0] = False
    _TIME_OUT[1] = False

    tread_1 = MyThread(_TIME_LIMIT, 1)

    n = random.randint(1, 99)
    chances = 5

    
    tread_1.start()
    print(f"You have {_TIME_LIMIT} sec")

    guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: " ))
    while n != "guess" and not _TIME_OUT[0]:
        print(not _TIME_OUT, _TIME_OUT)
        chances -=1
        if chances == 0:
            print("out of chances, it is now player 2's turn to play. The number was", n)
            break
        if guess < n:
            print("guess is low you have",chances,"chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high you have",chances, "chances left")
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances, "chances left")
            break
            
    if _TIME_OUT[0]:
        print("Sorry, out of time!")

    tread_2 = MyThread(_TIME_LIMIT, 2)

    n1 = random.randint(1, 99)
    chances1 = 0

    tread_2.start()
    print(f"You have {_TIME_LIMIT} sec")

    guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances: "))
    while n1 != "guess" and not _TIME_OUT[1]:
        chances1 +=1
        if chances1 ==5:
            print("out of chances, the number was", n1)
            break
        if guess1 < n1:
            print("guess is low you have",chances1,"chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        elif guess > n1:
            print ("guess is high you have",chances1, "chances left")
            guess1 = int(input("Enter an integer from 1 to 99: "))
        else:
            print("you guessed it and have", chances1, "chances left")
            break

    if _TIME_OUT[1]:
        print("Sorry, out of time!")

    retry=input("would you like to play again? (please choose either 'yes' or 'no' )")
    if retry == "yes":
        main()
    elif retry == "no":
        print("Okay. have a nice day! :D ")
    else:
        print("Invalid input")


if __name__ == "__main__":
    main()
Adrien Kaczmarek
  • 530
  • 4
  • 13
  • hi thanks for the reply, can i ask what "sleep" means and what sound you are talking about haha i dont hear anyth when i start the program? and also can u give me any pointers on how to just immediately stop the game once the timer has run up. again, thank you so much for your help – tiger1234522 Jul 21 '20 at 10:42
  • `sleep` is just a function that pause your program for a given amount a time. Here the function is executed in a thread (parallel branch) so it only pause its branch (not the main). The sound is just the basic notification sound (works on Linux and MacOS, don't know if it works too on Windows), you obtain this sound by printing `\a`. – Adrien Kaczmarek Jul 21 '20 at 13:18
  • i see... can i ask why when i run the programme there is a false, false thing and how do i remove it – tiger1234522 Jul 22 '20 at 13:59
  • Just remove the `print(not _TIME_OUT, _TIME_OUT)` statement. Just look at the `print` statement and try to figure it out which one you want to delete. Here as you see it was very straight forward. Hope this help you – Adrien Kaczmarek Jul 22 '20 at 14:07