Open In App

Word Guessing Game Design using React-Native

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

In this article, we will create a Word Guessing App using React Native. Word Guess app is a guessing game, where a hint will be given based on the word you have to guess. This app provides hints and a limited number of attempts to make the game challenging and enjoyable.

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

wordg
Output Preview of word guess game

Prerequisite

Approach

  • UI Design: Create an intuitive user interface using React Native components and define styles for a visually appealing game layout.
  • Game Logic: Implement core game logic functions, such as random word selection, word checking, hint usage, and result display.
  • State Management: Utilize the useState hook to manage the state of game elements, including word data, user input, hints, and messages.
  • Lifecycle and Rendering: Employ the useEffect hook to handle game lifecycle and ensure the UI updates accurately based on game state, and thoroughly test the application for functionality.

Steps to Create React Native Application

Step 1: Create a react native application by using this command in command prompt

React-native init GFGWordGame

Project Structure:

reactnativeProj
Project Structure

Example: Below is the basic implementation of the Word Guessing Game using React-Native

JavaScript
import React, { useState, useEffect } from 'react';
import {
	View, Text, TextInput,
	TouchableOpacity, StyleSheet, Alert
} from 'react-native';
import { sampleWords } from './SampleData'

const getRandomWord = () => {
	const randomPlace =
		Math.floor(Math.random() * sampleWords.length);
	return sampleWords[randomPlace];
};

const GFGWordGame = () => {
	const [wordData, setWordData] =
		useState(getRandomWord());
	const [msg, setMsg] = useState('');
	const [inputText, setInputText] = useState('');
	const [hints, setHints] = useState(3);
	const [displayWord, setDisplayWord] =
		useState(false);

	const checkWordGuessedFunction = () => {
		return inputText.toLowerCase() ===
			wordData.word.toLowerCase();
	};

	const useHint = () => {
		if (hints > 0 && !displayWord) {
			const hiddenLetterIndex = wordData.word
				.split('')
				.findIndex(
					(letter) =>
						letter !== ' ' &&
						inputText[hiddenLetterIndex] !==
						letter);
			const updatedText =
				inputText.slice(0, hiddenLetterIndex) +
				wordData.word[hiddenLetterIndex] +
				inputText.slice(hiddenLetterIndex + 1);
			setHints(hints - 1);
			setInputText(updatedText);
		}
	};

	const showResult = () => {
		if (checkWordGuessedFunction()) {
			setMsg(`Congratulations! You guessed 
			the word correctly!`);
		} else {
			setMsg('You made a Wrong Guess. Try again!');
			setDisplayWord(true);
		}
	};

	const restartGameFunction = () => {
		setWordData(getRandomWord());
		setMsg('');
		setInputText('');
		setHints(3);
		setDisplayWord(false);
	};

	useEffect(() => {
		if (displayWord) {
			showResult();
		}
	});

	return (
		<View style={styles.container}>
			<Text style={styles.appName}>
				GeeksforGeeks
			</Text>
			<Text style={styles.heading}>
				Word Guess Game
			</Text>
			<Text style={styles.wordDescription}>
				Hint: {wordData.description}
			</Text>
			<View style={styles.hints}>
				<Text style={styles.hintText}>
					Hints Remaining: {hints}
				</Text>
			</View>
			<TextInput
				style={styles.input}
				value={inputText}
				onChangeText={(text) => setInputText(text)}
				placeholder="Enter your guess"
				editable={!displayWord}
			/>
			<View style={styles.buttonSection}>
				<TouchableOpacity onPress={useHint}
					disabled={hints === 0 || displayWord}
					style={styles.hintButton}>
					<Text style={styles.hintButtonText}>Use Hint</Text>
				</TouchableOpacity>
				<TouchableOpacity onPress={showResult}
					style={styles.showResultButton}
					disabled={displayWord}>
					<Text style={styles.buttonText}>
						Show Result
					</Text>
				</TouchableOpacity>
				<TouchableOpacity onPress={restartGameFunction}
					style={styles.restartButton}>
					<Text style={styles.buttonText}>
						Restart
					</Text>
				</TouchableOpacity>
			</View>
			{msg && (
				<View style={styles.message}>
					<Text style={styles.messageText}>
						{msg}
					</Text>
					{displayWord &&
						<Text>
							Correct word was: {wordData.word}
						</Text>}
				</View>
			)}
		</View>
	);
};

const styles = StyleSheet.create({
	container: {
		flex: 1,
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: '#f0f0f0',
		padding: 16,
	},
	appName: {
		fontSize: 24,
		fontWeight: 'bold',
		color: 'green',
	},
	heading: {
		fontSize: 20,
		fontWeight: 'bold',
		marginBottom: 16,
	},
	wordDescription: {
		marginTop: 16,
		marginBottom: 16,
	},
	hints: {
		marginTop: 16,
		marginBottom: 16,
	},
	hintText: {
		fontSize: 16,
	},
	hintButton: {
		padding: 10,
		backgroundColor: 'orange',
		borderRadius: 5,
	},
	hintButtonText: {
		color: 'white',
	},
	showResultButton: {
		padding: 10,
		backgroundColor: 'green',
		borderRadius: 5,
		marginRight: 10,
		marginLeft: 10,
	},
	restartButton: {
		padding: 10,
		backgroundColor: 'red',
		borderRadius: 5,
	},
	buttonText: {
		color: 'white',
	},
	message: {
		marginTop: 16,
		alignItems: 'center',
	},
	messageText: {
		fontSize: 18,
		fontWeight: 'bold',
	},
	input: {
		width: '80%',
		height: 40,
		borderWidth: 1,
		borderColor: 'black',
		marginBottom: 16,
		paddingLeft: 8,
	},
	buttonSection: {
		flexDirection: 'row',
		marginTop: 16,
	},
});

export default GFGWordGame;
JavaScript
//SampleData.js
export const sampleWords = [
	{
		word: 'HELLO',
		description:
			`A common greeting to say hi.`,
	},
	{
		word: 'WORLD',
		description:
			`The planet we live on, which 
			is full of land and water.`,
	},
	{
		word: 'JAVASCRIPT',
		description:
			`A popular programming language for building interactive 
		websites and provides behavior to applications.`,
	},
	{
		word: 'REACT',
		description:
			`A JavaScript library in which we 
		have written this project code.`,
	},
	{
		word: 'PROGRAMMING',
		description: `The process of developing code to 
		assist computers to perform tasks.`,
	},
	{
		word: 'GEEKSFORGEEKS',
		description: `An educational website for
		computer science 'geeks.'`,
	},
	{
		word: 'EXPO',
		description: 'A framework for building universal native apps with React.',
	},
	{
		word: 'MOBILE',
		description: 'Relating to smartphones and tablet devices.',
	},
	{
		word: 'COMPONENT',
		description: 'A reusable building block in React for UI elements.',
	},
	{
		word: 'DEVELOPER',
		description: 'Someone who writes code and creates software applications.',
	},
	{
		word: 'DATABASE',
		description: 'A structured collection of data stored electronically.',
	},
	{
		word: 'NETWORK',
		description: 'A group of interconnected computers or devices.',
	},
];

Step To run the app:

Step 1: To run react native application use the following command:

npx expo start

Step 2: Depending on your operating system type the following comman

  • To run on IOS:
npx react-native run-ios
  • To run on android:
npx react-native run-android

Output:


Next Article

Similar Reads