/
main.dart
297 lines (270 loc) · 9.1 KB
/
main.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
* Copyright 2023 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:tflite_flutter_plugin_rl_example/game_agent.dart';
void main() {
runApp(const PlaneStrike());
}
class PlaneStrike extends StatefulWidget {
const PlaneStrike({super.key});
// This widget is the root of your application.
@override
_PlaneStrikeState createState() => _PlaneStrikeState();
}
class _PlaneStrikeState extends State<PlaneStrike> {
// The board should be in square shape so we only need one size
final _boardSize = 8;
// Number of pieces needed to form a 'plane'
final _planePieceCount = 8;
late int _agentHits;
late int _playerHits;
late PolicyGradientAgent _policyGradientAgent;
late List<List<double>> _agentBoardState;
late List<List<double>> _agentHiddenBoardState;
late List<List<double>> _playerBoardState;
late List<List<double>> _playerHiddenBoardState;
@override
void initState() {
super.initState();
_resetGame();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TFLite Flutter Reference App',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: _buildGameBody(),
);
}
List<List<double>> _fillWithZeros() =>
List.generate(_boardSize, (_) => List.filled(_boardSize, 0.0));
void _resetGame() {
_agentHits = 0;
_playerHits = 0;
_policyGradientAgent = PolicyGradientAgent();
// We keep track of 4 sets of boards (2 for each player):
// - *BoardState is the visible board that tracks the game progress
// - *HiddentBoardState is the secret board that records the true plane location
_agentBoardState = _fillWithZeros();
_agentHiddenBoardState = _setBoardState();
_playerBoardState = _fillWithZeros();
_playerHiddenBoardState = _setBoardState();
}
List<List<double>> _setBoardState() {
var hiddenBoardState = _fillWithZeros();
// Place the plane on the board
// First, decide the plane's orientation
// 0: heading right
// 1: heading up
// 2: heading left
// 3: heading down
var rng = Random();
int planeOrientation = rng.nextInt(4);
// Figrue out the location of plane core as the '*' below
// | | | | | ---
// |-*- -*- -*-| |
// | | | | | -*-
// --- |
int planeCoreX, planeCoreY;
switch (planeOrientation) {
case 0:
planeCoreX = rng.nextInt(_boardSize - 2) + 1;
planeCoreY = rng.nextInt(_boardSize - 3) + 2;
// Populate the tail
hiddenBoardState[planeCoreX][planeCoreY - 2] = 1;
hiddenBoardState[planeCoreX - 1][planeCoreY - 2] = 1;
hiddenBoardState[planeCoreX + 1][planeCoreY - 2] = 1;
break;
case 1:
planeCoreX = rng.nextInt(_boardSize - 3) + 1;
planeCoreY = rng.nextInt(_boardSize - 2) + 1;
// Populate the tail
hiddenBoardState[planeCoreX + 2][planeCoreY] = 1;
hiddenBoardState[planeCoreX + 2][planeCoreY + 1] = 1;
hiddenBoardState[planeCoreX + 2][planeCoreY - 1] = 1;
break;
case 2:
planeCoreX = rng.nextInt(_boardSize - 2) + 1;
planeCoreY = rng.nextInt(_boardSize - 3) + 1;
// Populate the tail
hiddenBoardState[planeCoreX][planeCoreY + 2] = 1;
hiddenBoardState[planeCoreX - 1][planeCoreY + 2] = 1;
hiddenBoardState[planeCoreX + 1][planeCoreY + 2] = 1;
break;
default:
planeCoreX = rng.nextInt(_boardSize - 3) + 2;
planeCoreY = rng.nextInt(_boardSize - 2) + 1;
// Populate the tail
hiddenBoardState[planeCoreX - 2][planeCoreY] = 1;
hiddenBoardState[planeCoreX - 2][planeCoreY + 1] = 1;
hiddenBoardState[planeCoreX - 2][planeCoreY - 1] = 1;
}
// Populate the 'cross' in the plane
hiddenBoardState[planeCoreX][planeCoreY] = 1;
hiddenBoardState[planeCoreX + 1][planeCoreY] = 1;
hiddenBoardState[planeCoreX - 1][planeCoreY] = 1;
hiddenBoardState[planeCoreX][planeCoreY + 1] = 1;
hiddenBoardState[planeCoreX][planeCoreY - 1] = 1;
return hiddenBoardState;
}
Widget _buildGameBody() {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: const Text('Plane Strike game based on TFLite'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_gridView(_buildAgentBoardItems),
Text(
"Agent's board (hits: $_playerHits)",
style: const TextStyle(
fontSize: 18,
color: Colors.blue,
fontWeight: FontWeight.bold),
),
const Divider(
height: 20,
thickness: 5,
indent: 20,
endIndent: 20,
),
Text(
"Your board (hits: $_agentHits)",
style: const TextStyle(
fontSize: 18,
color: Colors.purple,
fontWeight: FontWeight.bold),
),
_gridView(_buildPlayerBoardItems),
ElevatedButton(
onPressed: () => setState(_resetGame),
child: const Text("Reset game"),
),
],
),
),
);
}
Widget _gridView(
Widget Function(BuildContext context, int x, int y) itemBuilder) {
return Builder(
builder: (context) => Container(
width: 265,
height: 265,
decoration:
BoxDecoration(border: Border.all(color: Colors.black, width: 2.0)),
child: GridView.count(
crossAxisCount: _boardSize,
children: [
for (int i = 0; i < _boardSize; i++)
for (int j = 0; j < _boardSize; j++) itemBuilder(context, i, j)
],
),
),
);
}
Widget _buildAgentBoardItems(BuildContext context, int x, int y) {
return GestureDetector(
onTap: () => _gridItemTapped(context, x, y),
child: _buildGridItem(x, y, 'agent'),
);
}
Widget _buildPlayerBoardItems(BuildContext context, int x, int y) =>
_buildGridItem(x, y);
Widget _buildGridItem(int x, int y, [String agentOrPlayer = 'player']) {
var boardState = _agentBoardState;
var hiddenBoardState = _agentHiddenBoardState;
if (agentOrPlayer == 'player') {
boardState = _playerBoardState;
hiddenBoardState = _playerHiddenBoardState;
}
Color gridItemColor;
switch ((boardState[x][y]).toInt()) {
// hit
case 1:
gridItemColor = Colors.red;
break;
// miss
case -1:
gridItemColor = Colors.yellow;
break;
default:
if (hiddenBoardState[x][y] == 1 && agentOrPlayer == 'player') {
gridItemColor = Colors.green;
} else {
gridItemColor = Colors.white;
}
}
return Container(
decoration: BoxDecoration(
color: gridItemColor,
border: Border.all(color: Colors.black, width: 0.5),
),
);
}
bool _takeAction(int x, int y, List<List<double>> boardList,
List<List<double>> targetBoardList) {
if (targetBoardList[x][y].toInt() == 1) {
// Non-repeat move
if (boardList[x][y].toInt() == 0) {
boardList[x][y] = 1;
return true;
}
} else {
boardList[x][y] = -1;
}
return false;
}
void _gridItemTapped(context, x, y) {
if (_agentBoardState[x][y] != 0) {
return;
}
setState(() {
if (_takeAction(x, y, _agentBoardState, _agentHiddenBoardState)) {
_playerHits++;
}
// Agent takes action
int agentAction = _policyGradientAgent.predict(_playerBoardState);
if (_takeAction(agentAction ~/ _boardSize, agentAction % _boardSize,
_playerBoardState, _playerHiddenBoardState)) {
_agentHits++;
}
});
String userPrompt = '';
if (_playerHits == _planePieceCount && _agentHits == _planePieceCount) {
userPrompt = "Draw game!";
} else if (_agentHits == _planePieceCount) {
userPrompt = "Agent wins!";
} else if (_playerHits == _planePieceCount) {
userPrompt = "You win!";
}
if (userPrompt != '') {
Future.delayed(const Duration(seconds: 2), () => setState(_resetGame));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(userPrompt),
duration: const Duration(seconds: 2),
));
}
}
}