Open In App

Ping Pong Game using React

Last Updated : 23 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Ping Pong is one of the earliest video games. It's a two-player game in which each player controls the paddle by dragging it from one side of the screen to the other to strike the ball back and forth. In this article, you will see how you can create a simple but exciting game of ping pong using React.

Preview of the project: Let us have a look at how the final application will look like.ping

Prerequisites

Approach to create Ping Pong Game:

  • To create a game interface and to handle the state, we will use React components.
  • The arrow keys and the "w" and "d" keys are used by the players to control the paddles.
  • inside the playing field, paddles can move upwards and downwards.
  • When the ball hits a paddle it goes off the top and bottom of the wall.
  • When the ball comes to either side of the screen, the game is over.
  • We can start, restar and stop the game with the helps of button provided.
  • We are able to detect the ball collision with paddle or wall with the help of DOM element boundingClientRect properties.

Steps to Create the Project:

Step 1: Create a ReactJS project:

npx create-react-app ping-pong-game

Step 2: Navigate to the project:

cd ping-pong-game

Step 3: Start the project:

npm start

Project Structure:

Screenshot-(1399)
The project structure of the code

The updated dependencies in package.json file will look like:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example : Write the following code in App.js file

CSS
/*App.css*/

.ping-pong-container {
    position: relative;
    width: 600px;
    height: 400px;
    border: 1px solid #ccc;
    margin: 20px auto;
    overflow: hidden;

}

.paddle {
    position: absolute;
    width: 20px;
    height: 100px;
    background-color: #333;
    transition: top 0.2s;
}

.paddle-left {
    left: 0;
}

.paddle-right {
    right: 0;
}

.ball {
    position: absolute;
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    transition: top 0.2s, left 0.2s;
}

.paused {
    animation-play-state: paused;
}

.controls {
    margin-top: 10px;
    display: flex;
    gap: 10px;
}

button {
    padding: 5px 10px;
    font-size: 16px;
    cursor: pointer;
}

.game-over {
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    height: 45vh;
}
JavaScript

Output:


Next Article

Similar Reads

three90RightbarBannerImg