Create a Tic-Tac-Toe using React-Native
Last Updated :
09 Nov, 2023
In this article, we will learn how to build a Tic-Tac-Toe game using React-Native. React Native enables the application to run a single code base on multiple platforms like Android, IOS, etc. Developing the TicTacToe game application allows us to learn basic styling, app logic, user interaction, and more which will help improve our basic foundation in React-Native.
Preview of final output: Let us have a look at how the final application will look like.
Tic Tac Toe using React Native
Prerequisites:
Approach:
The react component named “TicTacToe” is created to implement game logic, board, styling and event handling. The game logic includes handling user interactions like clicking squares on the board and restart game button. The game logic also includes the logic to check winner at every move and restart the game. By clicking the restart button, the game will be reset. When there is no more moves to do from both the players then the game will be draw.
Rules of Tic-Tac-Toe:
- It is a game played on 3 X 3 grid.
- One player should pick symbol ‘X’ another player should pick ‘O’.
- The players can mark their symbols on the grid alternatively.
- The player who marked 3 in a row horizontally, vertically or diagonally at first will be considered as winner.
- If there is no more moves to do from both the players then the game is draw.
Steps to create the project:
Step 1: Create React-Native Application using the following command
npx create-expo-app tictactoe
Step 2: Open the React Native project folder using “cd” command.
cd tictactoe
Step 3: Install “npm install react-native-paper” package using the following npm install command.
npm install react-native-paper
Project Structure:
Project Structure
Example: Write the below code in the App.js file.
Javascript
import React, { Component } from 'react' ;import { View, Text, TouchableOpacity, Button, StyleSheet} from 'react-native' ;import { Provider as PaperProvider, Appbar} from 'react-native-paper' ;class TicTacToe extends Component { constructor(props) { super (props); this .state = { squares: Array(9).fill( null ), xIsNext: true , }; }
|
Steps to run the application:
Step 1: Navigate to terminal/command prompt and run the following command to run the Tic Tac Toe application.
npx expo start
Step 2: Based on your operating system type the following command:
- To run the application in android device.
npx react-native run-android
- To run the application in iOS device
npx react-native run-ios
Output:
TicTacToe using React-Native demo
Share your thoughts in the comments
Please Login to comment...