Last active
September 8, 2023 18:02
-
-
Save fisherds/419ae6cbc7fe317197f3158b1382fbb7 to your computer and use it in GitHub Desktop.
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
// One possible solution | |
enum TicTacToeMark { none, x, o } | |
enum TicTacToeState { xTurn, oTurn, xWon, oWon, tie } | |
class TicTacToeGame { | |
var board = List<TicTacToeMark>.filled(9, TicTacToeMark.none); | |
var state = TicTacToeState.xTurn; | |
void pressedSquare(int index) { | |
if (index < 0 || index >= board.length) { | |
return; | |
} | |
if (board[index] != TicTacToeMark.none) { | |
return; | |
} | |
if (state == TicTacToeState.xTurn) { | |
board[index] = TicTacToeMark.x; | |
state = TicTacToeState.oTurn; | |
checkForGameOver(); | |
} else if (state == TicTacToeState.oTurn) { | |
board[index] = TicTacToeMark.o; | |
state = TicTacToeState.xTurn; | |
checkForGameOver(); | |
} | |
} | |
List<String> get linesOf3 { | |
final lines = <String>[]; | |
final b = boardString; | |
lines.add(b[0] + b[1] + b[2]); | |
lines.add(b[3] + b[4] + b[5]); | |
lines.add(b[6] + b[7] + b[8]); | |
lines.add(b[0] + b[3] + b[6]); | |
lines.add(b[1] + b[4] + b[7]); | |
lines.add(b[2] + b[5] + b[8]); | |
lines.add(b[0] + b[4] + b[8]); | |
lines.add(b[2] + b[4] + b[6]); | |
return lines; | |
} | |
void checkForGameOver() { | |
if (!board.contains(TicTacToeMark.none)) { | |
state = TicTacToeState.tie; | |
} | |
for (final line in linesOf3) { | |
if (line == "XXX") { | |
state = TicTacToeState.xWon; | |
} else if (line == "OOO") { | |
state = TicTacToeState.oWon; | |
} | |
} | |
} | |
String get stateString => state.toString().split('.').last; | |
String get boardString { | |
var s = ""; | |
for (final mark in board) { | |
s += | |
mark == TicTacToeMark.x ? "X" : (mark == TicTacToeMark.o ? "O" : "-"); | |
} | |
return s; | |
} | |
@override | |
String toString() { | |
return "$stateString $boardString"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment