From 9b10a34476e1fee280f05b0a15befdc2c4625d27 Mon Sep 17 00:00:00 2001 From: Andrei Stoica Date: Fri, 20 Dec 2024 12:41:49 -0500 Subject: [PATCH] win condition check --- lib/main.dart | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/lib/main.dart b/lib/main.dart index ad06f84..9f6d1a0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -91,6 +91,7 @@ class _MyHomePageState extends State { 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 { }; }); 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 getRow(int index) => data.getRange(index, index + 3); + Iterable getCol(int index) => [ + data[index], + data[index + 3], + data[index + 3 * 2], + ]; + Iterable getCross(int index) { + if (index == 0) { + return [data[0], data[4], data[8]]; + } + return [data[3], data[4], data[6]]; + } + + TTCState _checkRow(Iterable row) => row.reduce((value, element) => + (element == TTCState.empty || value == TTCState.empty || element != value) + ? TTCState.empty + : value); + + TTCState _checkBoard(Iterable rowValues) => + rowValues.reduce((value, element) { + if (value != TTCState.empty) { + return value; + } + if (element != TTCState.empty) { + return element; + } + + return TTCState.empty; + }); + + TTCState _checkWin() { + Iterable rows = Iterable.generate(3, (i) => _checkRow(getRow(i))); + Iterable cols = Iterable.generate(3, (i) => _checkRow(getCol(i))); + Iterable 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"))); } }