In this tutorial, we'll create a simple car racing game using React.js. The player can move the car left and right using the keyboard arrow keys. The opponent cars will move from the top to the bottom, and the game will end with a "Game Over" alert when the player's car collides with an opponent car. The speed of the opponent cars will gradually increase, making the game more challenging.
Step 1: Set Up the Project
First, make sure you have create-react-app
installed. If not, install it using the following command:
npx create-react-app car-racing-game
Navigate to your project directory:
cd car-racing-game
Step 2: Install Styled-Components
We will use styled-components
for styling our components. Install it using the following command:
npm install styled-components
Step 3: Create the Game Components
Create a new file src/App.js
and replace its content with the following code:
import React, { useState, useEffect } from 'react';
import styled, { keyframes } from 'styled-components';
const moveRoad = keyframes\`
0% {
background-position: 0 0;
}
100% {
background-position: 0 100%;
}
\`;
const GameContainer = styled.div\`
width: 500px;
height: 700px;
border: 1px solid black;
margin: 50px auto;
position: relative;
overflow: hidden;
background-color: #333;
background-image: linear-gradient(#555 20%, transparent 20%, transparent 40%, #555 40%, #555 60%, transparent 60%, transparent 80%, #555 80%);
background-size: 100% 50px;
animation: \${moveRoad} 2s linear infinite;
\`;
const Car = styled.img\`
width: 50px;
height: 100px;
position: absolute;
top: \${(props) => (props.isPlayer ? 'auto' : props.y + 'px')};
bottom: \${(props) => (props.isPlayer ? '10px' : 'auto')};
left: \${(props) => props.x + 'px'};
border-radius: 5px;
\`;
const Score = styled.div\`
position: absolute;
top: 10px;
left: 10px;
color: white;
font-size: 20px;
font-family: Arial, sans-serif;
\`;
const App = () => {
const [playerX, setPlayerX] = useState(225); // Player car's initial x position
const [opponents, setOpponents] = useState([]);
const [score, setScore] = useState(0);
const [gameOver, setGameOver] = useState(false);
useEffect(() => {
const handleKeyDown = (e) => {
if (e.key === 'ArrowLeft' && playerX > 0) setPlayerX(playerX - 20);
if (e.key === 'ArrowRight' && playerX < 450) setPlayerX(playerX + 20);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [playerX]);
useEffect(() => {
const interval = setInterval(() => {
if (gameOver) return;
setOpponents((prevOpponents) =>
prevOpponents
.map((opponent) => ({ ...opponent, y: opponent.y + opponent.speed }))
.filter((opponent) => opponent.y < 700)
);
setOpponents((prevOpponents) => {
const newOpponent = {
x: Math.random() * 450,
y: -100,
speed: Math.random() * 5 + 4 + score / 50, // Adjusted speed
};
return prevOpponents.length < 4 ? [...prevOpponents, newOpponent] : prevOpponents;
});
setScore((prevScore) => prevScore + 1);
setOpponents((prevOpponents) => {
for (let opponent of prevOpponents) {
if (
opponent.y + 100 >= 600 &&
opponent.x < playerX + 50 &&
opponent.x + 50 > playerX
) {
setGameOver(true);
alert(\`Game Over! Score: \${score}\`);
clearInterval(interval);
}
}
return prevOpponents;
});
}, 50); // Adjusted interval time
return () => clearInterval(interval);
}, [opponents, playerX, score, gameOver]);
return (
Score: {score}
{opponents.map((opponent, index) => (
))}
);
};
export default App;
Make sure to replace "path/to/player-car.png"
and "path/to/opponent-car.png"
with the actual paths to your car images.
Conclusion
With these steps, you have created a basic car racing game in React.js. The player can move the car left and right, and the opponent cars move from the top to the bottom. The game ends with a "Game Over" alert when the player's car collides with an opponent car, and the score is displayed on the screen.
Comments
Post a Comment