game_board.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:fast_gbk/fast_gbk.dart';
  4. import 'package:file_picker/file_picker.dart';
  5. import 'package:shirne_dialog/shirne_dialog.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter/services.dart';
  9. import 'package:universal_html/html.dart' as html;
  10. import 'global.dart';
  11. import 'pages/setting_page.dart';
  12. import 'components/game_bottom_bar.dart';
  13. import 'models/play_mode.dart';
  14. import 'pages/home_page.dart';
  15. import 'models/game_manager.dart';
  16. import 'components/play.dart';
  17. import 'components/edit_fen.dart';
  18. /// 游戏页面
  19. class GameBoard extends StatefulWidget {
  20. const GameBoard({Key? key}) : super(key: key);
  21. @override
  22. State<GameBoard> createState() => _GameBoardState();
  23. }
  24. class _GameBoardState extends State<GameBoard> {
  25. GameManager gamer = GameManager.instance;
  26. PlayMode? mode;
  27. @override
  28. void initState() {
  29. super.initState();
  30. }
  31. Widget selectMode() {
  32. final maxHeight = MediaQuery.of(context).size.height;
  33. return Center(
  34. child: SizedBox(
  35. height: maxHeight * 0.6,
  36. child: Column(
  37. mainAxisAlignment: MainAxisAlignment.spaceAround,
  38. children: [
  39. ElevatedButton.icon(
  40. onPressed: () {
  41. setState(() {
  42. mode = PlayMode.modeRobot;
  43. });
  44. },
  45. icon: const Icon(Icons.android),
  46. label: Text(context.l10n.modeRobot),
  47. ),
  48. ElevatedButton.icon(
  49. onPressed: () {
  50. MyDialog.toast(
  51. context.l10n.featureNotAvailable,
  52. iconType: IconType.error,
  53. );
  54. },
  55. icon: const Icon(Icons.wifi),
  56. label: Text(context.l10n.modeOnline),
  57. ),
  58. ElevatedButton.icon(
  59. onPressed: () {
  60. setState(() {
  61. mode = PlayMode.modeFree;
  62. });
  63. },
  64. icon: const Icon(Icons.map),
  65. label: Text(context.l10n.modeFree),
  66. ),
  67. if (kIsWeb)
  68. TextButton(
  69. onPressed: () {
  70. var link =
  71. html.window.document.getElementById('download-apk');
  72. if (link == null) {
  73. link = html.window.document.createElement('a');
  74. link.style.display = 'none';
  75. link.setAttribute('id', 'download-apk');
  76. link.setAttribute('target', '_blank');
  77. link.setAttribute('href', 'chinese-chess.apk');
  78. html.window.document
  79. .getElementsByTagName('body')[0]
  80. .append(link);
  81. }
  82. link.click();
  83. },
  84. child: const Text('Download APK'),
  85. ),
  86. ],
  87. ),
  88. ),
  89. );
  90. }
  91. @override
  92. Widget build(BuildContext context) {
  93. return Scaffold(
  94. appBar: AppBar(
  95. title: Text(context.l10n.appTitle),
  96. leading: Builder(
  97. builder: (BuildContext context) {
  98. return IconButton(
  99. icon: const Icon(Icons.menu),
  100. tooltip: context.l10n.openMenu,
  101. onPressed: () {
  102. Scaffold.of(context).openDrawer();
  103. },
  104. );
  105. },
  106. ),
  107. actions: mode == null
  108. ? null
  109. : [
  110. IconButton(
  111. icon: const Icon(Icons.swap_vert),
  112. tooltip: context.l10n.flipBoard,
  113. onPressed: () {
  114. gamer.flip();
  115. },
  116. ),
  117. IconButton(
  118. icon: const Icon(Icons.copy),
  119. tooltip: context.l10n.copyCode,
  120. onPressed: () {
  121. copyFen();
  122. },
  123. ),
  124. IconButton(
  125. icon: const Icon(Icons.airplay),
  126. tooltip: context.l10n.parseCode,
  127. onPressed: () {
  128. applyFen();
  129. },
  130. ),
  131. IconButton(
  132. icon: const Icon(Icons.airplay),
  133. tooltip: context.l10n.editCode,
  134. onPressed: () {
  135. editFen();
  136. },
  137. ),
  138. /*IconButton(icon: Icon(Icons.minimize), onPressed: (){
  139. }),
  140. IconButton(icon: Icon(Icons.zoom_out_map), onPressed: (){
  141. }),
  142. IconButton(icon: Icon(Icons.clear), color: Colors.red, onPressed: (){
  143. this._showDialog(context.l10n.exit_now,
  144. [
  145. TextButton(
  146. onPressed: (){
  147. Navigator.of(context).pop();
  148. },
  149. child: Text(context.l10n.dont_exit),
  150. ),
  151. TextButton(
  152. onPressed: (){
  153. if(!kIsWeb){
  154. Isolate.current.pause();
  155. exit(0);
  156. }
  157. },
  158. child: Text(context.l10n.yes_exit,style: TextStyle(color:Colors.red)),
  159. )
  160. ]
  161. );
  162. })*/
  163. ],
  164. ),
  165. drawer: Drawer(
  166. semanticLabel: context.l10n.menu,
  167. child: ListView(
  168. padding: EdgeInsets.zero,
  169. children: [
  170. DrawerHeader(
  171. decoration: const BoxDecoration(
  172. color: Colors.blue,
  173. ),
  174. child: Center(
  175. child: Column(
  176. children: [
  177. Image.asset(
  178. 'assets/images/logo.png',
  179. width: 100,
  180. height: 100,
  181. ),
  182. Text(
  183. context.l10n.appTitle,
  184. style: const TextStyle(
  185. color: Colors.white,
  186. fontSize: 24,
  187. ),
  188. ),
  189. ],
  190. ),
  191. ),
  192. ),
  193. ListTile(
  194. leading: const Icon(Icons.add),
  195. title: Text(context.l10n.newGame),
  196. onTap: () {
  197. Navigator.pop(context);
  198. setState(() {
  199. if (mode == null) {
  200. setState(() {
  201. mode = PlayMode.modeFree;
  202. });
  203. }
  204. gamer.newGame();
  205. });
  206. },
  207. ),
  208. ListTile(
  209. leading: const Icon(Icons.description),
  210. title: Text(context.l10n.loadManual),
  211. onTap: () {
  212. Navigator.pop(context);
  213. if (mode == null) {
  214. setState(() {
  215. mode = PlayMode.modeFree;
  216. });
  217. }
  218. loadFile();
  219. },
  220. ),
  221. ListTile(
  222. leading: const Icon(Icons.save),
  223. title: Text(context.l10n.saveManual),
  224. onTap: () {
  225. Navigator.pop(context);
  226. saveManual();
  227. },
  228. ),
  229. ListTile(
  230. leading: const Icon(Icons.copy),
  231. title: Text(context.l10n.copyCode),
  232. onTap: () {
  233. Navigator.pop(context);
  234. copyFen();
  235. },
  236. ),
  237. ListTile(
  238. leading: const Icon(Icons.settings),
  239. title: Text(context.l10n.setting),
  240. onTap: () {
  241. Navigator.pop(context);
  242. Navigator.push(
  243. context,
  244. MaterialPageRoute(
  245. builder: (BuildContext context) => const SettingPage(),
  246. ),
  247. );
  248. },
  249. ),
  250. ],
  251. ),
  252. ),
  253. body: SafeArea(
  254. child: Center(
  255. child: mode == null ? selectMode() : PlayPage(mode: mode!),
  256. ),
  257. ),
  258. bottomNavigationBar:
  259. (mode == null || MediaQuery.of(context).size.width >= 980)
  260. ? null
  261. : GameBottomBar(mode!),
  262. );
  263. }
  264. void editFen() {
  265. Navigator.of(context).push<String>(
  266. MaterialPageRoute(
  267. builder: (BuildContext context) {
  268. return HomePage(child: EditFen(fen: gamer.fenStr));
  269. },
  270. ),
  271. ).then((fenStr) {
  272. if (fenStr != null && fenStr.isNotEmpty) {
  273. gamer.newGame(fenStr);
  274. }
  275. });
  276. }
  277. Future<void> applyFen() async {
  278. final l10n = context.l10n;
  279. ClipboardData? cData = await Clipboard.getData(Clipboard.kTextPlain);
  280. String fenStr = cData?.text ?? '';
  281. TextEditingController filenameController =
  282. TextEditingController(text: fenStr);
  283. filenameController.addListener(() {
  284. fenStr = filenameController.text;
  285. });
  286. final confirmed = await MyDialog.confirm(
  287. TextField(
  288. controller: filenameController,
  289. ),
  290. buttonText: l10n.apply,
  291. title: l10n.situationCode,
  292. );
  293. if (confirmed ?? false) {
  294. if (RegExp(
  295. r'^[abcnrkpABCNRKP\d]{1,9}(?:/[abcnrkpABCNRKP\d]{1,9}){9}(\s[wb]\s-\s-\s\d+\s\d+)?$',
  296. ).hasMatch(fenStr)) {
  297. gamer.newGame(fenStr);
  298. } else {
  299. MyDialog.alert(l10n.invalidCode);
  300. }
  301. }
  302. }
  303. void copyFen() {
  304. Clipboard.setData(ClipboardData(text: gamer.fenStr));
  305. MyDialog.alert(context.l10n.copySuccess);
  306. }
  307. Future<void> saveManual() async {
  308. String content = gamer.manual.export();
  309. String filename = '${DateTime.now().millisecondsSinceEpoch ~/ 1000}.pgn';
  310. if (kIsWeb) {
  311. await _saveManualWeb(content, filename);
  312. } else if (Platform.isAndroid || Platform.isIOS) {
  313. await _saveManualNative(content, filename);
  314. }
  315. }
  316. Future<void> _saveManualNative(String content, String filename) async {
  317. final result = await FilePicker.platform.saveFile(
  318. dialogTitle: 'Save pgn file',
  319. fileName: filename,
  320. allowedExtensions: ['pgn'],
  321. );
  322. if (context.mounted && result != null) {
  323. List<int> fData = gbk.encode(content);
  324. await File('$result/$filename').writeAsBytes(fData);
  325. MyDialog.toast(context.l10n.saveSuccess);
  326. }
  327. }
  328. Future<void> _saveManualWeb(String content, String filename) async {
  329. List<int> fData = gbk.encode(content);
  330. var link = html.window.document.createElement('a');
  331. link.setAttribute('download', filename);
  332. link.style.display = 'none';
  333. link.setAttribute('href', Uri.dataFromBytes(fData).toString());
  334. html.window.document.getElementsByTagName('body')[0].append(link);
  335. link.click();
  336. await Future<void>.delayed(const Duration(seconds: 10));
  337. link.remove();
  338. }
  339. Future<void> loadFile() async {
  340. FilePickerResult? result = await FilePicker.platform.pickFiles(
  341. type: FileType.custom,
  342. allowedExtensions: ['pgn', 'PGN'],
  343. withData: true,
  344. );
  345. if (result != null && result.count == 1) {
  346. String content = gbk.decode(result.files.single.bytes!);
  347. if (gamer.isStop) {
  348. gamer.newGame();
  349. }
  350. gamer.loadPGN(content);
  351. } else {
  352. // User canceled the picker
  353. }
  354. }
  355. }