Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Explore Tic-Tac-Toe Game In Flutter

To track down Flutter, a well-known open-source framework for making constructed mobile, web, and system applications from a solitary codebase, play the immortal round of spasm tic-tac-toe.

In this article, we will Explore the Tic-Tac-Toe Game In Flutter. We perceive how to execute a demo program. We will show you how to create a tic-tac-toe game in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The demo video below shows how to make a tic-tac-toe game in Flutter for beginners and how the game will work in your Flutter applications. We will offer a user the opportunity to play the game, which will be shown on their device.

Demo Module::


How to implement code in dart file :

You need to implement it in your code respectively:

Ensure Flutter and Dart are set up on your PC before we start writing code. If not, configure your environment using the official Flutter installation manual.

Once Flutter is installed, use the following command to start a new Flutter project:

flutter create flutter_tic_tac_toe_game_demo

This will create a brand-new Flutter project with the name flutter_tic_tac_toe_game_demo. Please click here to access the project directory:

cd flutter_tic_tac_toe_game_demo

Create a new dart file called game_screen.dart inside the lib folder.

First, we will create a list of strings called gameGridis equal to the square bracket. Also, create a String currentPlayer.

List<List<String>> gameGrid = [];
String currentPlayer = '';

Let’s create an initState method. In this method, we will add the startGame() method. In this method, we will add game rationale right into it. We’ll utilize a 2D list to represent the game state where every cell can either be unfilled, “X,” or “O.” We’ll likewise watch the dynamic player.

@override
void initState() {
super.initState();
startGame();
}
void startGame() {
gameGrid = List.generate(3, (_) => List.filled(3, ''));
currentPlayer = 'X';
setState(() {});
}

In this body part, we will add a Column widget. In this widget, we will add a current player which means they will show a playing active player. We will create a game board so, we will use GridView.builder() method.

Column(
children: [
const SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Current Player:',style: TextStyle(fontSize: 18),),
Text(currentPlayer,style: const TextStyle(fontSize: 18,fontWeight: FontWeight.bold),)
],
),
const SizedBox(height: 50,),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 9,
itemBuilder: (context, index) {
final row = index ~/ 3;
final col = index % 3;
return GestureDetector(
onTap: () => onCellTapped(row, col),
child: Container(
decoration: BoxDecoration(
border: Border.all(),
),
child: Center(
child: Text(
gameGrid[row][col],
style: const TextStyle(fontSize: 48),
),
),
),
);
},
),
),
ElevatedButton(onPressed: resetGame,style: ElevatedButton.styleFrom(
backgroundColor: Colors.green.shade300, // Background color
), child: const Text("Reset Game"),)
],
),

In this technique, we will add a 3×3 grid of cells built utilizing a GridView.builder method. In this method, we will add the gridDelegate was a SliverGridDelegateWithFixedCrossAxisCount(), and inside a crossAxisCount was a three. We will add that itemCount was a nine, itemBuilder we will return with GestureDetector() method. In this method, to deal with tapping, we epitomize every cell in a GestureDetector.

The onCellTapped function, which we’ll execute below, is summoned when a cell is tapped. Likewise, we will make an ElevatedButton. On this button, we will add the onPressed() function. In this function, we will add the resetGame function, and add the ElevatedButton.styleFrom() function. Inside the function, we will add backgroundColor was Colors.green.shade300, and its child we will add text “Reset Game”, which we’ll execute beneath, is invoked when a button is tapped.

Let’s create a onCellTapped() function:

The checkForWinner function in this code searches for win conditions while the onCellTapped function updates the board at whatever point a cell is tapped. Utilizing the showWinnerDialog function, we show a dialog on the off chance that there is a winner or a draw.

void onCellTapped(int row, int col) {
if (gameGrid[row][col].isEmpty) {
setState(() {
gameGrid[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
});


String winner = checkForWinner();
if (winner.isNotEmpty) {
showWinnerDialog(winner);
}
}
}


void showWinnerDialog(String winner) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Game Over'),
content:
Text(winner == 'Draw' ? 'It\'s a draw!' : 'Player $winner wins!'),
actions: [
TextButton(
onPressed: () {
resetGame();
Navigator.pop(context);
},
child: const Text('Play Again'),
),
],
),
);
}

Let’s create a checkForWinner() function:

These functions are in charge of determining if the game has a winner or a draw and displaying a dialog when it is over.

String checkForWinner() {
for (int i = 0; i < 3; i++) {
if (gameGrid[i][0] == gameGrid[i][1] &&
gameGrid[i][1] == gameGrid[i][2] &&
gameGrid[i][0].isNotEmpty) {
return gameGrid[i][0];
}
if (gameGrid[0][i] == gameGrid[1][i] &&
gameGrid[1][i] == gameGrid[2][i] &&
gameGrid[0][i].isNotEmpty) {
return gameGrid[0][i];
}
}
if (gameGrid[0][0] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][2] &&
gameGrid[0][0].isNotEmpty) {
return gameGrid[0][0];
}
if (gameGrid[0][2] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][0] &&
gameGrid[0][2].isNotEmpty) {
return gameGrid[0][2];
}
bool isDraw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (gameGrid[i][j].isEmpty) {
isDraw = false;
break;
}
}
}
if (isDraw) {
return 'Draw';
}
return '';
}

Let’s create a resetGame() function:

To allow participants to restart a game, we should at long last form the resetGame function. When the “Play Again” button in the dialog is hit, we utilize this function to reset the game board and the current player.

void resetGame() {
setState(() {
startGame();
});
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Outputs

Code File:


import 'package:flutter/material.dart';

class GameScreen extends StatefulWidget {
const GameScreen({super.key});

@override
State<GameScreen> createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
List<List<String>> gameGrid = [];
String currentPlayer = '';
@override
void initState() {
super.initState();
startGame();
}
void startGame() {
gameGrid = List.generate(3, (_) => List.filled(3, ''));
currentPlayer = 'X';
setState(() {});
}

void onCellTapped(int row, int col) {
if (gameGrid[row][col].isEmpty) {
setState(() {
gameGrid[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
});
String winner = checkForWinner();
if (winner.isNotEmpty) {
showWinnerDialog(winner);
}
}
}

String checkForWinner() {
for (int i = 0; i < 3; i++) {
if (gameGrid[i][0] == gameGrid[i][1] &&
gameGrid[i][1] == gameGrid[i][2] &&
gameGrid[i][0].isNotEmpty) {
return gameGrid[i][0];
}
if (gameGrid[0][i] == gameGrid[1][i] &&
gameGrid[1][i] == gameGrid[2][i] &&
gameGrid[0][i].isNotEmpty) {
return gameGrid[0][i];
}
}
if (gameGrid[0][0] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][2] &&
gameGrid[0][0].isNotEmpty) {
return gameGrid[0][0];
}
if (gameGrid[0][2] == gameGrid[1][1] &&
gameGrid[1][1] == gameGrid[2][0] &&
gameGrid[0][2].isNotEmpty) {
return gameGrid[0][2];
}
bool isDraw = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (gameGrid[i][j].isEmpty) {
isDraw = false;
break;
}
}
}
if (isDraw) {
return 'Draw';
}
return '';
}

void showWinnerDialog(String winner) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Game Over'),
content:
Text(winner == 'Draw' ? 'It\'s a draw!' : 'Player $winner wins!'),
actions: [
TextButton(
onPressed: () {
resetGame();
Navigator.pop(context);
},
child: const Text('Play Again'),
),
],
),
);
}

void resetGame() {
setState(() {
startGame();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text("Flutter Tic-Tac-Toe Game Demo"),
centerTitle: true,
backgroundColor: Colors.green.shade300,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
const SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Current Player:',style: TextStyle(fontSize: 18),),
Text(currentPlayer,style: const TextStyle(fontSize: 18,fontWeight: FontWeight.bold),)
],
),
const SizedBox(height: 50,),
Expanded(
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemCount: 9,
itemBuilder: (context, index) {
final row = index ~/ 3;
final col = index % 3;
return GestureDetector(
onTap: () => onCellTapped(row, col),
child: Container(
decoration: BoxDecoration(
border: Border.all(),
),
child: Center(
child: Text(
gameGrid[row][col],
style: const TextStyle(fontSize: 48),
),
),
),
);
},
),
),
ElevatedButton(onPressed: resetGame,style: ElevatedButton.styleFrom(
backgroundColor: Colors.green.shade300, // Background color
), child: const Text("Reset Game"),)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Tic-Tac-Toe Game In Flutter; you can modify this code according to your choice. This was a small introduction to the Tic-Tac-Toe Game In Flutter In Dart User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Tic-Tac-Toe Game in your Flutter projectsWe will show you what the Introduction is. Make a demo program for working on the Tic-Tac-Toe Game in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.