Create Games with Flutter | Tic Tac Toe

Hello, guys! Do you know you can make games using Flutter?

This week, I learned how to make Tic Tac Toe using Flutter, and in this post, I’ll describe how you can make your own Tic Tac Toe game with Flutter.

Tic Tac Toe Game Made using Flutter

It took me two days to design the game itself, then another two days to personalize the app on my own. It was a lot of fun attempting to put this game together.

I followed Mitch Koko while creating this application. His YouTube videos are so awesome.

Create Games Using Flutter

Table of Contents:

  1. Introduction
  2. Logic and Coding
    1. Creating a 3 * 3 Grid
    2. Defining O and X
    3. Winning the Game
    4. Making the Draw
    5. Conclusion and What’s Next

Introduction

This image has an empty alt attribute; its file name is 5c9nb1.gif

This is the intro Screen that the user first sees when he opens the application. I added animation and effects like Hero Animation and Avatar Glow effect.

This is the second screen that users see after the user presses the Play Game Button. There are three expanded widgets.

First Expanded Widget: This was used for Scoreboard which collects the information on Player O and Player X wins and losses. On the Player’s win, the counter will go from 0 to 1.

Second Expanded Widget: I set the flex to 3 for this widget. This was used for the game itself. Once the user taps on one of the 9 boxes, O or X will appear on the game board. This was done by using GridBuilder for making 3 by 3 Grid.

Third Expanded Widget: This was used for mainly three functions- to reset the counter on Scoreboard, to reset the gameboard and for Day and Night function as shown in the images above.

Now Let’s get started.

The Main Logic and Code

Creating a 3 * 3 Grid

First of all, we will be building a 3 by 3 Grid using GridView Builder. The codes are as follows:

Expanded(
               flex: 3,
               child: Container(
                 child: GridView.builder(
                     itemCount: 9,
                     gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                         crossAxisCount: 3),
                     itemBuilder: (BuildContext context, int index) {
                       return GestureDetector(
                         onTap: () {},
                         child: Container(
                           child: Center(
                             child: Text(
                               index,
                             ),
                           ),
                         ),
                       );
                     }),
               ),
             ),

The itemcount is set to 9 for 9 boxes. We will be using SliverGridDelegateWithFixedCrossAxisCount with crossAxiscount which we will set to 3, so as to create 3 columns. You can read the documentation of SliverGridDelegateWithFixedCrossAxisCount for more details. We will be returning the GestureDetector.

Grid making with flutter tutorials
The Output of the Above Code

The GestureDetector requires onTap property.

With onTap, we can define what will happen if users were to click on each box. For now, we will keep the onTap empty.

Defining O and X

We first declared oturn as a bool type which can either be true or false only. We will set oturn as true at first.

bool oturn = true;

List<String> display = ["", "", "", "", "", "", "", "", ""]; 

We will also be declaring display as List type which first contains 9 empty items as shown above.

Now it’s time to describe the situation when we will use O and X. We will define that in _tapped() method.

  _tapped(index) {
    setState(() {
      if (oturn && display[index] == "") {
        display[index] = "O";
      } else if (!oturn && display[index] == "") {
        display[index] = "X";
      }
      oturn = !oturn;
      checkwin();
    });
  }

Then with the use of If and else if statements, we will assign X or O in those boxes.

display[index] defines the box location where the user tap. For example, display[4]’s location would be the center as shown in the image below.

making a grid in flutter

The first if statement defines if oturn is true and if display[index] is empty then the box will have O when the user taps on the box. Similarly, when oturn is false and if display[index] is empty, then the box will have X.

In the end, we will do ohturn =! ohturn meaning if it is O turn, next it will be X’s turns, but both O and X values/turns cannot be the same at the same time.

We put _tapped(index) method inside onTap.

Expanded(
               flex: 3,
               child: Container(
                 child: GridView.builder(
                     itemCount: 9,
                     gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                         crossAxisCount: 3),
                     itemBuilder: (BuildContext context, int index) {
                       return GestureDetector(
                         onTap: () {
                           _tapped(index);
                         },
                         child: Container(
                           decoration: griddecoration,
                           child: Center(
                             child: Text(
                               display[index],
                               style: oxstyle,
                             ),
                           ),
                         ),
                       );
                     }),
               ),
             ),

Winning the Game

We will also constantly check whether the game has been finished or not with the help of checkwin() method.

checkwin() {
    if (display[0] == display[1] &&
        display[0] == display[2] &&
        display[0] != "") {
      showDialogBox(display[0]);
    }
    if (display[3] == display[4] &&
        display[3] == display[5] &&
        display[3] != "") {
      showDialogBox(display[3]);
    }
    if (display[6] == display[7] &&
        display[6] == display[8] &&
        display[6] != "") {
      showDialogBox(display[6]);
    }
    if (display[0] == display[3] &&
        display[0] == display[6] &&
        display[0] != "") {
      showDialogBox(display[6]);
    }
    if (display[1] == display[4] &&
        display[1] == display[7] &&
        display[1] != "") {
      showDialogBox(display[1]);
    }
    if (display[2] == display[5] &&
        display[2] == display[8] &&
        display[2] != "") {
      showDialogBox(display[5]);
    }
    if (display[0] == display[4] &&
        display[0] == display[8] &&
        display[0] != "") {
      showDialogBox(display[0]);
    }
    if (display[2] == display[4] &&
        display[2] == display[6] &&
        display[2] != "") {
      showDialogBox(display[6]);
    }
    if (filledBox == 9) {
      showDrawDialog();
    }
  }

Here we are checking if display[0] is equal to display[1] and display[2] and is not empty for the first row. If all the boxes on the first row have the same value(O or X), then showDialogBox(display[0]) will be triggered. The showDialogBox has the task of creating a simple alert box to inform the user that somebody won.

Similarly, we will check the second row 3, 4, 5, and third-row 6, 7, 8. Then next is three columns and we also have to check the two diagonals 0, 4, 8 and 2, 4, 6.

Making the Draw

We will also be checking if there is any draw or not by using filledbox with integer datatype. First, we will set filledbox to 0 and as the user taps on each box, the filledbox value will increase by one and once it reaches 9, that means there are 9 taps and still no one has won, hence we will show the draw information using showDrawDialog method.

Conclusion and What’s Next

That’s all the information needed to build the Tic Tac Toe Game. Now you can also make Tic Tac Toe Game.

Good Luck! Make your own Flutter Game.

Next Step:

I will try to make this Game responsive to most android devices and learn how to put ads on the application. If all done, I will put the TicTacToe on Google Play Store.

Thanks for reading. Hope you have a good day.

Leave a Comment