Finished beta

This commit is contained in:
Linloir 2022-03-06 16:55:46 +08:00
parent 9722abaeeb
commit 3f4338174b
8 changed files with 16353 additions and 94 deletions

15925
assets/txt/words_alpha.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
/* /*
* @Author : Linloir * @Author : Linloir
* @Date : 2022-03-05 20:56:05 * @Date : 2022-03-05 20:56:05
* @LastEditTime : 2022-03-06 12:14:57 * @LastEditTime : 2022-03-06 16:10:50
* @Description : The display widget of the wordle game * @Description : The display widget of the wordle game
*/ */
@ -22,20 +22,49 @@ class _WordleDisplayWidgetState extends State<WordleDisplayWidget> with TickerPr
int r = 0; int r = 0;
int c = 0; int c = 0;
bool onAnimation = false; bool onAnimation = false;
bool acceptInput = true;
late final List<List<Map<String, dynamic>>> inputs; late final List<List<Map<String, dynamic>>> inputs;
void _validationAnimation(List<int> validation) async { void _validationAnimation(List<int> validation) async {
onAnimation = true; onAnimation = true;
bool result = true;
for(int i = 0; i < 5; i++) { for(int i = 0; i < 5; i++) {
setState((){ setState((){
inputs[r][i]["State"] = validation[i]; inputs[r][i]["State"] = validation[i];
print('Set $r, $i to state ${validation[i]}');
}); });
if(validation[i] != 1) {
result = false;
}
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
} }
mainBus.emit(event: "AnimationStops", args: []);
onAnimation = false; onAnimation = false;
r++; r++;
c = 0; c = 0;
if(r == 6 || result == true) {
mainBus.emit(event: "Result", args: result);
acceptInput = false;
}
}
void _onValidation(dynamic args) {
List<int> validation = args;
_validationAnimation(validation);
}
void _onNewGame(dynamic args) {
setState(() {
r = 0;
c = 0;
onAnimation = false;
acceptInput = true;
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 5; j++) {
inputs[i][j]["Letter"] = "";
inputs[i][j]["State"] = 0;
}
}
});
} }
@override @override
@ -56,15 +85,15 @@ class _WordleDisplayWidgetState extends State<WordleDisplayWidget> with TickerPr
} }
] ]
]; ];
mainBus.onBus( mainBus.onBus(event: "Attempt", onEvent: _onValidation,);
event: "Attempt", mainBus.onBus(event: "NewGame", onEvent: _onNewGame);
onEvent: (args) { }
print('Heard');
List<int> validation = args; @override
print(validation); void dispose() {
_validationAnimation(validation); mainBus.offBus(event: "Attempt", callBack: _onValidation);
} mainBus.offBus(event: "NewGame", callBack: _onNewGame);
); super.dispose();
} }
@override @override
@ -121,16 +150,16 @@ class _WordleDisplayWidgetState extends State<WordleDisplayWidget> with TickerPr
decoration: BoxDecoration( decoration: BoxDecoration(
border: Border.all( border: Border.all(
color: inputs[i][j]["State"] == 1 ? Colors.green[600]! : color: inputs[i][j]["State"] == 1 ? Colors.green[600]! :
inputs[i][j]["State"] == 2 ? Colors.yellow[800]! : inputs[i][j]["State"] == 2 ? Colors.yellow[800]! :
inputs[i][j]["State"] == 3 ? Colors.grey[850]! : inputs[i][j]["State"] == 3 ? Colors.grey[850]! :
inputs[i][j]["State"] == -1 ? Colors.grey[700]! : inputs[i][j]["State"] == -1 ? Colors.grey[700]! :
Colors.grey[400]!, Colors.grey[400]!,
width: 3.0, width: 3.0,
), ),
color: inputs[i][j]["State"] == 1 ? Colors.green[600]! : color: inputs[i][j]["State"] == 1 ? Colors.green[600]! :
inputs[i][j]["State"] == 2 ? Colors.yellow[800]! : inputs[i][j]["State"] == 2 ? Colors.yellow[800]! :
inputs[i][j]["State"] == -1 ? Colors.grey[700]! : inputs[i][j]["State"] == -1 ? Colors.grey[700]! :
Colors.white, Colors.white,
), ),
child: Center( child: Center(
child: Text( child: Text(
@ -154,13 +183,12 @@ class _WordleDisplayWidgetState extends State<WordleDisplayWidget> with TickerPr
], ],
), ),
), ),
InputPannelWidget(), const InputPannelWidget(),
], ],
), ),
onNotification: (noti) { onNotification: (noti) {
print('Get');
if(noti.type == InputType.singleCharacter) { if(noti.type == InputType.singleCharacter) {
if(r < 6 && c < 5 && !onAnimation) { if(r < 6 && c < 5 && !onAnimation && acceptInput) {
setState((){ setState((){
inputs[r][c]["Letter"] = noti.msg; inputs[r][c]["Letter"] = noti.msg;
inputs[r][c]["State"] = 3; inputs[r][c]["State"] = 3;
@ -170,6 +198,15 @@ class _WordleDisplayWidgetState extends State<WordleDisplayWidget> with TickerPr
}); });
} }
} }
else if(noti.type == InputType.backSpace) {
if(c > 0 && !onAnimation) {
setState(() {
inputs[r][c - 1]["Letter"] = "";
inputs[r][c - 1]["State"] = 0;
c--;
});
}
}
return false; return false;
}, },
); );

34
lib/generator.dart Normal file
View File

@ -0,0 +1,34 @@
/*
* @Author : Linloir
* @Date : 2022-03-06 15:03:57
* @LastEditTime : 2022-03-06 16:16:14
* @Description : Word generator
*/
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'dart:math';
abstract class Words {
static Set<String> dataBase = <String>{};
static Future<void> importWordsDatabase() async {
var data = await rootBundle.loadString('assets/txt/words_alpha.txt');
dataBase.addAll(LineSplitter.split(data));
}
static Future<String> generateWord() async{
int bound = dataBase.length;
if(bound == 0) {
await Words.importWordsDatabase();
bound = dataBase.length;
}
var rng = Random();
return dataBase.elementAt(rng.nextInt(bound));
}
static bool isWordValidate(String word) {
return dataBase.lookup(word.toLowerCase()) != null;
}
}

View File

@ -1,7 +1,7 @@
/* /*
* @Author : Linloir * @Author : Linloir
* @Date : 2022-03-05 20:55:53 * @Date : 2022-03-05 20:55:53
* @LastEditTime : 2022-03-06 12:17:55 * @LastEditTime : 2022-03-06 16:09:08
* @Description : Input pannel class * @Description : Input pannel class
*/ */
@ -17,45 +17,225 @@ class InputPannelWidget extends StatefulWidget {
} }
class _InputPannelWidgetState extends State<InputPannelWidget> { class _InputPannelWidgetState extends State<InputPannelWidget> {
final _keyState = <String, int>{};
final List<List<String>> _keyPos = List<List<String>>.unmodifiable([
['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'],
['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'],
['Z', 'X', 'C', 'V', 'B', 'N', 'M']
]);
Map<String, int> _cache = {};
void _onLetterValidation(dynamic args) {
_cache = args as Map<String, int>;
}
void _onAnimationStops(dynamic args) {
_cache.forEach((key, value) {
setState(() {
_keyState[key] = value;
});
});
}
void _onNewGame(dynamic args) {
setState(() {
var aCode = 'A'.codeUnitAt(0);
var zCode = 'Z'.codeUnitAt(0);
var alphabet = List<String>.generate(
zCode - aCode + 1,
(index) => String.fromCharCode(aCode + index),
);
for(String c in alphabet) {
_keyState[c] ??= 0;
_keyState[c] = 0;
}
});
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
var aCode = 'A'.codeUnitAt(0);
var zCode = 'Z'.codeUnitAt(0);
var alphabet = List<String>.generate(
zCode - aCode + 1,
(index) => String.fromCharCode(aCode + index),
);
for(String c in alphabet) {
_keyState[c] ??= 0;
_keyState[c] = 0;
}
mainBus.onBus(event: "Validation", onEvent: _onLetterValidation);
mainBus.onBus(event: "AnimationStops", onEvent: _onAnimationStops);
mainBus.onBus(event: "NewGame", onEvent: _onNewGame);
}
@override
void dispose() {
mainBus.offBus(event: "Validation", callBack: _onLetterValidation);
mainBus.offBus(event: "AnimationStops", callBack: _onAnimationStops);
mainBus.offBus(event: "NewGame", callBack: _onNewGame);
super.dispose();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Row( return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
ElevatedButton( Row(
child: const Text('A'), mainAxisAlignment: MainAxisAlignment.center,
onPressed: () { mainAxisSize: MainAxisSize.max,
const InputNotification(type: InputType.singleCharacter, msg: "A").dispatch(context); children: [
}, for(int i = 0; i < 10; i++)
Padding(
padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
child: SizedBox(
width: 50.0,
height: 80.0,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))),
backgroundColor: MaterialStateProperty.all<Color?>(
_keyState[_keyPos[0][i]]! == 0 ? Colors.grey[400] :
_keyState[_keyPos[0][i]]! == 1 ? Colors.green[600] :
_keyState[_keyPos[0][i]]! == 2 ? Colors.orange[600] :
Colors.grey[850]
),
),
child: Center(
child: Text(
_keyPos[0][i],
style: TextStyle (
fontSize: 18,
fontWeight: FontWeight.bold,
color: _keyState[_keyPos[0][i]]! == 0 ? Colors.grey[850] : Colors.white,
),
),
),
onPressed: () {
InputNotification(type: InputType.singleCharacter, msg: _keyPos[0][i]).dispatch(context);
},
)
),
)
],
), ),
ElevatedButton( Row(
child: const Text('W'), mainAxisAlignment: MainAxisAlignment.center,
onPressed: () { mainAxisSize: MainAxisSize.max,
const InputNotification(type: InputType.singleCharacter, msg: "W").dispatch(context); children: [
}, for(int i = 0; i < 9; i++)
Padding(
padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
child: SizedBox(
width: 50.0,
height: 80.0,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))),
backgroundColor: MaterialStateProperty.all<Color?>(
_keyState[_keyPos[1][i]]! == 0 ? Colors.grey[400] :
_keyState[_keyPos[1][i]]! == 1 ? Colors.green[600] :
_keyState[_keyPos[1][i]]! == 2 ? Colors.orange[600] :
Colors.grey[850]
),
),
child: Center(
child: Text(
_keyPos[1][i],
style: TextStyle (
fontSize: 18,
fontWeight: FontWeight.bold,
color: _keyState[_keyPos[1][i]]! == 0 ? Colors.grey[850] : Colors.white,
),
),
),
onPressed: () {
InputNotification(type: InputType.singleCharacter, msg: _keyPos[1][i]).dispatch(context);
},
)
),
),
Padding(
padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
child: SizedBox(
width: 110,
height: 80.0,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))),
backgroundColor: MaterialStateProperty.all<Color?>(Colors.grey[700]),
),
child: const Icon(
Icons.backspace_rounded,
color: Colors.white,
),
onPressed: () {
const InputNotification(type: InputType.backSpace, msg: "").dispatch(context);
},
),
),
),
],
), ),
ElevatedButton( Row(
child: const Text('O'), mainAxisAlignment: MainAxisAlignment.center,
onPressed: () { mainAxisSize: MainAxisSize.max,
const InputNotification(type: InputType.singleCharacter, msg: "O").dispatch(context); children: [
}, for(int i = 0; i < 7; i++)
), Padding(
ElevatedButton( padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
child: const Text('R'), child: SizedBox(
onPressed: () { width: 50.0,
const InputNotification(type: InputType.singleCharacter, msg: "R").dispatch(context); height: 80.0,
}, child: ElevatedButton(
), style: ButtonStyle(
ElevatedButton( shape: MaterialStateProperty.all<OutlinedBorder?>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))),
child: const Text('Submit'), backgroundColor: MaterialStateProperty.all<Color?>(
onPressed: () { _keyState[_keyPos[2][i]]! == 0 ? Colors.grey[400] :
const InputNotification(type: InputType.inputConfirmation, msg: "").dispatch(context); _keyState[_keyPos[2][i]]! == 1 ? Colors.green[600] :
}, _keyState[_keyPos[2][i]]! == 2 ? Colors.orange[600] :
Colors.grey[850]
),
),
child: Center(
child: Text(
_keyPos[2][i],
style: TextStyle (
fontSize: 18,
fontWeight: FontWeight.bold,
color: _keyState[_keyPos[2][i]]! == 0 ? Colors.grey[850] : Colors.white,
),
),
),
onPressed: () {
InputNotification(type: InputType.singleCharacter, msg: _keyPos[2][i]).dispatch(context);
},
)
),
),
Padding(
padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 5.0),
child: SizedBox(
width: 170,
height: 80.0,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all<OutlinedBorder?>(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0))),
backgroundColor: MaterialStateProperty.all<Color?>(Colors.green[600]),
),
child: const Icon(
Icons.keyboard_return_rounded,
color: Colors.white,
),
onPressed: () {
const InputNotification(type: InputType.inputConfirmation, msg: "").dispatch(context);
},
),
),
)
],
), ),
], ],
); );

View File

@ -1,11 +1,12 @@
/* /*
* @Author : Linloir * @Author : Linloir
* @Date : 2022-03-05 20:21:34 * @Date : 2022-03-05 20:21:34
* @LastEditTime : 2022-03-05 20:46:33 * @LastEditTime : 2022-03-06 16:08:09
* @Description : * @Description :
*/ */
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import './offline.dart'; import './offline.dart';
import './generator.dart';
void main() { void main() {
runApp(const MyApp()); runApp(const MyApp());
@ -35,13 +36,40 @@ class HomePage extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return FutureBuilder(
body: Center( future: Words.importWordsDatabase(),
child: ElevatedButton( builder: (context, snapshot) {
child: const Text('Offline'), if(snapshot.connectionState == ConnectionState.done) {
onPressed: () => Navigator.of(context).pushNamed("/Offline"), return Scaffold(
) body: Center(
) child: ElevatedButton(
child: const Text('Offline'),
onPressed: () => Navigator.of(context).pushNamed("/Offline"),
),
),
);
}
else {
return const Center(
child: SizedBox(
height: 100.0,
width: 100.0,
child: CircularProgressIndicator(
strokeWidth: 5.0,
),
),
);
}
},
); );
// Scaffold(
// body: Center(
// child: ElevatedButton(
// child: const Text('Offline'),
// onPressed: () => Navigator.of(context).pushNamed("/Offline"),
// )
// )
// );
} }
} }

View File

@ -1,14 +1,14 @@
/* /*
* @Author : Linloir * @Author : Linloir
* @Date : 2022-03-05 20:41:41 * @Date : 2022-03-05 20:41:41
* @LastEditTime : 2022-03-06 11:41:41 * @LastEditTime : 2022-03-06 16:22:11
* @Description : Offline page * @Description : Offline page
*/ */
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:wordle/event_bus.dart';
import 'package:wordle/validation_provider.dart'; import 'package:wordle/validation_provider.dart';
import './display_pannel.dart'; import './display_pannel.dart';
import './input_pannel.dart';
class OfflinePage extends StatefulWidget { class OfflinePage extends StatefulWidget {
const OfflinePage({Key? key}) : super(key: key); const OfflinePage({Key? key}) : super(key: key);
@ -36,9 +36,11 @@ class _OfflinePageState extends State<OfflinePage> {
iconTheme: const IconThemeData(color: Colors.black), iconTheme: const IconThemeData(color: Colors.black),
actions: [ actions: [
IconButton( IconButton(
icon: const Icon(Icons.history), icon: const Icon(Icons.refresh_rounded),
color: Colors.black, color: Colors.black,
onPressed: (){}, onPressed: (){
mainBus.emit(event: "NewGame", args: []);
},
) )
], ],
), ),

View File

@ -1,14 +1,15 @@
/* /*
* @Author : Linloir * @Author : Linloir
* @Date : 2022-03-05 21:40:51 * @Date : 2022-03-05 21:40:51
* @LastEditTime : 2022-03-06 11:42:36 * @LastEditTime : 2022-03-06 16:17:30
* @Description : Validation Provider class * @Description : Validation Provider class
*/ */
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import './event_bus.dart'; import './event_bus.dart';
import './generator.dart';
enum InputType { singleCharacter, inputConfirmation } enum InputType { singleCharacter, backSpace, inputConfirmation }
class InputNotification extends Notification { class InputNotification extends Notification {
const InputNotification({required this.type, required this.msg}); const InputNotification({required this.type, required this.msg});
@ -27,21 +28,34 @@ class ValidationProvider extends StatefulWidget {
} }
class _ValidationProviderState extends State<ValidationProvider> { class _ValidationProviderState extends State<ValidationProvider> {
String answer = "WORDLE"; String answer = "";
Set<String> letterSet = <String>{'W', 'O', 'R', 'D', 'L', 'E'}; Map<String, int> letterMap = {};
String curAttempt = ""; String curAttempt = "";
int curAttemptCount = 0; int curAttemptCount = 0;
bool acceptInput = true; bool acceptInput = true;
void _newGame(String answer) { void _onNewGame(dynamic args) {
this.answer = answer; _newGame();
letterSet.clear(); }
letterSet.addAll(answer.split(''));
void _newGame() async{
answer = await Words.generateWord();
answer = answer.toUpperCase();
letterMap = {};
answer.split('').forEach((c) {
letterMap[c] ??= 0;
letterMap[c] = letterMap[c]! + 1;
});
letterMap = Map.unmodifiable(letterMap);
curAttempt = ""; curAttempt = "";
curAttemptCount = 0; curAttemptCount = 0;
acceptInput = true; acceptInput = true;
} }
void _onGameEnd(dynamic args) {
args as bool ? _onGameWin() : _onGameLoose();
}
void _onGameWin() { void _onGameWin() {
acceptInput = false; acceptInput = false;
_showResult(true); _showResult(true);
@ -52,27 +66,44 @@ class _ValidationProviderState extends State<ValidationProvider> {
_showResult(false); _showResult(false);
} }
void _showResult(bool result) { void _showResult(bool result) async {
showDialog( var startNew = await showDialog<bool>(
context: context, context: context,
builder: (context) { builder: (context) {
return AlertDialog( return AlertDialog(
title: const Text('Result'), title: const Text('Result'),
content: Text(result ? "Won" : "Lost"), content: Text(result ? "Won" : "Lost"),
actions: [
TextButton(
child: const Text('Back'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: const Text('New Game'),
onPressed: () => Navigator.of(context).pop(true),
)
],
); );
} }
); );
} if(startNew == true) {
mainBus.emit(event: "NewGame", args: []);
bool _isWordValidate(String word) { }
return true;
} }
@override @override
void initState(){ void initState(){
super.initState(); super.initState();
mainBus.onBus(event: "NewGame", onEvent: (args) => _newGame(args as String)); _newGame();
mainBus.onBus(event: "Result", onEvent: (args) => args as bool ? _onGameWin() : _onGameLoose()); mainBus.onBus(event: "NewGame", onEvent: _onNewGame);
mainBus.onBus(event: "Result", onEvent: _onGameEnd);
}
@override
void dispose() {
mainBus.offBus(event: "NewGame", callBack: _onNewGame);
mainBus.offBus(event: "Result", callBack: _onGameEnd);
super.dispose();
} }
@override @override
@ -80,34 +111,49 @@ class _ValidationProviderState extends State<ValidationProvider> {
return NotificationListener<InputNotification>( return NotificationListener<InputNotification>(
child: widget.child, child: widget.child,
onNotification: (noti) { onNotification: (noti) {
print('Get'); if(noti.type == InputType.inputConfirmation) {
if(noti.type == InputType.inputConfirmation){
if(curAttempt.length < 5) { if(curAttempt.length < 5) {
print('failed');
//Not enough //Not enough
return true; return true;
} }
else { else {
//Check validation //Check validation
if(_isWordValidate(curAttempt)) { if(Words.isWordValidate(curAttempt)) {
//Generate map
Map<String, int> leftWordMap = Map.from(letterMap);
var positionValRes = <int>[for(int i = 0; i < 5; i++) -1];
var letterValRes = <String, int>{};
for(int i = 0; i < 5; i++) {
if(curAttempt[i] == answer[i]) {
positionValRes[i] = 1;
leftWordMap[curAttempt[i]] = leftWordMap[curAttempt[i]]! - 1;
letterValRes[curAttempt[i]] = 1;
}
}
for(int i = 0; i < 5; i++) {
if(curAttempt[i] != answer[i] && leftWordMap[curAttempt[i]] != null && leftWordMap[curAttempt[i]]! > 0) {
positionValRes[i] = 2;
leftWordMap[curAttempt[i]] = leftWordMap[curAttempt[i]]! - 1;
letterValRes[curAttempt[i]] = letterValRes[curAttempt[i]] == 1 ? 1 : 2;
}
else if(curAttempt[i] != answer[i]) {
positionValRes[i] = -1;
letterValRes[curAttempt[i]] ??= -1;
}
}
//emit current attempt //emit current attempt
mainBus.emit( mainBus.emit(
event: "Attempt", event: "Attempt",
args: <int>[ args: positionValRes,
for(int i = 0; i < 5; i++) );
if(curAttempt[i] == answer[i]) mainBus.emit(
1 event: "Validation",
else if(letterSet.lookup(curAttempt[i]) != null) args: letterValRes,
2
else
-1
],
); );
print('Emited');
curAttempt = ""; curAttempt = "";
curAttemptCount++; curAttemptCount++;
} }
else{ else {
showDialog( showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
@ -126,6 +172,11 @@ class _ValidationProviderState extends State<ValidationProvider> {
} }
} }
} }
else if(noti.type == InputType.backSpace) {
if(curAttempt.isNotEmpty) {
curAttempt = curAttempt.substring(0, curAttempt.length - 1);
}
}
else{ else{
if(acceptInput && curAttempt.length < 5) { if(acceptInput && curAttempt.length < 5) {
curAttempt += noti.msg; curAttempt += noti.msg;

View File

@ -61,6 +61,8 @@ flutter:
# assets: # assets:
# - images/a_dot_burr.jpeg # - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg # - images/a_dot_ham.jpeg
assets:
- assets/words_alpha.txt
# An image asset can refer to one or more resolution-specific "variants", see # An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware. # https://flutter.dev/assets-and-images/#resolution-aware.