Create a simple Tic Tac Toe app in Flutter

Sayan Mondal
Jun 6, 2019 · 7 min read

Creating an application which is totally deployable and looks completely native has never been so easy, but hey! we’ve got Flutter now.

This is an amazing start for all the beginners in Flutter as this is something I call like a step into the intermediate world of Flutter development. After making this project you’d definitely feel more confident and have a better grip on the fundamentals of Flutter.

So let's get started, shall we?

What is Flutter?

Flutter is an open-source mobile as well as a web(announced recently at Google IO 2019) development framework created by Google itself. The most loved feature about this framework is you can make applications for both Android as well as iOS on a single codebase. Yes, that’s right, you don’t need to switch between different development environments, all you need is Flutter. It is also announced to be the primary method of creating applications for Google Fuchsia.

To know more about Flutter you can read this article by Paulina Szklarska here: Flutter — 5 reasons why you may love it

Prerequisites

Although this is a pretty simple project with no added dependencies or pulling API requests, there are a couple of things you need, to get started.

Step 1:

Make sure you have flutter installed on your system, whether it’s Mac or Windows or Linux. If you do then Great! 👍 If not, go to the official Flutter Installation Documentation and choose your OS and simply follow the instructions. I would highly recommend you to watch this video if you don’t have Flutter installed in your system yet. 👇 ✨

Installing Flutter into your system

Step 2:

You should have at least a basic amount of knowledge about Dart.

Dart is a client-optimized programming language for fast apps on multiple platforms. It is developed by Google and is used to build mobile, desktop, backend and web applications.

Here is the source code of this project.

How our final product should look

Final Project Look

This is what we’re aiming to build. It’s a simple Tic Tac Toe application which requires two players to play the game, It has an auto reset feature which auto resets the game after one of the player wins.

If any one of the users wants to reset the game midway and try again they can do so by clicking the reset button.

Adding all the assets we’ll need

First things first, let's add all the images(circle, cross, etc) we’ll be needing during our entire project. Open pubspec.yaml file inside your project folder, and scroll through till you see this.

# To add assets to your application, add an assets section, like this:# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg

Download the assets here — Assets Source File or you could explore and choose your own circles, empty box as well as the cross. Replace the above line of code with the new ones. (If you have chosen new images, make sure you give the names of the correct assets)

# To add assets to your application, add an assets section, like this:assets:
- images/circle.png
- images/cross.png
- images/edit.png

Now that you’ve added these assets into your project, Flutter will recognize them easily.

Create a HomePage

Once you are done with adding the assets, go to the lib/main.dart file and delete all the boilerplate code and insert your own themes or app title, etc. Here you’ll link a HomePage class which we’ll create very soon.

To link the HomePage class add a home: HomePage(), right after you’ve created the MaterialApp.

Source Code of main.dart

Now you’ll see a swirly red line at the class declaration and that’s okay to have at this point since we haven’t made that class yet. So let’s go ahead and do that.

Make a new lib/HomePage.dart file, create a Stateful Widget inside of which add three image variables, namely ‘cross’, ‘circle’, ‘empty/edit’ to store all those images we have previously assigned into a variable respectively. Later in this project, we’ll need to return as well as use them for checking purposes so it’s a lot better to store them in a variable beforehand.

class _HomePageState extends State<HomePage> { //TODO: link up images
AssetImage cross = AssetImage("images/cross.png");
AssetImage circle = AssetImage("images/circle.png");
AssetImage edit = AssetImage("images/edit.png");
Snippet of HomePage

Initialize and Reset

Whenever our application loads up for the first time, we want all the boxes to be empty. And the user should be able to tap them and change its state, to do that we need to create a list of strings which should have 9 elements(3 boxes in each row). As we want these elements to be empty whenever the app starts, we need to set the default state to empty.

//Stores if circle wins or cross wins
String message;
//Creating a list of Strings
List<String> gameState;
//TODO: initiazlie the state of box with empty
@override
void initState() {
super.initState();
setState(() {
this.gameState = [
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
"empty",
];
this.message = "";
});
}

Similarly, create a resetGame() function which also sets the game state back to empty whenever the user clicks on the Reset Button.

Initialize and Reset Game State

Changing State to Cross or Circle upon user click

To implement this functionality we have implemented a function called playGame(). This function takes the user click as an index number and checks whether the element of the specific index in gameState(lists of String created earlier) is either empty or not.

To set the state to a cross or a circle alternately upon user click we need to initialize a boolean variable which will keep on switching between True and False upon user click.

Whenever it’s true we can set the state to cross and when it’s false we set it to circle or vice versa.

We’ve also created a function of type AssetImage called getImage() — The primary function of this method is to see what is the state of the index in the gameState list(which the user clicks on) and convert that string into an image(circle or cross).

Switch State upon user click

Game Logic

Surprisingly the logic behind this game is actually very simple, and all you have to do is check consecutive indexes and that’s it. Confused? Let me give you an example.

As we’ve already created our list with 9 elements where there are 3 elements in each row, what we actually have to check is whether the 1st element is equal to the 2nd one and whether or not the 2nd element is equal to the next consecutive element, if your answer is true for both the cases! Viola, you’ve got the winner.

Similarly, you should not just check for horizontal elements but also for vertically downward elements as well in which case the index will go like if the 1st element is equal to the 4th and if that is equal to the 7th. It’s all a matter of indexes.

You should keep doing this check for the 3 horizontal rows and also for the 3 vertical columns. Wait a minute! What about the diagonals? We won’t miss that out either, so again we’ll go for index checking of 1,5 and 9 and for the opposite diagonal we go for 3,5 and 7. And that’s it, there is your main game logic. Yes, it is that simple.

Winning Logic of Tic Tac Toe game

The UI

In Flutter whenever we want to create something that is boxed or clustered and in a fixed space and size the best option to go for is a Grid Layout. In this project, we use something called GridView.builder(), this builder gives us some properties like itemCount and itemBuilder, which helps us to count the total number of elements which will be present in the grid as well as return specific indexes of those contexts which the user taps on.

To see the full UI construction visit here 👇

Photo by Aaron Burden on Unsplash

Last but not the least, Thank you for reading this, Since I’m a beginner and I may make mistakes, feel free to point it out so that I can rectify them along the way. If you want to see more Flutter projects consider exploring my GitHub account.

Peace Out.

The Startup

Medium's largest active publication, followed by +588K people. Follow to join our community.

Sayan Mondal

Written by

Tech enthusiast | Microsoft Technology Associate Certified | Flutter Developer | One-sided lover of Google.

The Startup

Medium's largest active publication, followed by +588K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade