-
Notifications
You must be signed in to change notification settings - Fork 12
/
game_page.dart
127 lines (103 loc) · 2.87 KB
/
game_page.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import 'package:flutter/material.dart';
import 'package:flutter_tic_tac_toe/ai/ai.dart';
import 'package:flutter_tic_tac_toe/ui/field.dart';
import 'package:flutter_tic_tac_toe/ui/game_presenter.dart';
class GamePage extends StatefulWidget {
final String title;
GamePage(this.title);
@override
GamePageState createState() => GamePageState();
}
class GamePageState extends State<GamePage> {
List<int> board;
int _currentPlayer;
GamePresenter _presenter;
GamePageState() {
this._presenter = GamePresenter(_movePlayed, _onGameEnd);
}
void _onGameEnd(int winner) {
var title = "Game over!";
var content = "You lose :(";
switch(winner) {
case Ai.HUMAN: // will never happen :)
title = "Congratulations!";
content = "You managed to beat an unbeatable AI!";
break;
case Ai.AI_PLAYER:
title = "Game Over!";
content = "You lose :(";
break;
default:
title = "Draw!";
content = "No winners here.";
}
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
new FlatButton(
onPressed: () {
setState(() {
reinitialize();
Navigator.of(context).pop();
});
},
child: Text("Restart"))
],
);
});
}
void _movePlayed(int idx) {
setState(() {
board[idx] = _currentPlayer;
if (_currentPlayer == Ai.HUMAN) {
// switch to AI player
_currentPlayer = Ai.AI_PLAYER;
_presenter.onHumanPlayed(board);
} else {
_currentPlayer = Ai.HUMAN;
}
});
}
String getSymbolForIdx(int idx) {
return Ai.SYMBOLS[board[idx]];
}
@override
void initState() {
super.initState();
reinitialize();
}
void reinitialize() {
_currentPlayer = Ai.HUMAN;
// generate the initial board
board = List.generate(9, (idx) => 0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(60),
child: Text("You are playing as X", style: TextStyle(fontSize: 25),),
),
Expanded(
child: GridView.count(
crossAxisCount: 3,
// generate the widgets that will display the board
children: List.generate(9, (idx) {
return Field(idx: idx, onTap: _movePlayed, playerSymbol: getSymbolForIdx(idx));
}),
),
),
],
),
);
}
}