Here is an example of a simple game built using React. In this game, the player has to click on an image to score points, and the images shuffle after every click. The game keeps track of the player's score and highest score.
First, let's create a new React component called Game
. The component will have a state object that includes the current score, highest score, and an array of images. Here's the code for the initial component:
javascript
import React, { Component } from 'react'; class Game extends Component { state = { score: 0, highScore: 0, images: [ "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150", "https://via.placeholder.com/150" ] }; render() { return ( <div> <h1>Click an image to score points!</h1> <p>Score: {this.state.score}</p> <p>High Score: {this.state.highScore}</p> </div> ); } } export default Game;
Next, let's add a function that shuffles the images in the state object. We'll call this function every time the player clicks on an image. Here's the code for the shuffleImages
function:
javascript
shuffleImages = () => { const images = [...this.state.images]; let currentIndex = images.length, tempValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; tempValue = images[currentIndex]; images[currentIndex] = images[randomIndex]; images[randomIndex] = tempValue; } this.setState({ images }); };
Finally, let's add a function that handles a click on an image. We'll use the shuffleImages
function to shuffle the images and update the player's score and high score. Here's the code for the handleImageClick
function:
javascript
handleImageClick = (event) => { this.shuffleImages(); const imageIndex = this.state.images.indexOf(event.target.src); if (imageIndex === -1) { this.setState({ score: 0 }); } else { const newScore = this.state.score + 1; const newHighScore = Math.max(newScore, this.state.highScore); this.setState({ score: newScore, highScore: newHighScore }); } };
We'll also need to render the images in the component. Here's the updated render
function that includes the images and an onClick
event handler for each image:
javascript
render() { return ( <div> <h1>Click an image to score points!</h1> <p>Score: {this.state.score}</p> <p>High Score: {this.state.highScore}</p> <div> {this.state.images.map((image, index) => ( <img key={index} src={image} alt={`Image ${index}`} onClick={this.handleImageClick} /> ))} </div> </div> ); }
And that's it! We've created a simple game using React. Here's the
2 Comments
Great thanks ,u r the best one without chitchat and just cool content!!
ReplyDeleteMy Pleasure
Delete