Build Tic Tac Toe game with ChatGPT

Build Tic Tac Toe game with ChatGPT

Hey there welcome to this new article where i will share the fastest way to build Flutter mobile application with less or no coding. we are not using any kind of no code platform. We will take help of ChatGPT for coding stuff.

As we all know ChatGPT made by openAI is AI model tool which process your queries and generate appropriate answers. In this tutorial we are building Tic Tac Toe game project with help of ChatGPT. We will ask coding stuff to ChatGPT and our part is just understand code developed by AI tool and assemble it in proper manner. If some bud or error arise we solve it by ourselves or we can agin take help of ChatGPT.

That is it for the introduction let’s start with the stuff which coding ๐Ÿคฉ

See Video Tutorial :

Build Tic Tac Toe game with ChatGPT

Step by step process to build Tic-Tac-Toe game with ChatGPT

Step 1 : Ask Prompt to ChatGPT

As we all know chatGPT is chatbot but the smart one. so first thing we need is to open ChatGPT and type prompt to build this Tic Tac Toe game for us. You can write prompts as you like but here is mine which i used for this project.

You can ChatGPT by going on this link : ChatGPT

write flutter code for multiplayer tic tac toe game user can be real or AI

after writing this prompt you have to wait for the response. With this prompt you will get complete source code for Tic Tac Toe game now the next step is to create project and assemble the code.


Step 2 : Create Flutter Project

Now after the code generation, It is time to implementation of this Flutter Code. Lets create Flutter Project with Help of the Vscode Not explaining the project creation part because if you donโ€™t know the basics yet you need to learn basics to understand the process of implementation of code.

Creating a new project

To create a new Flutter project from the Flutter starter app template:

  1. Open the Command Palette (Ctrl+Shift+P (Cmd+Shift+P on macOS)).
  2. Select the Flutter: New Project command and press Enter.
  3. Select Application and press Enter.
  4. Select a Project location.
  5. Enter your desiredย Project name.

Read more about flutter project creation at https://docs.flutter.dev/tools/vs-code

Step 3 : Replace the main.dart file with new generated Code

After successful project creation. Open main.dart file and replace its code with the new generated code by ChatGPT. Here is My code which i get from ChatGPT

main.dart

import 'dart:math';
import 'package:flutter/material.dart';

void main() {
  runApp(TicTacToeApp());
}

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

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

class _TicTacToeScreenState extends State<TicTacToeScreen> {
  List<String> board = List.filled(9, '');
  bool isPlayer1Turn = true; // Player 1 starts
  bool gameFinished = false;

  void makeMove(int index) {
    if (!gameFinished && board[index] == '') {
      setState(() {
        board[index] = isPlayer1Turn ? 'X' : 'O';
        isPlayer1Turn = !isPlayer1Turn;
      });
      checkWinner();
      if (!isPlayer1Turn && !gameFinished) {
        // AI's turn
        int aiMove = getBestMove();
        makeMove(aiMove);
      }
    }
  }

  int getBestMove() {
    int bestScore = -1000;
    int bestMove = -1;
    for (int i = 0; i < 9; i++) {
      if (board[i] == '') {
        board[i] = 'O';
        int score = minimax(board, 0, false);
        board[i] = '';
        if (score > bestScore) {
          bestScore = score;
          bestMove = i;
        }
      }
    }
    return bestMove;
  }

  int minimax(List<String> board, int depth, bool isMaximizing) {
    int score = evaluate(board);
    if (score == 10) return score;
    if (score == -10) return score;
    if (!board.contains('')) return 0;

    if (isMaximizing) {
      int bestScore = -1000;
      for (int i = 0; i < 9; i++) {
        if (board[i] == '') {
          board[i] = 'O';
          bestScore = max(bestScore, minimax(board, depth + 1, !isMaximizing));
          board[i] = '';
        }
      }
      return bestScore;
    } else {
      int bestScore = 1000;
      for (int i = 0; i < 9; i++) {
        if (board[i] == '') {
          board[i] = 'X';
          bestScore = min(bestScore, minimax(board, depth + 1, !isMaximizing));
          board[i] = '';
        }
      }
      return bestScore;
    }
  }

  int evaluate(List<String> board) {
    // Check rows, columns, and diagonals for a win
    for (int i = 0; i < 3; i++) {
      if (board[i * 3] == board[i * 3 + 1] &&
          board[i * 3] == board[i * 3 + 2]) {
        if (board[i * 3] == 'O') return 10;
        if (board[i * 3] == 'X') return -10;
      }
      if (board[i] == board[i + 3] && board[i] == board[i + 6]) {
        if (board[i] == 'O') return 10;
        if (board[i] == 'X') return -10;
      }
    }
    if (board[0] == board[4] && board[0] == board[8]) {
      if (board[0] == 'O') return 10;
      if (board[0] == 'X') return -10;
    }
    if (board[2] == board[4] && board[2] == board[6]) {
      if (board[2] == 'O') return 10;
      if (board[2] == 'X') return -10;
    }
    return 0; // No winner yet
  }

  void checkWinner() {
    for (int i = 0; i < 3; i++) {
      if (board[i * 3] == board[i * 3 + 1] &&
          board[i * 3] == board[i * 3 + 2] &&
          board[i * 3] != '') {
        showWinnerDialog(board[i * 3]);
        return;
      }
      if (board[i] == board[i + 3] &&
          board[i] == board[i + 6] &&
          board[i] != '') {
        showWinnerDialog(board[i]);
        return;
      }
    }
    if (board[0] == board[4] && board[0] == board[8] && board[0] != '') {
      showWinnerDialog(board[0]);
      return;
    }
    if (board[2] == board[4] && board[2] == board[6] && board[2] != '') {
      showWinnerDialog(board[2]);
      return;
    }
    if (!board.contains('')) {
      showDrawDialog();
    }
  }

  void showWinnerDialog(String winner) {
    setState(() {
      gameFinished = true;
    });
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Game Over'),
        content: Text('$winner wins!'),
        actions: [
          TextButton(
            onPressed: () {
              resetGame();
              Navigator.of(context).pop();
            },
            child: Text('Play Again'),
          ),
        ],
      ),
    );
  }

  void showDrawDialog() {
    setState(() {
      gameFinished = true;
    });
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Game Over'),
        content: Text('It\'s a draw!'),
        actions: [
          TextButton(
            onPressed: () {
              resetGame();
              Navigator.of(context).pop();
            },
            child: Text('Play Again'),
          ),
        ],
      ),
    );
  }

  void resetGame() {
    setState(() {
      board = List.filled(9, '');
      isPlayer1Turn = true;
      gameFinished = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Tic Tac Toe'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
              ),
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
                  onTap: () {
                    makeMove(index);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(),
                    ),
                    child: Center(
                      child: Text(
                        board[index],
                        style: TextStyle(fontSize: 40),
                      ),
                    ),
                  ),
                );
              },
              itemCount: 9,
              shrinkWrap: true,
            ),
            if (gameFinished)
              ElevatedButton(
                onPressed: resetGame,
                child: Text('Restart Game'),
              ),
          ],
        ),
      ),
    );
  }
}

Step 4 : Run the Code

That is it after coping code from ChatGPT and some bug fixes you can run the code and see running Tic Tac Toe game. Now test the function of the game. Add more function the same way by asking code from ChatGPT and publish Your version of this game. You can also do the same steps for other small project but you need to write prompt in such way that ChatGPT can understand properly and write code as per your need.


Follow me at

Facebook : https://www.facebook.com/rajjani8/

Youtube : https://www.youtube.com/channel/UClqD9_F5sCJN1st7tl30Q2A

Github : https://github.com/rajjani88

Instagram : https://www.instagram.com/_rajjani/

Thanks for Reading see you in the next one ๐Ÿ™‚

Raj Avatar