win condition check

This commit is contained in:
Andrei Stoica 2024-12-20 12:41:49 -05:00
parent 3821c555b1
commit 9b10a34476
1 changed files with 54 additions and 1 deletions

View File

@ -91,6 +91,7 @@ class _MyHomePageState extends State<MyHomePage> {
enum TTCState { empty, x, o }
/// Board of a single game of tic tac toe
class TTCGame extends StatefulWidget {
const TTCGame({
super.key,
@ -126,11 +127,63 @@ class _TTCGameState extends State<TTCGame> {
};
});
widget.onClick?.call();
notifyWin();
break;
default:
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(const SnackBar(content: Text("Invalid Choice")));
..showSnackBar(const SnackBar(
content: Text("Invalid Choice: cell already has value")));
}
}
Iterable<TTCState> getRow(int index) => data.getRange(index, index + 3);
Iterable<TTCState> getCol(int index) => [
data[index],
data[index + 3],
data[index + 3 * 2],
];
Iterable<TTCState> getCross(int index) {
if (index == 0) {
return [data[0], data[4], data[8]];
}
return [data[3], data[4], data[6]];
}
TTCState _checkRow(Iterable<TTCState> row) => row.reduce((value, element) =>
(element == TTCState.empty || value == TTCState.empty || element != value)
? TTCState.empty
: value);
TTCState _checkBoard(Iterable<TTCState> rowValues) =>
rowValues.reduce((value, element) {
if (value != TTCState.empty) {
return value;
}
if (element != TTCState.empty) {
return element;
}
return TTCState.empty;
});
TTCState _checkWin() {
Iterable<TTCState> rows = Iterable.generate(3, (i) => _checkRow(getRow(i)));
Iterable<TTCState> cols = Iterable.generate(3, (i) => _checkRow(getCol(i)));
Iterable<TTCState> crosses =
Iterable.generate(2, (i) => _checkRow(getCross(i)));
return _checkBoard([...rows, ...cols, ...crosses]);
}
void notifyWin() {
TTCState state = _checkWin();
if (state != TTCState.empty) {
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(
SnackBar(content: Text("${state.name.toUpperCase()} wins")));
}
}