84 lines
1.9 KiB
Dart
84 lines
1.9 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'state.dart';
|
|
|
|
/// Board of a single game of tic tac toe
|
|
class TTCGame extends StatelessWidget {
|
|
const TTCGame({
|
|
super.key,
|
|
required this.turn,
|
|
required this.cellOnTapCallback,
|
|
required this.data,
|
|
this.cellTextStyle,
|
|
});
|
|
|
|
final TTCState turn;
|
|
final List<TTCState> data;
|
|
|
|
/// styling for text in cell
|
|
final TextStyle? cellTextStyle;
|
|
|
|
/// hook into end of turn cycle;
|
|
final Function cellOnTapCallback;
|
|
|
|
Border _genCellBorder(
|
|
int index, {
|
|
BorderSide borderSide = const BorderSide(),
|
|
}) {
|
|
return Border(
|
|
top: index < 3 ? BorderSide.none : borderSide,
|
|
bottom: index > 5 ? BorderSide.none : borderSide,
|
|
left: [0, 3, 6].contains(index) ? BorderSide.none : borderSide,
|
|
right: [2, 5, 8].contains(index) ? BorderSide.none : borderSide,
|
|
);
|
|
}
|
|
|
|
Widget _genCell(int index, TTCState state) => Container(
|
|
decoration: BoxDecoration(border: _genCellBorder(index)),
|
|
child: TTCCell(
|
|
state: state,
|
|
textStyle: cellTextStyle,
|
|
stateSetCallback: () {
|
|
cellOnTapCallback(index);
|
|
},
|
|
));
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
List<Widget> cells = [];
|
|
for (final (index, state) in data.indexed) {
|
|
cells.add(_genCell(index, state));
|
|
}
|
|
return GridView.count(
|
|
crossAxisCount: 3,
|
|
shrinkWrap: true,
|
|
children: cells,
|
|
);
|
|
}
|
|
}
|
|
|
|
class TTCCell extends StatelessWidget {
|
|
const TTCCell({
|
|
super.key,
|
|
required this.state,
|
|
this.stateSetCallback,
|
|
this.textStyle,
|
|
});
|
|
|
|
final TTCState state;
|
|
final VoidCallback? stateSetCallback;
|
|
final TextStyle? textStyle;
|
|
|
|
String get text => switch (state) {
|
|
TTCState.empty => "",
|
|
TTCState.x => "X",
|
|
TTCState.o => "O",
|
|
};
|
|
|
|
@override
|
|
Widget build(BuildContext context) => InkWell(
|
|
onTap: stateSetCallback,
|
|
child: Center(
|
|
child: Text(text, style: textStyle),
|
|
));
|
|
}
|