import random
import datetime


def color_game():
    colors = ["red", "orange", "yellow", "green", "blue", "pink", "purple", "brown", "black", "white"]
    secret = random.choice(colors)
    guess = input("What is my color? ").strip().lower()

    if guess == secret:
        print("Noice 😄")
    else:
        print(f"Wrong, it was {secret}.")


def madlib():
    friend = input("Enter a random funny name: ").strip()
    place = input("Enter a restaurant name: ").strip()
    food = input("Enter a weird food: ").strip()

    story = (
        f"One day me and my friend {friend} went to the restaurant called {place} "
        f"and ate a thing called {food}. It was so bad, so we went back home and went to sleep."
    )
    print(story)


def number_game(limit=10):
    secret = random.randint(1, limit)
    while True:
        guess_str = input(f"What number am I thinking of (1 to {limit})? ").strip()
        if guess_str.isdigit():
            guess = int(guess_str)
            break
        print("Please enter a valid whole number.")

    if guess == secret:
        print(f"You got it right, you had a 1/{limit} chance.")
    else:
        print(f"You got it wrong, it was {secret}.")


def semester_calculator():
    name = input("What is your name? ").strip()
    ans = input(f"Hi {name}, I am a semester calculator. Would you like to continue? (yes/no) ").strip().lower()

    if ans not in {"yes", "y"}:
        print("Ok, have a nice day.")
        return

    grades = []
    for sem in range(1, 5):
        while True:
            g = input(f"What is your semester {sem} grade? ").strip()
            try:
                grades.append(float(g))
                break
            except ValueError:
                print("Enter a number (example: 92 or 92.5).")

    avg = sum(grades) / len(grades)
    print(f"Average: {avg:.2f}")


def show_date():
    now = datetime.datetime.now()
    print(now.year)
    print(now.strftime("%A"))
    print(now.month)


def three_try_question(prompt, answer):
    for attempt in range(3):
        guess = input(prompt).strip()
        if guess.lower() == answer.lower():
            print("Correct Answer")
            return True
        if attempt < 2:
            print("Sorry, wrong answer, try again.")
    print(f"The correct answer is {answer}.")
    return False


def jojo_guessing_game():
    print("Word bank: Jonathan, Joseph, Jotaro, Josuke, Giorno, Jolyne, Johnny")
    score = 0

    questions = [
        ("Who is the main jojo of part 1? ", "Jonathan"),
        ("Who is the jojo of part 2? ", "Joseph"),
        ("Who is the jojo of part 3? ", "Jotaro"),
        ("Who is the jojo of part 4? ", "Josuke"),
        ("Who is the jojo of part 5? ", "Giorno"),
        ("Who is the jojo of part 6? ", "Jolyne"),
        ("Who is the jojo of part 7? ", "Johnny"),
        ("Who is the jojo of part 8? ", "Josuke"),
    ]

    for q, a in questions:
        if three_try_question(q, a):
            score += 1

    print(f"Your score is {score}/{len(questions)}")


def adventure_game():
    yes = {"yes", "y"}
    no = {"no", "n"}

    print(
        """
WELCOME! LET'S START THE ADVENTURE

You are standing outside of your house and you see a man running towards you and asking for urgent shelter.
Will you provide shelter to him? (yes/no)
"""
    )

    ans1 = input(">> ").strip().lower()

    if ans1 in yes:
        print("\nAfter 2 minutes, the police come and ask if the thief is in your house. Will you say yes or no?\n")
        ans2 = input(">> ").strip().lower()

        if ans2 in yes:
            print("\nYou are an honest person. He was a thief. You won the game.")
        elif ans2 in no:
            print("\nYou helped a thief. Now go to jail. Game over.")
        else:
            print("\nWrong input. Goodbye.")

    elif ans1 in no:
        print("\nNow he is trying to kill you. Will you knock him down? (yes/no)\n")
        ans3 = input(">> ").strip().lower()

        if ans3 in yes:
            print("\nCongrats! He was a thief and you helped the police catch him with your bravery.")
        elif ans3 in no:
            print("\nSorry, you are dead. He was a thief and he killed you. Game over.")
        else:
            print("\nWrong input. Goodbye.")

    else:
        print("\nWrong input. Goodbye.")


def animal_guess_game():
    score = 0
    questions = [
        ("Which bear lives at the North Pole? ", "polar bear"),
        ("Which is the fastest land animal? ", "cheetah"),
        ("Which is the largest animal? ", "blue whale"),
    ]

    for q, a in questions:
        if three_try_question(q, a):
            score += 1

    print(f"Your score is {score}/{len(questions)}")


def main():
    games = {
        "colorgame": color_game,
        "madlib": madlib,
        "number game": lambda: number_game(10),
        "number game on steroids": lambda: number_game(50),
        "semester calculator": semester_calculator,
        "the date": show_date,
        "jojo guessing game": jojo_guessing_game,
        "game": adventure_game,
        "guess game": animal_guess_game,
    }

    while True:
        print("\nGames:", ", ".join(games.keys()))
        choice = input("What game do you want to play? ").strip().lower()

        if choice in {"quit", "exit", "q"}:
            print("Bye.")
            break

        game = games.get(choice)
        if game is None:
            print("Not a valid game name. Try again.")
            continue

        game()

        again = input("\nPlay another game? (yes/no) ").strip().lower()
        if again not in {"yes", "y"}:
            print("Bye.")
            break


if __name__ == "__main__":
    main()
