Open In App

Create a Text-based Adventure Game using React

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Text-based adventure games, also known as interactive fiction, have been very popular games since early computing. With their immersive storytelling and engaging gameplay, text adventures offer a unique gaming experience that relies heavily on narrative and player choice. In this article, we'll explore the basics of building a text-based adventure game, suitable for beginners who are eager to dive into game development.

Preview of Final Output: Let us have a look at how the final output will look like

err
Output Preview

Prerequisites:

Approach to build Text-based Adventure Game:

  • Define the storyline, including various scenarios, choices, and possible outcomes.
  • Create a new React project using Create React App or any other preferred method.
  • Create components to represent different parts of the game, such as App, Game, and Story.
  • Define the storyline with multiple scenarios and choices using data structures like arrays or objects.
  • Apply CSS styles or use CSS frameworks like Bootstrap to design an attractive and user-friendly interface.

Steps to Create Text-based Adventure Game in React

Step 1: Create a new React JS project using the following command.

npx create-react-app textgame

Step 2: Change to the project directory.

cd textgame

Step 3: Install the requires modules.

npm install bootstrap

Project Structure:

sdff

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",
"bootstrap": "^5.3.3",
"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 respective files.

JavaScript
// App.js

import React from 'react';
import Game from './components/Game';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
	return (
		<div className="container">
			<div className="card text-center mt-5">
				<div className="card-header bg-primary text-white">
					<h1 className="display-4">Text Adventure Game</h1>
				</div>
				<div className="card-body">
					<Game />
				</div>
			</div>
		</div>
	);
}

export default App;
JavaScript
// Game.js

import React, { useState } from 'react';
import Story from './Story';

const Game = () => {
	const [scenario, setScenario] = useState(0);
	const [gameResult, setGameResult] = useState(null);

	const handleChoice = (choice) => {
		if (choice.nextScenario !== undefined) {
			setScenario(choice.nextScenario);
		} else {
			console.error('Invalid choice!');
		}
	};

	const restartGame = () => {
		setScenario(0);
		setGameResult(null);
	};

	const handleGameResult = (result) => {
		setGameResult(result);
	};

	return (
		<div>
			{gameResult === 'win' && <img src="https://media.geeksforgeeks.org/wp-content/uploads/20240222121721/win.jpg" alt="You win" />}
			{gameResult === 'lose' && <img src="https://media.geeksforgeeks.org/wp-content/uploads/20240222122023/lose.jpg" alt="You lose" />}
			{gameResult ? (
				<center>
					<button onClick={restartGame}>Restart Game</button>
				</center>
			) : (
				<Story scenario={scenario} onChoice={handleChoice} onGameResult={handleGameResult} />
			)}
		</div>
	);
};

export default Game;
JavaScript
// Story.js

import React from 'react';

const Story = ({ scenario, onChoice, onGameResult }) => {
	const scenarios = [
		{
			id: 0,
			text: 'You find yourself standing in front of a dark cave. What do you do?',
			choices: [
				{ text: 'Enter the cave', nextScenario: 1 },
				{ text: 'Walk away', nextScenario: 2 }
			]
		},
		{
			id: 1,
			text: 'As you enter the cave, you see two tunnels. Which do you choose?',
			choices: [
				{ text: 'Go left', nextScenario: 3 },
				{ text: 'Go right', nextScenario: 4 }
			]
		},
		{
			id: 2,
			text: 'You walk away from the cave. The adventure ends here.',
			choices: []
		},
		{
			id: 3,
			text: 'You go left and find a key! What do you do?',
			choices: [
				{ text: 'Keep the key', nextScenario: 5 },
				{ text: 'Leave the key', nextScenario: 6 }
			]
		},
		{
			id: 4,
			text: 'You go right and encounter a dead end. What do you do?',
			choices: [
				{ text: 'Go back', nextScenario: 1 }
			]
		},
		{
			id: 5,
			text: 'You keep the key. As you move forward, you find a locked door. What do you do?',
			choices: [
				{ text: 'Use the key', nextScenario: 7 }
			]
		},
		{
			id: 6,
			text: 'You leave the key behind and move forward. The adventure ends here.',
			choices: []
		},
		{
			id: 7,
			text: 'You open the door with the key and find a treasure chest! Congratulations, you found
			the treasure! The adventure ends here.',
			choices: []
		}
	];

	const currentScenario = scenarios.find(s => s.id === scenario);

	const handleChoice = (choice) => {
		const nextScenario = choice.nextScenario;
		onChoice(choice);

		if (nextScenario === 7) {
			alert('Congratulations, you found the treasure! The adventure ends here.');
			onGameResult('win');
		} else if (nextScenario === 2 || nextScenario === 6) {
			onGameResult('lose'); 
		}
	};

	return (
		<div className="card mx-auto mt-5" style={{ maxWidth: '500px' }}>
			<div className="card-body">
				<p className="card-text">{currentScenario.text}</p>
				<ul className="list-group">
					{currentScenario.choices.map((choice, index) => (
						<li key={index} className="list-group-item">
							<button className="btn btn-primary btn-block" onClick={() => handleChoice(choice)}>
							{choice.text}</button>
						</li>
					))}
				</ul>
			</div>
		</div>
	);
};

export default Story;

Steps to run the project:

Step 1: Type the following command in terminal.

npm start

Step 2: Open web-browser and type the following URL

http://localhost:3000/

Output:


Next Article

Similar Reads