Hướng dẫn tạo game Tic-Tac-Toe bằng React-Native

React Native cho phép ứng dụng chạy một code base duy nhất trên nhiều nền tảng như Android, iOS... Học cách phát triển game TicTacToe cho phép bạn học cách tạo kiểu cơ bản, tương tác người dùng và nhiều hơn thế nữa. Tất cả sẽ giúp bạn cải thiện nền tảng cơ bản trong React-Native.

Game TicTacToe

Điều kiện cần có để lập trình game Tic-Tac-Toe bằng React Native

  • Node.js
  • React Native
  • React Native Components
  • React Event Handling
  • Expo CLI

Hướng dẫn tạo game Tic-Tac-Toe bằng React Native

Thành phần react tên TicTacToe được tạo để triển khai logic game, bảng, kiểu và xử lý sự kiện. Logic game bao gồm xử lý tương tác người dùng như click vào hình vuông trên bảng và khởi động lại nút bấm game. Logic game cũng bao gồm logic kiểm tra người chiến thắng ở mỗi bước di chuyển & khởi động lại game. Bằng cách click vào nút khởi động lại, game sẽ được reset. Khi cả hai người chơi đều không còn bước di chuyển, game kết kết thúc.

Quy tắc chơi game Tic-Tac-Toe

  • Đây là game được chơi trên bảng kẻ ô 3x3.
  • Một người chơi sẽ chọn biểu tượng X, người còn lại chọn O.
  • Người chơi có thể đánh dấu những biểu tượng này trên bảng kẻ ô.
  • Người chơi đánh được 3 dấu liên tiếp theo hàng ngang, dọc hoặc chéo trước tiên sẽ được xem là người chiến thắng.
  • Nếu cả hai người chơi đều hết bước di chuyển, trò chơi sẽ kết thúc với tỷ số hòa.

Các bước tạo dự án

Bước 1: Tạo ứng dụng React-Native bằng lệnh sau:

npx create-expo-app tictactoe

Bước 2: Mở thư mục dự án React Native bằng lệnh cd:

cd tictactoe

Bước 3: Cài đặt package “npm install react-native-paper” bằng lệnh cài npm sau:

npm install react-native-paper

Cấu trúc dự án:

Cấu trúc dự án

Ví dụ: Viết code bên dưới trong file App.js:

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,	 }; } // Function to handle clicks on the squares handleClick(i) {	 const squares = this.state.squares.slice();	 if (calculateWinner(squares) || squares[i]) {		 return;	 }	 squares[i] =		 this.state.xIsNext ? 'X' : 'O';	 this.setState({		 squares: squares,		 xIsNext: !this.state.xIsNext,	 }); } // Function to restart the game restartGame() {	 this.setState({		 // Set default values to reset the game		 squares: Array(9).fill(null),		 xIsNext: true,	 }); } // Function to render the squares while playing renderSquare(i) {	 return (		 // render individual squares		 <TouchableOpacity			 style={styles.square}			 onPress={() => this.handleClick(i)}		 >			 <Text style={styles.squareText}>				 {this.state.squares[i]}			 </Text>		 </TouchableOpacity>	 ); } // Function to render everything inside the component render() {	 const winner =		 calculateWinner(this.state.squares);	 let status;	 // if someone won the game, change the status to winner	 // if all the squares are filled and no is won, Display as draw!	 if (winner) {		 status = `Winner: ${winner}`;	 } else if (this.state.squares.every((square) =>		 square !== null)) {		 status = 'Draw!';	 } else {		 status = `Next player:				 ${this.state.xIsNext ? 'X' : 'O'}`;	 }	 // return entire game screen	 return (		 <View style={styles.container}>			 <Text style={styles.title}>				 Tic Tac Toe			 </Text>			 <View style={				 {					 flexDirection: 'row',					 flexWrap: 'wrap'				 }			 }>				 {this.renderSquare(0)}				 {this.renderSquare(1)}				 {this.renderSquare(2)}			 </View>			 <View				 style={					 {						 flexDirection: 'row',						 flexWrap: 'wrap'					 }				 }>				 {this.renderSquare(3)}				 {this.renderSquare(4)}				 {this.renderSquare(5)}			 </View>			 <View				 style={					 {						 flexDirection: 'row',						 flexWrap: 'wrap'					 }				 }>				 {this.renderSquare(6)}				 {this.renderSquare(7)}				 {this.renderSquare(8)}			 </View>			 <Text style={styles.status}>				 {status}			 </Text>			 <Button				 title="Restart Game"				 onPress={() => this.restartGame()}				 style={styles.restartButton}			 />		 </View>	 ); }}// Stylingsconst styles = StyleSheet.create({ container: {	 flex: 1,	 justifyContent: 'center',	 alignItems: 'center',	 backgroundColor: '#FFFFE0', }, title: {	 fontSize: 24,	 marginBottom: 20, }, square: {	 width: 100,	 height: 100,	 borderWidth: 1,	 borderColor: 'black',	 justifyContent: 'center',	 alignItems: 'center', }, squareText: {	 fontSize: 40, }, status: {	 marginVertical: 20,	 fontSize: 20, }, restartButton: {	 marginTop: 10, },});// Function to determine the winner function calculateWinner(squares) { const lines = [	 [0, 1, 2],	 [3, 4, 5],	 [6, 7, 8],	 [0, 3, 6],	 [1, 4, 7],	 [2, 5, 8],	 [0, 4, 8],	 [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) {	 const [a, b, c] = lines[i];	 if (squares[a] &&		 squares[a] === squares[b] &&		 squares[a] === squares) {		 return squares[a];	 } } return null;}// Return the entire componenentexport default function App() { return (	 <PaperProvider>		 <Appbar.Header>			 <Appbar.Content				 title="Tic Tac Toe" />		 </Appbar.Header>		 <TicTacToe />	 </PaperProvider> );}

Các bước chạy game Tic-Tac-Toe

Bước 1: Điều hướng tới nhắc lệnh/terminal và chạy lệnh sau để khởi động ứng dụng Tic Tac Toe.

npx expo start

Bước 2: Dựa trên kiểu hệ điều hành, nhập lệnh sau:

Để chạy ứng dụng trên thiết bị Android:

npx react-native run-android

Để chạy ứng dụng trên iOS:

npx react-native run-ios

Kết quả:

Kết quả game Tic-Tac-Toe

Thế là xong! Chúc các bạn thành công!

Thứ Sáu, 10/11/2023 16:43
31 👨 160
0 Bình luận
Sắp xếp theo