Tag: #Game

  • Earth–Mars Orbital Transfer Animation Python Script

    This Python script animates a simplified simulation of Earth and Mars orbiting the Sun along circular paths, while a spacecraft travels between them using a basic interpolation trajectory with a sinusoidal arc. It dynamically updates the planet positions and labels to clearly indicate which is Earth (blue) and which is Mars (red).

    This script uses NumPy for efficient numerical computations and trigonometric functions, and Matplotlib (including mpl_toolkits.mplot3d for 3D rendering and matplotlib.animation for dynamic visualizations) to animate the planetary orbits and spacecraft trajectory. To install these libraries, open your Terminal and run:

    pip install numpy matplotlib

    (Use pip3 if you’re working with Python 3.)

    Click to view script…
    #!/usr/bin/env python3
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D  # needed for 3D projection
    from matplotlib.animation import FuncAnimation
    
    # -----------------------------------------
    # 1) Orbital and Planetary Parameters
    # -----------------------------------------
    # Simplified units: 1 "unit" = 1 Astronomical Unit (AU)
    # Time is in days
    
    # Orbital radii (approx in AU)
    R_EARTH = 1.0
    R_MARS  = 1.52
    
    # Orbital periods (approx in days)
    T_EARTH = 365.0
    T_MARS  = 687.0
    
    # Angular velocities (radians per day)
    w_EARTH = 2.0 * np.pi / T_EARTH
    w_MARS  = 2.0 * np.pi / T_MARS
    
    # Initial phases (starting positions)
    phi_earth0 = 0.0
    phi_mars0  = 0.0
    
    # Radii of the planets (for plotting spheres)
    EARTH_RADIUS = 0.05
    MARS_RADIUS  = 0.03
    
    # -----------------------------------------
    # 2) Define Planet Position Functions
    # -----------------------------------------
    def planet_position(time, R, omega, phi0=0.0):
        """
        Returns the (x, y, z) position of a planet orbiting in the XY plane.
        """
        x = R * np.cos(omega * time + phi0)
        y = R * np.sin(omega * time + phi0)
        z = 0.0
        return np.array([x, y, z])
    
    # -----------------------------------------
    # 3) Spacecraft Trajectory
    # -----------------------------------------
    def find_launch_day(t_range):
        """
        Finds a launch day in t_range where the Earth-Mars distance is minimized.
        """
        best_day = None
        min_dist = 1e9
        for t in t_range:
            earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
            mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
            dist = np.linalg.norm(mars_pos - earth_pos)
            if dist < min_dist:
                min_dist = dist
                best_day = t
        return best_day
    
    def spacecraft_trajectory(t, t_launch, t_arrival, home_func, target_func):
        """
        Computes a simple interpolated trajectory between two planets.
        Outside the travel window, it holds the departure or arrival position.
        """
        if t <= t_launch:
            return home_func(t_launch)
        elif t >= t_arrival:
            return target_func(t_arrival)
        else:
            # Fraction of travel completed
            frac = (t - t_launch) / (t_arrival - t_launch)
            pos_home = home_func(t_launch)
            pos_target = target_func(t_arrival)
            # Add a sinusoidal 'arc' in the Z direction for visual flair
            arc_height = 0.2 * np.sin(np.pi * frac)
            interp = (1 - frac) * pos_home + frac * pos_target
            interp[2] += arc_height
            return interp
    
    # -----------------------------------------
    # 4) Set Up the Animation Plot
    # -----------------------------------------
    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(111, projection='3d')
    
    # Function to draw a sphere (used for Earth and Mars)
    def plot_sphere(ax, center, radius, color, alpha=1.0):
        u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        ax.plot_surface(x, y, z, color=color, alpha=alpha)
    
    # Global variables to store our plot elements
    earth_surf = None
    mars_surf = None
    spacecraft_marker, = ax.plot([], [], [], 'go', markersize=6)
    earth_label = None
    mars_label = None
    
    # Time settings for the simulation (e.g., 1200 days)
    total_frames = 1000
    times = np.linspace(0, 1200, total_frames)
    
    # Find a simplistic launch day within the first 300 days
    launch_day = find_launch_day(range(300))
    travel_time = 180.0  # days for Earth-to-Mars travel
    arrival_day = launch_day + travel_time
    
    # Return trip parameters (optional)
    stay_time_on_mars = 100.0
    return_launch_day = arrival_day + stay_time_on_mars
    return_arrival_day = return_launch_day + 200.0
    
    # Utility to get the x, y, z coordinates for a sphere surface
    def _sphere_xyz(center, radius, n_u=20, n_v=10):
        u = np.linspace(0, 2*np.pi, n_u)
        v = np.linspace(0, np.pi, n_v)
        u, v = np.meshgrid(u, v)
        x = center[0] + radius * np.cos(u) * np.sin(v)
        y = center[1] + radius * np.sin(u) * np.sin(v)
        z = center[2] + radius * np.cos(v)
        return x, y, z
    
    # -----------------------------------------
    # 5) Animation Update Function
    # -----------------------------------------
    def update(frame):
        global earth_surf, mars_surf, earth_label, mars_label
    
        # Current time in days
        t = times[frame]
    
        # Update positions for Earth and Mars
        earth_pos = planet_position(t, R_EARTH, w_EARTH, phi_earth0)
        mars_pos  = planet_position(t, R_MARS,  w_MARS,  phi_mars0)
    
        # Remove old spheres if they exist
        if earth_surf is not None:
            earth_surf.remove()
        if mars_surf is not None:
            mars_surf.remove()
    
        # Plot new spheres for Earth and Mars
        earth_surf = ax.plot_surface(*_sphere_xyz(earth_pos, EARTH_RADIUS),
                                     color='blue', alpha=0.6)
        mars_surf = ax.plot_surface(*_sphere_xyz(mars_pos, MARS_RADIUS),
                                    color='red', alpha=0.6)
        
        # Remove old labels if they exist
        if earth_label is not None:
            earth_label.remove()
        if mars_label is not None:
            mars_label.remove()
        
        # Add new text labels above each planet
        earth_label = ax.text(earth_pos[0], earth_pos[1], earth_pos[2] + EARTH_RADIUS + 0.05,
                              'Earth', color='blue', fontsize=10, weight='bold')
        mars_label = ax.text(mars_pos[0], mars_pos[1], mars_pos[2] + MARS_RADIUS + 0.05,
                             'Mars', color='red', fontsize=10, weight='bold')
        
        # Update spacecraft position based on current time
        if t < return_launch_day:
            # Outbound: Earth to Mars
            sc_pos = spacecraft_trajectory(t, launch_day, arrival_day,
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0),
                                           lambda tau: planet_position(tau, R_MARS,  w_MARS,  phi_mars0))
        else:
            # Return: Mars to Earth
            sc_pos = spacecraft_trajectory(t, return_launch_day, return_arrival_day,
                                           lambda tau: planet_position(tau, R_MARS, w_MARS, phi_mars0),
                                           lambda tau: planet_position(tau, R_EARTH, w_EARTH, phi_earth0))
        
        # Update the spacecraft marker (green dot)
        spacecraft_marker.set_data([sc_pos[0]], [sc_pos[1]])
        spacecraft_marker.set_3d_properties([sc_pos[2]])
        
        # Return all updated artists
        return earth_surf, mars_surf, spacecraft_marker, earth_label, mars_label
    
    # -----------------------------------------
    # 6) Plot Aesthetics and Animation Setup
    # -----------------------------------------
    ax.set_xlim(-1.6, 1.6)
    ax.set_ylim(-1.6, 1.6)
    ax.set_zlim(-0.6, 0.6)
    ax.set_xlabel('X (AU)')
    ax.set_ylabel('Y (AU)')
    ax.set_zlabel('Z')
    ax.set_title('Earth–Mars Orbits with Spacecraft Launch')
    
    # Draw the Sun at the origin as a yellow sphere
    plot_sphere(ax, [0, 0, 0], 0.1, 'yellow', alpha=0.9)
    
    # Create the animation
    anim = FuncAnimation(fig, update, frames=total_frames, interval=30, blit=False)
    
    plt.show()
  • True or False Trivia Challenge Python Script

    This interactive quiz game lets you explore fun categories by answering unique True/False questions. With each question, you’ll receive immediate feedback and an insightful explanation to expand your knowledge.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Animal Trivia",
                "questions": [
                    {
                        "question": "Elephants are the only animals that can't jump.",
                        "answer": True,
                        "description": "True! Due to their massive weight and unique limb structure, elephants are physically incapable of jumping."
                    },
                    {
                        "question": "Bats are blind.",
                        "answer": False,
                        "description": "False! While bats use echolocation, they also have functional eyes and can see."
                    },
                    {
                        "question": "A group of flamingos is called a 'flamboyance'.",
                        "answer": True,
                        "description": "True! The collective noun for flamingos is indeed 'flamboyance', which suits their vibrant appearance."
                    },
                    {
                        "question": "An octopus has three hearts.",
                        "answer": True,
                        "description": "True! Octopuses have two branchial hearts and one systemic heart."
                    },
                    {
                        "question": "Goldfish have a memory span of just three seconds.",
                        "answer": False,
                        "description": "False! Goldfish can actually remember things for months."
                    }
                ]
            },
            "2": {
                "name": "Space Facts",
                "questions": [
                    {
                        "question": "A day on Venus is longer than its year.",
                        "answer": True,
                        "description": "True! Venus rotates very slowly, making its day longer than the time it takes to orbit the Sun."
                    },
                    {
                        "question": "There is no sound in space.",
                        "answer": True,
                        "description": "True! Space is a vacuum, so sound cannot travel."
                    },
                    {
                        "question": "Mars has the tallest volcano in the solar system, Olympus Mons.",
                        "answer": True,
                        "description": "True! Olympus Mons on Mars stands about 22 kilometers high, making it the tallest volcano known."
                    },
                    {
                        "question": "Saturn is the only planet with rings.",
                        "answer": False,
                        "description": "False! While Saturn’s rings are the most prominent, Jupiter, Uranus, and Neptune also have ring systems."
                    },
                    {
                        "question": "The footprints on the Moon will disappear over time due to wind erosion.",
                        "answer": False,
                        "description": "False! The Moon has no atmosphere or wind, so the footprints will likely remain for millions of years."
                    }
                ]
            },
            "3": {
                "name": "History Myths",
                "questions": [
                    {
                        "question": "Napoleon Bonaparte was extremely short.",
                        "answer": False,
                        "description": "False! Napoleon was of average height for his era; the myth of his short stature comes from a misunderstanding of French measurements."
                    },
                    {
                        "question": "The Great Wall of China is visible from space.",
                        "answer": False,
                        "description": "False! The Great Wall is very narrow and follows the natural contours of the land, making it nearly impossible to see from space with the naked eye."
                    },
                    {
                        "question": "Vikings wore horned helmets.",
                        "answer": False,
                        "description": "False! There is no historical evidence that Vikings ever wore horned helmets; this image was popularized by 19th-century artists."
                    },
                    {
                        "question": "The French Revolution began in 1789.",
                        "answer": True,
                        "description": "True! The French Revolution, which reshaped France and influenced modern democracies, began in 1789."
                    },
                    {
                        "question": "Christopher Columbus made his first voyage to the Americas in 1492.",
                        "answer": True,
                        "description": "True! In 1492, Columbus set sail, marking the beginning of European exploration of the Americas."
                    }
                ]
            }
        }
    
        print("Welcome to the True/False Quiz Game!")
        
        while True:
            print("\nChoose a category for your quiz:")
            for key, cat in categories.items():
                print(f"{key}. {cat['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Thanks for playing! Goodbye!")
                break
            
            if choice not in categories:
                print("Invalid choice. Please try again.")
                continue
            
            selected_cat = categories[choice]
            print(f"\nYou selected: {selected_cat['name']}")
            # Create a local copy of the questions list so each question is shown only once.
            available_questions = selected_cat["questions"].copy()
            
            while available_questions:
                question = random.choice(available_questions)
                available_questions.remove(question)
                
                print("\n" + question["question"])
                user_answer = input("Type T for True or F for False: ").strip().lower()
                
                if user_answer not in ["t", "f"]:
                    print("Invalid input. Please type 'T' or 'F'.")
                    continue
                
                user_bool = True if user_answer == "t" else False
                
                if user_bool == question["answer"]:
                    print("Correct!")
                else:
                    print("Incorrect!")
                
                print("Explanation:", question["description"])
                
                # Check if there are more questions available.
                if available_questions:
                    another = input("\nWould you like another question from this category? (y/n): ").strip().lower()
                    if another != "y":
                        break
                else:
                    print("\nNo more questions left in this category.")
                    
    if __name__ == "__main__":
        main()
  • Historical News Fun Facts Python Script

    This Python script provides an interactive and engaging way to learn about major historical news events. Users can choose from a variety of categories and receive a random, interesting fact from each, making history both fun and informative.

    Click to view script…
    #!/usr/bin/env python3
    import random
    
    def main():
        categories = {
            "1": {
                "name": "Wars & Conflicts",
                "facts": [
                    "World War II (1939-1945) saw the largest mobilization of military forces in history.",
                    "The American Civil War (1861-1865) led to the abolition of slavery in the United States.",
                    "World War I (1914-1918) introduced modern warfare techniques like tanks and chemical warfare.",
                    "The Vietnam War sparked significant anti-war protests and shaped global politics for decades.",
                    "The Korean War (1950-1953) ended in an armistice, leaving the Korean Peninsula divided.",
                    "The Gulf War (1990-1991) was one of the first conflicts broadcast live on television.",
                    "The Napoleonic Wars reshaped Europe in the early 19th century.",
                    "The Crimean War (1853-1856) saw the first use of the telegraph for military communication.",
                    "The Thirty Years' War (1618-1648) was one of the longest and most destructive conflicts in Europe.",
                    "The Falklands War (1982) highlighted the lingering effects of colonial disputes."
                ]
            },
            "2": {
                "name": "Political Milestones",
                "facts": [
                    "The fall of the Berlin Wall in 1989 symbolized the end of the Cold War.",
                    "Nelson Mandela's release in 1990 marked a significant step toward ending apartheid in South Africa.",
                    "The Declaration of Independence in 1776 laid the foundation for the United States.",
                    "The French Revolution (1789-1799) radically transformed France’s political and social structure.",
                    "India gained independence from British colonial rule in 1947.",
                    "The establishment of the United Nations in 1945 aimed to promote peace and cooperation globally.",
                    "The suffragette movement secured voting rights for women in many countries during the early 20th century.",
                    "The end of the Cold War in 1991 reshaped global political alliances.",
                    "The formation of the European Union helped unify post-war Europe.",
                    "The Arab Spring in the early 2010s spurred political change across several Middle Eastern countries."
                ]
            },
            "3": {
                "name": "Tech & Science Breakthroughs",
                "facts": [
                    "The Apollo 11 moon landing in 1969 was watched live by millions around the globe.",
                    "The invention of the internet revolutionized communication and information sharing.",
                    "The Human Genome Project, completed in 2003, mapped the entire human genetic code.",
                    "The launch of the Hubble Space Telescope in 1990 expanded our view of the universe.",
                    "The discovery of penicillin in 1928 marked the beginning of modern antibiotics.",
                    "The advent of smartphones has transformed everyday communication and connectivity.",
                    "ENIAC, one of the first computers built in 1945, paved the way for the computer age.",
                    "Quantum computing promises to tackle problems beyond the capabilities of classical computers.",
                    "The discovery of the Higgs boson in 2012 confirmed the mechanism that gives particles mass.",
                    "CRISPR technology is revolutionizing genetics through precise gene editing."
                ]
            },
            "4": {
                "name": "Natural Disasters",
                "facts": [
                    "The 2004 Indian Ocean tsunami is one of the deadliest natural disasters in modern history.",
                    "The eruption of Mount Vesuvius in AD 79 famously buried the Roman cities of Pompeii and Herculaneum.",
                    "The 1906 San Francisco earthquake led to massive destruction and a major rebuild of the city.",
                    "Hurricane Katrina in 2005 devastated the Gulf Coast region of the United States.",
                    "The Great Galveston Hurricane of 1900 remains the deadliest natural disaster in U.S. history.",
                    "The 2011 Tōhoku earthquake and tsunami in Japan triggered a nuclear crisis at Fukushima.",
                    "The Dust Bowl of the 1930s severely impacted agriculture and displaced thousands in the American Midwest.",
                    "The 1980 eruption of Mount St. Helens was one of the most significant volcanic events in U.S. history.",
                    "The Lisbon earthquake of 1755 had far-reaching effects on European philosophy and society.",
                    "The Bhola cyclone of 1970 was one of the most catastrophic tropical cyclones ever recorded."
                ]
            },
            "5": {
                "name": "Cultural & Entertainment Events",
                "facts": [
                    "The Beatles’ appearance on The Ed Sullivan Show in 1964 kick-started Beatlemania in the U.S.",
                    "Woodstock in 1969 became an iconic symbol of the counterculture movement.",
                    "The launch of MTV in 1981 revolutionized the music industry and pop culture.",
                    "Blockbuster movies emerged in the 1970s, forever changing the film industry.",
                    "The first Academy Awards in 1929 established a global benchmark for cinematic achievement.",
                    "Reality TV's rise in the early 2000s reshaped modern television programming.",
                    "The global popularity of video games has transformed entertainment and technology industries.",
                    "Social media platforms in the 21st century have redefined celebrity culture and public interaction.",
                    "Streaming services have dramatically changed how audiences consume films and television shows.",
                    "Internet memes have become a defining aspect of digital culture in recent years."
                ]
            }
        }
        
        while True:
            print("\n=== Fun Fact Utility: Biggest News Events in History ===")
            print("Choose a category for a fun fact:")
            for key, value in categories.items():
                print(f"{key}. {value['name']}")
            print("Q. Quit")
            
            choice = input("Enter your choice: ").strip().lower()
            if choice == 'q':
                print("Goodbye!")
                break
            elif choice in categories:
                fact = random.choice(categories[choice]["facts"])
                print(f"\nFun Fact from {categories[choice]['name']}:")
                print(fact)
            else:
                print("Invalid choice. Please select a valid category.")
    
    if __name__ == "__main__":
        main()
  • Rock, Paper, Scissors JavaScript Game

    This Node.js script lets you challenge the computer in a classic match of Rock, Paper, Scissors. Simply enter your move, and the computer will randomly choose its move, with the game determining the winner based on standard rules.

    Click to view script…
    /*
     * Rock, Paper, Scissors Game
     *
     * Instructions:
     *   1. Enter your move: "rock", "paper", or "scissors".
     *   2. The computer will randomly choose its move.
     *   3. The game will then announce the winner:
     *      - Rock crushes scissors.
     *      - Scissors cuts paper.
     *      - Paper covers rock.
     *
     * Enjoy the game!
     */
    
    const readline = require('readline');
    
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    
    const choices = ["rock", "paper", "scissors"];
    
    // Function to randomly select the computer's choice
    function getComputerChoice() {
      const randomIndex = Math.floor(Math.random() * choices.length);
      return choices[randomIndex];
    }
    
    // Function to determine the result of the game
    function getResult(userChoice, computerChoice) {
      if (userChoice === computerChoice) {
        return "It's a tie!";
      }
      if (userChoice === "rock") {
        return computerChoice === "scissors" ? "You win! Rock crushes scissors." : "You lose! Paper covers rock.";
      }
      if (userChoice === "paper") {
        return computerChoice === "rock" ? "You win! Paper covers rock." : "You lose! Scissors cuts paper.";
      }
      if (userChoice === "scissors") {
        return computerChoice === "paper" ? "You win! Scissors cuts paper." : "You lose! Rock crushes scissors.";
      }
    }
    
    // Main game loop
    function playGame() {
      rl.question("Enter your move (rock, paper, or scissors): ", (answer) => {
        let userChoice = answer.trim().toLowerCase();
        if (!choices.includes(userChoice)) {
          console.log("Invalid move. Please choose rock, paper, or scissors.");
          return playGame();
        }
        const computerChoice = getComputerChoice();
        console.log(`Computer chose: ${computerChoice}`);
        const result = getResult(userChoice, computerChoice);
        console.log(result);
        rl.question("Play again? (yes/no): ", (response) => {
          if (response.trim().toLowerCase().startsWith("y")) {
            playGame();
          } else {
            console.log("Thanks for playing!");
            rl.close();
          }
        });
      });
    }
    
    console.log("=== Rock, Paper, Scissors Game ===");
    playGame();
  • Reverse Word Puzzle JavaScript Game

    This script randomly selects a word from a list, reverses it, and challenges the player to guess the original word. It demonstrates basic Node.js functionality, including using the readline module for handling terminal input.

    Click to view script…
    // reverseWordPuzzle.js
    
    // List of words for the puzzle
    const words = ['apple', 'banana', 'orange', 'strawberry', 'grape', 'pineapple', 'kiwi'];
    
    // Function to reverse a given word
    function reverseWord(word) {
      return word.split('').reverse().join('');
    }
    
    // Function to pick a random word from the array
    function getRandomWord() {
      return words[Math.floor(Math.random() * words.length)];
    }
    
    // Main function to run the game
    function playGame() {
      const originalWord = getRandomWord();
      const reversedWord = reverseWord(originalWord);
      
      console.log("=== Reverse Word Puzzle ===");
      console.log(`Unscramble this reversed word: ${reversedWord}`);
    
      // Create an interface for user input
      const readline = require('readline');
      const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
      });
    
      // Ask the user for their guess
      rl.question("Your guess: ", (answer) => {
        if(answer.trim().toLowerCase() === originalWord.toLowerCase()){
          console.log("Correct! Well done.");
        } else {
          console.log(`Incorrect. The correct word was: ${originalWord}`);
        }
        rl.close();
      });
    }
    
    // Start the game
    playGame();
  • Virtual Pet Simulator Python Script

    A simple virtual pet game where you can feed, play with, and put your pet to sleep—keep it happy and healthy or watch things go south.

    Click to view script…
    import time
    
    class VirtualPet:
        def __init__(self, name):
            self.name = name
            self.hunger = 5      # 0 means full, 10 means starving
            self.happiness = 5   # 0 means sad, 10 means happy
            self.energy = 5      # 0 means tired, 10 means full of energy
            self.alive = True
    
        def feed(self):
            if self.hunger > 0:
                self.hunger -= 1
                print(f"You fed {self.name}. Hunger is now {self.hunger}/10.")
            else:
                print(f"{self.name} isn't hungry right now!")
    
        def play(self):
            if self.energy > 0:
                self.happiness = min(10, self.happiness + 1)
                self.energy -= 1
                self.hunger = min(10, self.hunger + 1)
                print(f"You played with {self.name}. Happiness: {self.happiness}/10, Energy: {self.energy}/10, Hunger: {self.hunger}/10.")
            else:
                print(f"{self.name} is too tired to play.")
    
        def sleep(self):
            print(f"{self.name} is sleeping...")
            time.sleep(2)
            self.energy = min(10, self.energy + 3)
            self.hunger = min(10, self.hunger + 1)
            print(f"{self.name} woke up. Energy: {self.energy}/10, Hunger: {self.hunger}/10.")
    
        def status(self):
            print(f"\n{self.name}'s Status:")
            print(f"  Hunger: {self.hunger}/10")
            print(f"  Happiness: {self.happiness}/10")
            print(f"  Energy: {self.energy}/10")
    
        def update(self):
            # Stats change over time
            self.hunger = min(10, self.hunger + 1)
            self.happiness = max(0, self.happiness - 1)
            self.energy = max(0, self.energy - 1)
            if self.hunger == 10 or self.happiness == 0 or self.energy == 0:
                self.alive = False
                print(f"\nSadly, {self.name} has passed away due to neglect...")
    
    def main():
        pet_name = input("Name your pet: ")
        pet = VirtualPet(pet_name)
        print(f"Welcome, {pet.name}!")
        
        while pet.alive:
            pet.status()
            print("\nActions: feed | play | sleep | exit")
            action = input("What do you want to do? ").strip().lower()
            
            if action == "feed":
                pet.feed()
            elif action == "play":
                pet.play()
            elif action == "sleep":
                pet.sleep()
            elif action == "exit":
                print("Goodbye!")
                break
            else:
                print("Invalid action. Try again.")
            
            pet.update()
        
        print("Game over.")
    
    if __name__ == '__main__':
        main()