Tic Tac Toe Game

Create Free Backend With Appwrite

Tic Tac Toe Game Using Flutter

In this guide, we’ll create a simple Tic Tac Toe game using Flutter. We’ll use a GridView.builder to create the game grid and manage the game state.

1. Setup and Project Creation

First, ensure Flutter is installed on your machine. Create a new Flutter project with the following command:

flutter create tic_tac_toe_game

2. Designing the User Interface

Edit the lib/main.dart file with the following code to design the game’s interface:

import 'package:flutter/material.dart';

void main() => runApp(TicTacToeApp());

class TicTacToeApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tic Tac Toe',
      home: TicTacToeScreen(),
    );
  }
}

class TicTacToeScreen extends StatefulWidget {
  @override
  _TicTacToeScreenState createState() => _TicTacToeScreenState();
}

class _TicTacToeScreenState extends State<TicTacToeScreen> {
  List<String> board = List.filled(9, '', growable: false);
  String currentPlayer = 'X';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Tic Tac Toe')),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemCount: board.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () => _markCell(index),
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
              ),
              child: Center(
                child: Text(
                  board[index],
                  style: TextStyle(fontSize: 40),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  void _markCell(int index) {
    if (board[index] == '') {
      setState(() {
        board[index] = currentPlayer;
        currentPlayer = currentPlayer == 'X' ? 'O' : 'X';
      });
    }
  }
}
Run Online

Explanation

  • TicTacToeApp: Sets up the MaterialApp.
  • TicTacToeScreen: A StatefulWidget that contains the UI and logic for the game.
  • board: A list that represents the 3x3 grid of the game.
  • GridView.builder: Used to create the game grid.
  • _markCell: A function to mark a cell with the current player’s symbol.

Game Logic

  • The game alternates between two players, ‘X’ and ‘O’.
  • Players tap on a cell to mark it with their symbol.
  • The game continues until all cells are marked.

Run the App

To run the application, use the flutter run command, or press F5 in Visual Studio Code to start debugging.