Build a Digital Pet Game - Build a Digital Pet Game

Tell us what’s happening:

My tests keep getting failed even though it is written correctly. Please help me

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: index.tsx */

// index.tsx
const { useState, useEffect } = React;

export enum Action {
  EAT = "EAT",
  PLAY = "PLAY",
  SLEEP = "SLEEP",
}

export enum PetMood {
  HAPPY = "HAPPY",
  EXCITED = "EXCITED",
  CONTENT = "CONTENT",
  SAD = "SAD",
  TIRED = "TIRED",
  SICK = "SICK",
  HUNGRY = "HUNGRY",
}

const ACTION_IDS: Record<Action, string> = {
  [Action.EAT]: "eat-action",
  [Action.PLAY]: "play-action",
  [Action.SLEEP]: "sleep-action",
};

export const MOOD_EMOJI: Record<PetMood, string> = {
  [PetMood.HAPPY]: "😊",
  [PetMood.EXCITED]: "🤩",
  [PetMood.CONTENT]: "😌",
  [PetMood.SAD]: "😢",
  [PetMood.TIRED]: "😴",
  [PetMood.SICK]: "🤒",
  [PetMood.HUNGRY]: "🍖",
};

type Stats = {
  hunger: number;
  energy: number;
  happiness: number;
};

const MIN_STAT = 0;
const MAX_STAT = 100;
const TICK_MS = 500; // idle decay interval
const TICK_STEP = 5; // idle decay amount per tick

const clamp = (value: number): number =>
  Math.min(MAX_STAT, Math.max(MIN_STAT, value));

const getLevel = (value: number): "high" | "medium" | "low" => {
  if (value >= 67) return "high";
  if (value >= 34) return "medium";
  return "low";
};

const getMood = ({ hunger, energy, happiness }: Stats): PetMood => {
  if (hunger > 70) return PetMood.HUNGRY;
  if (energy < 30) return PetMood.TIRED;
  if (happiness < 30) return PetMood.SAD;
  if (happiness > 80 && energy > 70) return PetMood.EXCITED;
  if (happiness > 60) return PetMood.HAPPY;
  return PetMood.CONTENT;
};

export const PetGame = () => {
  const [petName, setPetName] = useState<string>("");
  const [gameStarted, setGameStarted] = useState<boolean>(false);
  const [stats, setStats] = useState<Stats>({
    hunger: 0,
    energy: 100,
    happiness: 100,
  });

  // Idle decay: the pet gets hungrier and less happy over time.
  useEffect(() => {
    if (!gameStarted) return;
    const id = setInterval(() => {
      setStats((prev) => ({
        ...prev,
        hunger: clamp(prev.hunger + TICK_STEP),
        happiness: clamp(prev.happiness - TICK_STEP),
      }));
    }, TICK_MS);
    return () => clearInterval(id);
  }, [gameStarted]);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (petName.trim() === "") return;
    setPetName(petName.trim());
    setGameStarted(true);
  };

  const handleAction = (action: Action) => {
    setStats((prev) => {
      switch (action) {
        case Action.EAT:
          return {
            ...prev,
            hunger: clamp(prev.hunger - 10),
            energy: clamp(prev.energy + 5),
          };
        case Action.PLAY:
          return {
            ...prev,
            energy: clamp(prev.energy - 10),
            happiness: clamp(prev.happiness + 10),
          };
        case Action.SLEEP:
          return {
            ...prev,
            hunger: clamp(prev.hunger + 10),
            energy: clamp(prev.energy + 20),
          };
        default:
          return prev;
      }
    });
  };

  const mood = getMood(stats);

  const statRows = [
    { key: "hunger", icon: "🍖", name: "Hunger", value: stats.hunger, level: getLevel(MAX_STAT - stats.hunger) },
    { key: "happiness", icon: "😊", name: "Happiness", value: stats.happiness, level: getLevel(stats.happiness) },
    { key: "energy", icon: "⚡", name: "Energy", value: stats.energy, level: getLevel(stats.energy) },
  ];

  return (
    <div className="base-container">
      <header>
        <h1>Digital Pet Game</h1>
      </header>

      {!gameStarted && (
        <div className="info-panel">
          <form className="start-questions" onSubmit={handleSubmit}>
            <label htmlFor="pet-name">What would you like to name your pet?</label>
            <div>
              <input
                id="pet-name"
                type="text"
                value={petName}
                onChange={(e) => setPetName(e.target.value)}
                placeholder="Enter a name"
              />
              <button id="set-name-btn" type="submit">
                Start Game
              </button>
            </div>
          </form>
        </div>
      )}

      {gameStarted && (
        <div className="game-container">
          <h2 className="pet-name">{petName}</h2>
          <div className="pet-sprite" id="pet-sprite">
            {MOOD_EMOJI[mood]}
          </div>
          <p id="pet-mood">{`Mood: ${mood}`}</p>

          <div className="stats-grid">
            {statRows.map((stat) => (
              <div className="stat stat-bar" id={`${stat.key}-stat`} key={stat.key}>
                <div className="stat-header">
                  <div className="stat-label">
                    <span className="stat-icon">{stat.icon}</span>
                    <span className="stat-name">{stat.name}</span>
                  </div>
                  <span className="stat-value">{stat.value}</span>
                </div>
                <div className="stat-progress">
                  <div
                    className={`stat-fill ${stat.level}`}
                    style={{ width: `${stat.value}%` }}
                  />
                </div>
              </div>
            ))}
          </div>

          <div className="pet-buttons">
            {[Action.EAT, Action.PLAY, Action.SLEEP].map((action) => (
              <button
                key={action}
                className="pet-button"
                id={ACTION_IDS[action]}
                onClick={() => handleAction(action)}
              >
                {action}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36

Challenge Information:

Build a Digital Pet Game - Build a Digital Pet Game

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-digital-pet-game/68c362b379059c388d3874f2.md at main · freeCodeCamp/freeCodeCamp · GitHub

I use this code and fortunately it works

code removed by moderator

Congratulations on solving the challenge! You should be proud of your achievement…we are! But we are removing your working solution, so it is not available to others who have not yet done the work to get there. Again, congrats!