Steps To Build A Tic Tac Toe Game with Dart

Steps To Build A Tic Tac Toe Game with Dart

At first when this assignment was given I thought I understood what we were asked to do until I started doing my research and looking for materials to study in other for me to get a better understanding of the work, then it stucked me that I never understood the question or what I was asked to do in the first place then I started with the battle of understanding the questions before I could be able to get the work done it took a lot of time but at last we are here and am happy and glad that the amount of time and hardwork I had to put into this project paid at the end. Enough of the long story let's get into the work proper :

Content Of The Assignment

Build a 2-player Tic Tac Toe game (Version 1) Write an article detailing your steps and thought process Features of the game: Draw out the tic tac toe board on the console Handle user input for x and o and store it (For e.g, When a player 1 who is X wants to place an X on the screen, they can’t click the terminal. So you are going to replace this clicking by asking the user for a coordinate of where they want to place their piece.)

Steps :

  1. I imported dart:io by typing, import dart:io which is a library that allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more. Many operations related to input and output are asynchronous and are handled using [Future]s or [Stream]s, both of which are defined in the dart:async library.

  2. I also imported dart:core by typing import dart:core which is a built-in types, collections, and other core functionality for every Dart program. It provides basic collection such as List, Map and Set.

  3. Bool winner = false; these statement is false because the game is yet to start and there is no winner yet.

  4. Bool isXturn = true; these statement is true because it's the turn of player X to play ie to start the game. IntmoveCount =0;

  5. List<String> is used to list the values ie (coordinates) the players are to use while playing the game from number 1-9

  6. List<String> combination= ['012', '048', '036', '147', '246', '258', '345', '678']; the combinations for the game are generated here.

  7. In my main void I generated the board for the game. Then get the next characters to play also check if the combination is true or false for a player ie X or O. The players are required to place their values where they want to place it ie X or O as the case maybe so this go on until there is a winner or in the case where there is a draw the console is being cleared using clearScreen(); and another new board is been redrawn with new information with generateBoard(); this has to go on until a winner is been declared.

  8. So at the end I created an if else statement that if the platform is Windows print(process.runSync("cls", [] ,runInShell: true).stdout); but if the otherwise print(process.runSync("clear", [], runInShell: true).stdout);

The Code


import 'dart:io';
import 'dart:core';

bool winner = false;
bool isXturn = true;
int moveCount = 0;
List<String> values = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
List<String> combinations = ['012', '048', '036', '147', '246', '258', '345', '678'];
void main() {
  generateBoard();
  getnextCharacter();
}
//check if a combination is true or false for a player (X or 0)
bool checkCombination(String combination, String checkFor) {
  //split the numbers in a list of integers
  List<int> numbers = combination.split('').map((item) {
    return int.parse(item);
  }).toList();
  bool match = false;
  for (final item in numbers) {
    if (values[item] == checkFor) {
      match = true;
    } else {
      match = false;
      break;
    }
  }
  return match;
}
void checkWinner(player) {
  for (final item in combinations) {
    bool combinationValidity = checkCombination(item, player);
    if (combinationValidity == true) {
      print('$player WON!');
      winner = true;
      break;
    }
  }
}
//get input, check winners
void getnextCharacter() {
  //get input from player
  print('Choose Number for ${isXturn == true ? "X" : "0"}');
  int number = int.parse(stdin.readLineSync());
  //change the value of selected number in values
  values[number - 1] = isXturn ? 'X' : '0';
  //change player turn
  isXturn = !isXturn;
  //increment move count
  moveCount++;
  if (moveCount == 9) {
    winner = true;
    print('DRAW!');
  } else {
    //clear the console
    clearScreen();
    //redraw the board with the new information
    generateBoard();
  }
  //
  //Check Validity for players, declare winner
  //
  //check validity for player X
  checkWinner('X');
  //check validity for player 0
  checkWinner('0');

  //until we have a winner, we call current function again
  if (winner == false) getnextCharacter();
}
//clear console screen
void clearScreen() {
  if (Platform.isWindows) {
    print(Process.runSync("cls", [], runInShell: true).stdout);
  } else {
    print(Process.runSync("clear", [], runInShell: true).stdout);
  }
}
//show current state of board
void generateBoard() {
  print('   |   |   ');
  print(' ${values[0]} | ${values[1]} | ${values[2]} ');
  print('___|___|___');
  print('   |   |   ');
  print(' ${values[3]} | ${values[4]} | ${values[5]} ');
  print('___|___|___');
  print('   |   |   ');
  print(' ${values[6]} | ${values[7]} | ${values[8]} ');
  print('   |   |   ');
}