import threading, time
import sys
import random
from queue import Queue

MIN, MAX = 0, 10  # number range in which random integer is created
THRESHOLD = 15  # time given to a player

q = Queue()  # queue for data exchange between threads


def countdown(n: int):
    '''Countdown function. From n to 0'''
    num = q.get()
    while n > 0 and q.empty():
        #sys.stderr.write(f'\n{n}')
        time.sleep(1)
        n -= 1
    if q.empty():
        #sys.stderr.write('\n0')
        sys.stderr.write(f'\nOVER. The number was {num}')


def game():
    '''Represents the game. Must be executed in daemon'''
    num = random.randint(MIN, MAX)
    q.put(num)
    print(f'Game started. Enter your number (from {MIN} to {MAX})')
    while True:
        try:
            guess = int(input('Your guess: '))
        except Exception:
            print('wrong format... try again') 
            continue
        if guess > num:
            print(f'Wrong! {guess} is GREATER than the target')
        elif guess < num:
            print(f'Wrong! {guess} is SMALLER than the target')
        elif guess == num:
            print(f'You are RIGHT! {guess} is the number')
            q.put('done')
            break


def main():
    counter = threading.Thread(target=countdown, args=[THRESHOLD])
    daemon_game = threading.Thread(target=game, daemon=True)
    counter.start()
    daemon_game.start()


if __name__ == '__main__':
    main()
