Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Design a brain teasing game with React and NeumorphismUI

  • Last Updated : 01 Feb, 2021

A brain-teasing game is designed to find how many questions can a person answer as fast as possible. We are going to design a React application with the NeumorphismUI which is going to display some interesting questions about some common facts and the user has to answer them ASAP.

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front end library responsible only for the view layer of the application. It is maintained by Facebook.

React uses a declarative paradigm that makes it easier to reason about your application and aims to be both efficient and flexible. It designs simple views for each state in your application, and React will efficiently update and render just the right component when your data changes. The declarative view makes your code more predictable and easier to debug.

Why use NeumorphismUI?

NeumorphismUI is a modern soft UI used in designing web elements, frames, and screens and is also a relatively new design trend that achieved great popularity these days. Its aesthetic is marked by minimal and real-looking UI that’s sort of a re-advancement of the old SkeuomorphismUI design trend. So, to make our game more user-friendly and attractive, we are going to use it in our project.



This game displays a set of questions that have to be answered as fast as possible and the score will be displayed accordingly. Incorrectly answered or wrongly typed answers will result in negative marking.

We will first create the React application and add some logic into it with some CSS Styling to give it, a soft feel.

What we are building?

Below is just a glimpse of what we are building here.

Now we are going to write some JSX code to build our web application.

The JSX Layout: The JSX layout defines the element structure that would be shown on the page. This includes

  • Game Main Container: This section contains our game heading and the Game container.
  • Game container: This section contains the Game component which contains the whole game logic in it.
  • Game component: This component contains the game score, question, error and success messages, input area, reset and enter button.
  • Game Error and Success messages: The error message will be displayed if the user entered an incorrect answer or if he tries to submit the answer with an empty input area while the success message will be displayed if the user enters the correct answer.
  • Input Area: This section contains the input area where the answer has to be typed.
  • Reset and Enter Button: The user can click on the reset button if he wants to skip to another question or he can click on the enter button to submit the answer.

Implementation:



Step 1: Create a React application using the following command:

npx create-react-app Brain-Teasing-Game

Step 2: After creating your project folder i.e. Brain-Teasing-Game, move to it using the following command:

cd Brain-Teasing-Game

Project Structure: It will look like the following.

Project Structure

Filename-App.js:

Javascript




import React from 'react';
import app from './App.css';
import Game from './Game.js';
  
function App() {
  // Creating the container and importing 
  // Game component
  return (
    <div className={app.Game__main_container}>
      <h1 className={app.Game__heading}>
       Welcome to the Brain Twister game
      </h1>
      <div className={app.Game__container}>
        <Game />
      </div>
    </div>
  );
}
  
export default App;

Filename-Game.js:

Javascript




import React, { useEffect, useState } from 'react';
import game from './Game.css';
  
const Game = () => {
  
// Initialising states with default values
  const [word, setWord] = useState('');
  const [value, setValue] = useState('');
  const [err, setErr] = useState('');
  const [success, setSuccess] = useState('');
  const [score, setScore] = useState(0);
  const [question, setQuestion] = useState('');
  
  // Starts generating words as soon as 
  // the component is placed in the DOM Tree
  useEffect(() => {
    wordGenerate();
  }, []);
  
  // Defining questions with their
  // corresponding answers
  const QUESTION = [];
  
  const ANSWERS = [];
  
  // Generating Random questions and storing
  // their answers in the state variable
  const wordGenerate = () => {};
  
  // checking if the typed answer is correct or not
  const check = () => {};
   
  // defining function to skip
  // to another question
  const reset = () => {};
  
  // Writing the JSX Code
  return (
    <div>
      <p className={game.Game__score}>SCORE : {score}</p>
  
      {question ? (
        <p className={game.Game__question}>Question: {question}</p>
  
      ) : null}
  
      {err ? <p className={game.Game__error}>{err}</p>
 : null}
  
      {success ? <p className={game.Game__success}>{success}</p>
 : null}
  
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Enter Answer Here!"
        className={game.Game__input_answer}
      />
  
      <button onClick={reset} className={game.Game__start}>
        Reset
      </button>
      <button onClick={check} className={game.Game__submit}>
        Enter
      </button>
    </div>
  );
};
  
export default Game;

Now, the basic structure of our app is created and now it’s the time to add some logic into it by defining the initialized functions in the Game Component.

Main Logic of the game: The main logic of the game is defined in the already initialized functions. There are several functions that work together to run the game.



  • Step 1: Writing the questions along with their corresponding answers

    The questions and the answers of the brain-teasing game are going to be stored in the initialized arrays.

    Javascript




    const QUESTION = [
        'Greatest Computer Science portal for geeks',
        'Full form of DSA',
        'Most Used Web Framework',
        'Founder of GeeksForGeeks',
        'Who Created Facebook',
        'CEO of Tesla and SpaceX',
        'When 5G going to launch in India',
      ];
      
      const ANSWERS = [
        'GeeksForGeeks',
        'Data Structures and algorithms',
        'React',
        'Sandeep Jain',
        'Mark Zuckerberg',
        'Elon Musk',
        '2021',
      ];
  • Step 2: Generating Random questions

    A function wordGenerate() will be called when the Game component is placed in the DOM Tree or when the user clicks on enter or reset button.

    We will generate a random number in the range of 0 to ANSWERS array length, store it as a variable, and then use it to pick random questions along with their answers and store them in the state variables.

    Javascript




    const wordGenerate = () => {
      const randomNumber = Math.floor(Math.random() * ANSWERS.length);
      setWord(ANSWERS[randomNumber]);
      setQuestion(QUESTION[randomNumber]);
    };
  • Step 3: Checking if the typed answer is correct or not

    We have two cases here:

    • User hasn’t entered any value in the input area:
      • If the typed value is null then it will show an error message
    • User has entered some value:
      • Convert the entered value to lowercase, compare it with the stored answer and then display the error or success messages accordingly

    Javascript






    const check = () => {
        if (value) {
          if (value.toLowerCase() === word.toLowerCase()) {
            setValue('');
            setErr(null);
            setSuccess('Correct Answer');
            setScore((prevScore) => prevScore + 1);
            wordGenerate();
          } else {
            setSuccess(null);
            setErr('Wrong Answer');
            setScore((prevScore) => prevScore - 1);
            setValue('');
            wordGenerate();
          }
        } else {
          setSuccess(null);
          setErr('Please enter the value!');
        }
      };
  • Step 4: Adding logic to reset button handler

    When the reset button is clicked, remove all the error messages and generate a new question.

    Javascript




    const reset = () => {
      setValue(null);
      setSuccess(null);
      setErr(null);
      wordGenerate();
    };

Filename-Game.js:After adding all the logic in our Brain Teasing Game, the final look of Game.js will be as follows:

Javascript




import React, { useEffect, useState } from 'react';
import game from './Game.css';
  
const Game = () => {
  
  // Initialising states with default values
  const [word, setWord] = useState('');
  const [value, setValue] = useState('');
  const [err, setErr] = useState('');
  const [success, setSuccess] = useState('');
  const [score, setScore] = useState(0);
  const [question, setQuestion] = useState('');
  
  // Starts generating words as soon as
  // the component is placed in the DOM Tree
  useEffect(() => {
    wordGenerate();
  }, []);
  
  // Defining questions with their
  // corresponding answers
  const QUESTION = [
    'Greatest Computer Science portal for geeks',
    'Full form of DSA',
    'Most Used Web Framework',
    'Founder of GeeksForGeeks',
    'Who Created Facebook',
    'CEO of Tesla and SpaceX',
    'When 5G going to launch in India',
  ];
  
  const ANSWERS = [
    'GeeksForGeeks',
    'Data Structures and algorithms',
    'React',
    'Sandeep Jain',
    'Mark Zuckerberg',
    'Elon Musk',
    '2021',
  ];
  
  // Generating Random questions and storing
  // their answers in the state variable
  const wordGenerate = () => {
    const randomNumber = Math.floor(Math.random() * ANSWERS.length);
    setWord(ANSWERS[randomNumber]);
    setQuestion(QUESTION[randomNumber]);
  };
  
  // checking if the typed answer is correct or not
  const check = () => {
    if (value) {
      if (value.toLowerCase() === word.toLowerCase()) {
        setValue('');
        setErr(null);
        setSuccess('Correct Answer');
        setScore((prevScore) => prevScore + 1);
        wordGenerate();
      } else {
        setSuccess(null);
        setErr('Wrong Answer');
        setScore((prevScore) => prevScore - 1);
        setValue('');
        wordGenerate();
      }
    } else {
      setSuccess(null);
      setErr('Please enter the value!');
    }
  };
  
  // defining function to skip
  // to another question
  const reset = () => {
    setValue(null);
    setSuccess(null);
    setErr(null);
    wordGenerate();
  };
  
  // Writing the JSX Code
  return (
    <div>
      <p className={game.Game__score}>SCORE : {score}</p>
  
      {question ? (
        <p className={game.Game__question}>Question: {question}</p>
  
      ) : null}
  
      {err ? <p className={game.Game__error}>{err}</p>
 : null}
  
      {success ? <p className={game.Game__success}>{success}</p>
 : null}
  
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Enter Answer Here!"
        className={game.Game__input_answer}
      />
  
      <button onClick={reset} className={game.Game__start}>
        Reset
      </button>
      <button onClick={check} className={game.Game__submit}>
        Enter
      </button>
    </div>
  );
};
  
export default Game;

Now with all the logic added to the game, we are going to add some CSS Styling to it to give it a more soft UI feel.

The CSS Styling: CSS is used to style the different portions and make them more visually appealing.

  • Adequate padding and margin are given to each element.
  • The text size of each element is such that it is easily readable by the user when playing the game.
  • A background color of #e4ebf5e0 is also provided in the index.css file
  • Code:

Filename: App.css

CSS




.Game__main_container {
  width: 40%;
  height: 50%;
  margin: 100px auto;
  border-radius: 3rem;
  box-shadow: 0.8rem 0.8rem 1.4rem #c8d0e7eb, -0.2rem -0.2rem 1.8rem #fff;
  padding: 4rem;
}
.Game__heading{
  box-shadow: 0.3rem 0.3rem 0.6rem #c8d0e7eb, -0.2rem -0.2rem 0.5rem #fff,
    inset 0.2rem 0.2rem 0.5rem #c8d0e7, inset -0.2rem -0.2rem 0.5rem #fff;
  border-radius: 10px;
  padding: 10px;
  text-align: center;
  color: #9baacf;
}</pre><p style="text-align:justify"><strong>Filename: Game.css</strong></p>
  
<pre>.Game__score {
  text-align: right;
  color: #6d5dfc;
  font-weight: 700;
  display: inline-block;
  width:100%;
}
.Game__error,
.Game__success {
  color: red;
  border-radius: 10px;
  padding: 20px;
  margin: 10px 0;
  background-color: rgba(255, 0, 0, 0.207);
}
.Game__success {
  color: #fff;
  background-color: rgba(0, 128, 0, 0.399);
}
.Game__question {
  color: #1a1a1a;
  font-size: 20px;
}
.Game__input_answer {
  width: 20.4rem;
  height: 3rem;
  display: block;
  border: none;
  border-radius: 1rem;
  font-size: 1.4rem;
  padding-left: 1.4rem;
  box-shadow: inset 0.2rem 0.2rem 0.5rem #c8d0e7,
    inset -0.2rem -0.2rem 0.5rem #fff;
  background: none;
  color: #9baacf;
  margin: 50px auto;
  outline: none;
}
.Game__input_answer input::placeholder {
  color: #bec8e482;
}
input:focus {
  box-shadow: 0.3rem 0.3rem 0.6rem #c8d0e7eb, -0.2rem -0.2rem 0.5rem #fff;
}
.Game__start,
.Game__submit {
  width: 45%;
  height: 4rem;
  font-size: 20px;
  margin: 10px;
  border-radius: 1rem;
  box-shadow: 0.3rem 0.3rem 0.6rem #c8d0e7, -0.2rem -0.2rem 0.5rem #fff;
  justify-self: center;
  display: inline;
  outline: none;
  border: none;
  cursor: pointer;
}
.Game__start {
  background: #6d5dfc;
  box-shadow: inset 0.2rem 0.2rem 1rem #8abdff,
    inset -0.2rem -0.2rem 1rem #5b0eeb, 0.3rem 0.3rem 0.6rem #c8d0e7,
    -0.2rem -0.2rem 0.5rem #fff;
  color: #e4ebf5;
}

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: The game is now ready to be played in any browser.

Source Code: https://github.com/RahulBansal123/Brain-Teasing-Game




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!