Flutter Tic Tac Toe Game TutorialL A complete guide

Tic Tac Toe, a classic game that has stood the test of time, is a fantastic project to develop in Flutter. Whether you’re building it for fun, to showcase your skills, or to challenge your friends with a quick game, creating a Flutter Tic Tac Toe game offers a perfect mix of creativity and learning. This tutorial will guide you through developing a Tic Tac Toe game in Flutter with features like AI integration, multiplayer support, and a user-friendly interface.

Flutter Tic Tac Toe Game Tutorial

Table of Contents

  1. Introduction to Flutter Tic Tac Toe
  2. Setting Up Your Flutter Project
  3. Features of the Tic Tac Toe Game
  4. Full Code Explanation
  5. Enhancements for a Better Gaming Experience
  6. Conclusion

1. Introduction to Flutter Tic Tac Toe

Tic Tac Toe is a simple two-player game where players alternately place their symbols (X or O) on a 3×3 grid. The first to align three symbols in a row, column, or diagonal wins.

In this project:

2. Setting Up Your Flutter Project

Step 1: Create a New Flutter Project

flutter create tic_tac_toe
cd tic_tac_toe

Step 2: Add Assets

Include the necessary images (cross_.png, circle_.png) in the assets folder and update pubspec.yaml:

flutter:
assets:
- assets/cross_.png
- assets/circle_.png

Run flutter pub get to load the assets.

3. Features of the Tic Tac Toe Game

  1. Game Modes: Play against AI or another player.
  2. Customizable Gameplay: Players can select their side (X or O).
  3. Score Tracking: Displays and updates scores for both players.
  4. User-Friendly UI: Intuitive design with animated transitions.
  5. AI Logic: The AI uses basic strategies to compete with players.

4. Full Code Explanation

Here’s the full Flutter code for the game, broken into logical segments:

Main App Setup

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

class TicTacToeApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue),
home: PlayModeScreen(),
);
}
}

Game Start Screen

The PlayModeScreen lets users choose between playing with AI or a friend.

class PlayModeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xfff6f6f6),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/cross_.png', width: 100),
Image.asset('assets/circle_.png', width: 100),
],
),
SizedBox(height: 50),
Text(
"Choose your play mode",
style: TextStyle(fontSize: 24),
),
SizedBox(height: 50),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChooseSideScreen(isAI: true),
),
);
},
child: Text("With AI"),
),
SizedBox(height: 30),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChooseSideScreen(isAI: false),
),
);
},
child: Text("With a Friend"),
),
],
),
),
);
}
}

Choose Side Screen

The ChooseSideScreen allows players to pick their preferred symbol, X or O.

class ChooseSideScreen extends StatefulWidget {
final bool isAI;
const ChooseSideScreen({required this.isAI});

@override
_ChooseSideScreenState createState() => _ChooseSideScreenState();
}

class _ChooseSideScreenState extends State<ChooseSideScreen> {
String selectedSide = 'X';

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Text("Pick your side"),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Radio(
value: 'X',
groupValue: selectedSide,
onChanged: (value) => setState(() => selectedSide = value!),
),
Radio(
value: 'O',
groupValue: selectedSide,
onChanged: (value) => setState(() => selectedSide = value!),
),
],
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GameScreen(
playerSide: selectedSide,
isAI: widget.isAI,
),
),
);
},
child: Text("Start Game"),
),
],
),
),
);
}
}

Game Screen

This is where the actual game happens. It includes the grid, game logic, and AI implementation.

class GameScreen extends StatefulWidget {
final String playerSide;
final bool isAI;

GameScreen({required this.playerSide, required this.isAI});

@override
_GameScreenState createState() => _GameScreenState();
}

class _GameScreenState extends State<GameScreen> {
List<String> board = List.filled(9, '');
String currentPlayer = 'X';
String winner = '';

void resetBoard() {
setState(() {
board.fillRange(0, board.length, '');
winner = '';
currentPlayer = 'X';
});
}

void makeMove(int index) {
if (board[index] == '' && winner == '') {
setState(() {
board[index] = currentPlayer;
currentPlayer = currentPlayer == 'X' ? 'O' : 'X';
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemBuilder: (context, index) => GestureDetector(
onTap: () => makeMove(index),
child: Container(
child: Center(
child: Text(board[index], style: TextStyle(fontSize: 32)),
),
),
),
itemCount: 9,
),
ElevatedButton(onPressed: resetBoard, child: Text("Reset")),
],
),
);
}
}

5. Enhancements for a Better Gaming Experience

  1. AI Improvements: Implement a minimax algorithm for a smarter AI.
  2. Animations: Add animations for moves and results.
  3. Themes: Include light and dark themes.
  4. Leaderboard: Track scores across sessions.

6. Conclusion

Creating a Tic Tac Toe game in Flutter is a great way to sharpen your skills. This project not only covers Flutter UI design but also incorporates logic building for game rules and AI.

Explore Other Flutter Topics…

  1. Introduction to Flutter and Dart
  2. Why choose Flutter
  3. Installing Flutter On Your Windows Mac And Linux System
  4. Your first Flutter app
  5. Flutter project structure
  6. Building blocks of Flutter
  7. Stateful vs. Stateless Widgets Explained
  8. Flutter layout system
  9. Flutter text widget
  10. Creating Buttons in Flutter: ElevatedButton, TextButton, and IconButton
  11. Handling User Input with Flutter Forms
  12. Container class in Flutter
  13. Flutter Navigation
  14. Flutter – Pass Data One Screen To Another Screen
  15. Managing Device Orientation in Flutter
  16. Stateful widget lifecycle in Flutter
  17. Future of Flutter
  18. Flutter Themes
  19. Flutter Animations
  20. Flutter AppBar Customization
  21. ListView in Flutter
  22. Flutter GridView
  23. Flutter Expanded Widget
  24. Flutter BottomNavigation Bar
  25. Floating Action Button
  26. Drawer Widgets in Flutter
  27. Form Validation in Flutter
  28. Flutter TextField
  29. Adding AdMob ads to a Flutter app
  30. Building Flutter Web & Desktop Applications
  31. What is Async and Await in Flutter
  32. HTTP requests in Flutter
  33. Parsing JSON in Flutter
  34. Tinder-Style Swipe Cards in Flutter
  35. Flutter Tic Tac Toe Game Tutorial
  36. Flutter Login UI Tutorial
  37. Flutter Card Widget Tutorial
  38. Flutter music player app tutorial
  39. Flutter introduction screens
  40. Shared Preferences in Flutter
  41. SQLite Database in Flutter
  42. Firebase Authentication in Flutter
  43. Firebase Firestore in Flutter
  44. Push Notifications in Flutter
  45. Handling File Uploads in Flutter
  46. Responsive Design in Flutter
  47. Provider in Flutter
  48. Riverpod in Flutter
  49. Flutter BLoC Pattern Tutorial

Leave a Reply

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