Last active
September 25, 2018 21:10
-
-
Save tth05/e370f1fbe9570ce69808418455f43d96 to your computer and use it in GitHub Desktop.
A very simple console version of tictactoe implemented in dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
var cells = List.generate(3, (_) => [0, 0, 0]); | |
var player = 1; | |
void main(List<String> arguments) { | |
printGameField(); | |
while (true) { | |
print("Player $player's turn"); | |
var input = int.parse(stdin.readLineSync()) - 1; | |
var row = (input / 3).floor(); | |
var col = (input % 3); | |
if (cells[row][col] == 1 || cells[row][col] == 2) { | |
print("That field is already taken"); | |
continue; | |
} | |
cells[row][col] = player; | |
printGameField(); | |
if (isWinningMove(col, row)) { | |
//Don't switch the players so the winner, because the winner should start the next round. | |
print("Player $player has won the game! Restarting..."); | |
cells = List.generate(3, (_) => [0, 0, 0]); | |
} else { | |
if (isTie()) { | |
print("It's a tie! Restarting..."); | |
cells = List.generate(3, (_) => [0, 0, 0]); | |
} | |
player = player == 1 ? 2 : 1; | |
} | |
} | |
} | |
bool isTie() { | |
var tie = true; | |
cells.forEach((r) => r.forEach((e) => e == 0 ? tie = false : {})); | |
return tie; | |
} | |
bool isWinningMove(int col, int row) { | |
return (cells[row][0] == player && cells[row][1] == player && cells[row][2] == player) || | |
(cells[0][col] == player && cells[1][col] == player && cells[2][col] == player) || | |
(row == col && cells[0][0] == player && cells[1][1] == player && cells[2][2] == player) || | |
(row + col == 2 && cells[0][2] == player && cells[1][1] == player && cells[2][0] == player); | |
} | |
void printGameField() { | |
cells.forEach((r) { | |
var line = ""; | |
r.forEach((f) => line += "$f "); | |
print(line); | |
}); | |
print(" "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment