Table of contents
Tic-tac-toe, a game that uses Xs and Os, involves two players who take turns marking the spaces in a three-by-three grid with X or O. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner of the game.
Features of The Game
The game is played on a grid that's 3 squares by 3 squares.
You are X, and your friend (or the computer) is O. Players take turns putting their marks in empty squares.
The first player to get 3 of their marks in a row (up, down, across, or diagonally) is the winner.
When all 9 squares are full, the game is over and it is a draw.
Steps in Achieving the Code
I imported
dart:io
by typing, importdart: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.I also imported
dart:core
by typing importdart:core
which is a built-in type, collection, and other core functionality for every Dart program. It provides basic collections such as List, Map and Set.Bool
winner = false; this statement is false because the game is yet to start and there is no winner yet.Bool
isXturn = true; this statement is true because it's the turn of player X to play ie to start the game.Int
moveCount =0;List<String>
is used to list the value ie (coordinates) the players are to use while playing the game from numbers 1-9List<String> combination= ['012', '048', '036', '147', '246', '258', '345', '678'];
the combinations for the game are generated here.In my main void I generated the board for the game. Then get the next characters to play and 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 them ie X or O as the case may be so this goes on until there is a winner or in the case where there is a draw the console is cleared using
clearScreen();
and another new board is been redrawn with new information withgenerateBoard();
this has to go on until a winner is been declared.So in the end, I created an if-else statement that if the platform is Windows
print(process.runSync("cls", [] ,runInShell: true).stdout);
but if the otherwiseprint(process.runSync("clear", [], runInShell: true).stdout).
Code Sample
import 'dart:core';
import 'dart:io';
bool winner = false;
bool isXturn = true;
List<String> cordinates = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
List<String> combinations = ['012', '048', '036', '147', '246', '258', '345', '678'];
void main() {
generateBoard();
getnextCharacter();
}
int movementCount = 0;
//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 (cordinates[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" : "O"}');
int number = int.parse(stdin.readLineSync()!);
//change the value of selected number in cordinates
cordinates[number - 1] = isXturn ? 'X' : 'O';
//change player turn
isXturn = !isXturn;
//increment move count
movementCount++;
if (movementCount == 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 O
checkWinner('O');
//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);
}
}
void generateBoard() {
print(' | | ');
print(' ${cordinates[0]} | ${cordinates[1]} | ${cordinates[2]} ');
print('___|___|___');
print(' | | ');
print(' ${cordinates[3]} | ${cordinates[4]} | ${cordinates[5]} ');
print('___|___|___');
print(' | | ');
print(' ${cordinates[6]} | ${cordinates[7]} | ${cordinates[8]} ');
print(' | | ');
}
}
}
}
Conclusion
This article has shown the basics of creating a functional tic-tac-toe game using the dart programming language in a very simple way. The code sample includes a tictactoe game that can be played effectively between two players. Have fun playing the game!