Categories
React Projects

Create a Whack a Mole Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a whack a mole game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app whack-a-mole

with NPM to create our React project.

Create the Whack a Mole Game

To create the whack a mole game, we write:

import React, { useState } from "react";

export default function App() {
  const [index, setIndex] = useState(0);
  const [score, setScore] = useState(0);
  const [timer, setTimer] = useState();

  const generateIndex = () => {
    setIndex(Math.floor(Math.random() * 6));
  };

  const startGame = () => {
    const timer = setInterval(generateIndex, 2000);
    setTimer(timer);
  };

  const endGame = () => {
    clearInterval(timer);
    setScore(0);
    setIndex(0);
  };

  const onClick = (n) => {
    if (index === n) {
      setScore((score) => score + 1);
    }
  };

  return (
    <div>
      <style>
        {`
        .hole {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          border-radius: 50%;
        }

        .container {
          display: inline-block;
        }

        img {
          width: 50px;
          height: 50px;
        }
      `}
      </style>
      <button onClick={startGame}>start game</button>
      <button onClick={endGame}>end game</button>
      <p>score: {score}</p>
      <div>
        {Array(6)
          .fill()
          .map((_, n) => {
            if (index === n) {
              return (
                <div className="container">
                  <img
                    src="https://grid.gograph.com/happy-mole-cartoon-vector-art_gg68718247.jpg"
                    alt="mole"
                    onClick={() => onClick(n)}
                  />
                </div>
              );
            } else {
              return (
                <div className="container">
                  <div className="hole"></div>
                </div>
              );
            }
          })}
      </div>
    </div>
  );
}

We create index , score , and timer states.

index is the index of the div to show the mole in.

Below that, we have the generateIndex function to generate the index to show the model.

startGame calls setInterval to start the timer.

We call setTimer to set the returned timer .

The endGame function calls clearInterval to clear the timer.

It also calls setScore and setIndex to reset the score and index values to 0.

Also, we have the onClick function to check if index is the same as n .

n is the index of the div that we clicked on.

If they’re the same, then we increase the score by calling setScore with a callback to return the existing score plus 1.

Below that, we have some styles to make the divs round.

We make them round with the border-radius .

Below that, we have buttons that call startGame and endGame respectively with we click them.

Then we add the score display.

And finally, we have an array with 6 slots rendered into divs.

If index is the same as n , we display the mole image.

Otherwise, we show an empty hole.

The img element has an onClick handler that calls onClick to check if what was clicked is where the mole image is displayed.

Conclusion

We can create a whack a mole game easily with React and Javascript.

Categories
React Projects

Create a Height Converter App with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a height converter app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app height-converter

with NPM to create our React project.

Create the Height Converter App

To create the height converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [feet, setFeet] = useState(0);
  const [inches, setInches] = useState(0);
  const [centimeters, setCentimeters] = useState(0);

  const submit = (e) => {
    e.preventDefault();
    const formValid = +feet >= 0 && +inches >= 0;
    if (!formValid) {
      return;
    }
    setCentimeters((+feet + +inches / 12) * 12 * 2.54);
  };

  return (
    <div>
      <form onSubmit={submit}>
        <div>
          <label>feet</label>
          <input value={feet} onChange={(e) => setFeet(e.target.value)} />
        </div>
        <div>
          <label>inches</label>
          <input value={inches} onChange={(e) => setInches(e.target.value)} />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>{centimeters} cm</p>
    </div>
  );
}

We create the feet , inches and centimeters states with the useState hook.

Then we define the submit function to calculate the centimeters from feet and inches .

In it, we call e.preventDefault to do client-side form submission.

Then we check if feet and inches are valid numbers.

If they are, then we calculate the centimeters equivalent of the feet and inches and call setCentimeters to set the centimeter value.

Below that, we have the form.

We pass the submit function to the onSubmit hook to trigger submission when we click the calculate button.

The inputs are used to set feet and inches .

onChange is set to a function to set each value.

e.target.value has the inputted value.

Below that, we display the centimeters value.

Conclusion

We can create a height converter app easily with React and JavaScript.

Categories
React Projects

Create a Guess a Number Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a guess a number game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app guess-number-game

with NPM to create our React project.

Create the Guess a Number Game

To create the guess a number game, we write:

import React, { useState } from "react";

export default function App() {
  const [started, setStarted] = useState(false);
  const [status, setStatus] = useState(false);
  const [answer, setAnswer] = useState(0);
  const [rightAnswer, setRightAnsweer] = useState(0);
  console.log(rightAnswer);

  const submit = (e) => {
    e.preventDefault();
    const formValid = +answer >= 0;
    if (!formValid) {
      return;
    }
    if (+answer === +rightAnswer) {
      setStatus("you got it");
      setStarted(false);
    } else if (+answer < +rightAnswer) {
      setStatus("too low");
    } else {
      setStatus("too high");
    }
  };

  const start = () => {
    setRightAnsweer(Math.ceil(Math.random() * 10));
    setStarted(true);
  };

  if (started) {
    return (
      <div>
        <form onSubmit={submit}>
          <div>
            <label>answer</label>
            <input value={answer} onChange={(e) => setAnswer(e.target.value)} />
          </div>
          <button type="submit">check</button>
        </form>
        <p>{status}</p>
      </div>
    );
  } else {
    return (
      <div>
        <button type="button" onClick={start}>
          start
        </button>
        <p>{status}</p>
      </div>
    );
  }
}

We have the started state to set render the form to let us enter a number when the game is started.

status shows whether the guess is right or not.

answer shows the answer.

rightAnswer has the right answer.

Next, we have the submit function that checks the answer we entered.

In it, we call e.preventDefault() to do client-side form submission.

Then we check if answer is bigger than or equal to 0.

If it is, then we check it against rightAnswer and set the status and started states accordingly.

The start function sets the rightAnswer with setRightAnswer .

setStarted sets the started state.

If started is true , we show the form.

We set the onSubmit prop to submit to let us submit our answer .

submit is run when we click on the check button, which has button type submit .

The input’s value is set to answer and we set answer with the onChange callback.

We get the inputted value with e.target.value .

Below the form, we show the status .

If started is false , we show the start button and the status .

Conclusion

We can create a guess a number game with React and JavaScript.

Categories
React Projects

Create a Balloon Popping Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a balloon popping game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app balloon-popping-game

with NPM to create our React project.

Create the Balloon Popping Game

To create the balloon popping game, we write:

import React, { useState } from "react";

const colors = ["red", "green", "blue"];

const generateColor = () => {
  const index = Math.floor(Math.random() * colors.length);
  return colors[index];
};

const balloonArr = Array(25)
  .fill()
  .map((_, i) => ({ id: i, popped: false, color: generateColor() }));

export default function App() {
  const [balloons, setBalloons] = useState(balloonArr);

  const onPop = (index) => {
    setBalloons((balloons) => {
      const b = [...balloons];
      b[index].popped = true;
      return b;
    });
  };

  return (
    <div className="App">
      <style>
        {`
        .balloon-container {
          display: inline-block;
        }

        .balloon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          border: 1px solid black;
        }
      `}
      </style>
      <div>
        {balloons.map((b, i) => {
          if (!b.popped) {
            return (
              <div className="balloon-container" key={b.id}>
                <div
                  className="balloon"
                  style={{ backgroundColor: b.color }}
                  onMouseOver={() => onPop(i)}
                ></div>
              </div>
            );
          } else {
            return <div className="balloon-container">popped</div>;
          }
        })}
      </div>
    </div>
  );
}

We have the colors array with the balloon colors.

generateColor picks a random color from the colors array.

Then we have the balloonArr array which has 25 objects with data for rendering the balloons.

It includes whether it’s popped or not, and the color .

In App , we have the balloons state which is set to balloonArr initially.

The onPop function lets us set the balloons entry with the given index ‘s popped property to true .

We have a callback to get the balloons , then we make a copy, modify it, and then return the modified copy.

Next, we have the styles to make the balloons display online.

The ballon class makes the div display as circles by setting the border-radius to 50% .

Then finally, we render the balloons by calling map .

In the map callback, we check if b.popped is false .

If it’s false , then we render the ballon with divs.

We set the styles and the onMouseOver prop to a function that calls the onPop function to pop the balloons by setting popped to true .

Otherwise, we render the ‘popped’ text.

Conclusion

We can create a balloon popping game with React and JavaScript.

Categories
React Projects

Create a Quiz Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create an addition game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app quiz-game

with NPM to create our React project.

Create the Quiz Game

To create the quiz game, we write:

import React, { useState } from "react";

const questions = [
  {
    question: "What is American football called in England?",
    choices: ["American football", "football", "Handball"],
    rightAnswer: "American football"
  },
  {
    question: "What is the largest country in the world?",
    choices: ["Russia", "Canada", "United States"],
    rightAnswer: "Russia"
  },
  {
    question: "What is the 100th digit of Pi?",
    choices: ["9", "4", "7"],
    rightAnswer: 9
  }
];

export default function App() {
  const [score, setScore] = useState(0);
  const [questionIndex, setQuestionIndex] = useState(0);
  const [answer, setAnswer] = useState("");

  const restart = () => {
    setScore(0);
    setAnswer("");
    setQuestionIndex(0);
  };

  const submit = (e) => {
    e.preventDefault();
    if (answer === questions[questionIndex].rightAnswer) {
      setScore((score) => score + 1);
    }

    if (questionIndex < questions.length) {
      setQuestionIndex((i) => i + 1);
    }
  };

if (questionIndex < questions.length) {
    return (
      <div>
        <label>{questions[questionIndex].question}</label>
        {questions[questionIndex].choices.map((c, i) => {
          return (
            <div>
              <input
                type="radio"
                name="choice"
                value={c}
                onChange={(e) => setAnswer(e.target.value)}
                checked={answer === c}
              />
              {c}
            </div>
          );
        })}
        <button type="button" onClick={submit}>
          check
        </button>
        <p>score: {score}</p>
      </div>
    );
  } else {
    return (
      <form>
        <div v-else>
          <button type="button" onClick={restart}>
            restart
          </button>
        </div>
        <p>score: {score}</p>
      </form>
    );
  }
}

We have the questions array with the question, choices, and rightAnswer properties with the question, the choices for the question, and the right answer for the question respectively.

Then in App , we have the score , questionIndex , and answer states created with useState .

answer is the answer the player chooses.

Below that, we have the submit function, we call e.preventDefault() to do client-side form submission.

Then we check if our answer choice is the same as rightAnswer .

If it is, then we call setScore to increment the score.

And if questionIndex is less than questions.length that means we have more questions to show.

Therefore, we call setQuestionIndex to increment the score with a callback that returns the original index i plus 1.

Next, we have an if statement that does the same check if the if in the submit function.

If questionIndex is less than questions.length , we should the question with the radio buttons for the player to choose the answer.

We set the checked prop to set the radio button to checked.

We determined which one if checked by comparing the answer value to c .

onChange lets us set the choice with a function that calls setAnswer to set the choice.

Below that, we display the check button that calls submit to submit the answer when we click it.

And then we show the score below that.

If the if condition is false , we show the restart button that calls restart to reset all the values.

And we also show the score below that.

Conclusion

We can create a quiz game easily with React and JavaScript.