mirror of
https://forgejo.allbyte.fr/nono/flutter_wordle
synced 2026-03-14 21:15:45 +01:00
62 lines
2 KiB
Dart
62 lines
2 KiB
Dart
import 'dart:convert';
|
|
import 'dart:math';
|
|
|
|
import 'package:diacritic/diacritic.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class WordLoader {
|
|
static final Map<String, List<String>> _cachedWordLists = {};
|
|
|
|
static Future<List<String>> loadWordList(String language) async {
|
|
if (_cachedWordLists.containsKey(language)) {
|
|
return _cachedWordLists[language]!;
|
|
}
|
|
|
|
try {
|
|
String assetPath = "assets/${language}_words.json";
|
|
String jsonString = await rootBundle.loadString(assetPath);
|
|
List<dynamic> wordsJson = json.decode(jsonString);
|
|
List<String> words = wordsJson.cast<String>();
|
|
_cachedWordLists[language] = words;
|
|
return words;
|
|
} catch (e) {
|
|
print("Error loading word list for language '$language': $e");
|
|
return [];
|
|
}
|
|
}
|
|
|
|
static Future<bool> isValidWord(String word) async {
|
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
var language = prefs.getString('selectedLanguage') ?? "english";
|
|
List<String> words = await WordLoader.loadWordList(language);
|
|
|
|
List<String> normalizedWords =
|
|
words.map((w) => removeDiacritics(w).toUpperCase()).toList();
|
|
return normalizedWords.contains(word.toUpperCase());
|
|
}
|
|
|
|
static List<String> _filterWordsByLength(List<String> words, int length) {
|
|
return words
|
|
.where((word) => word.length == length && !word.contains("-"))
|
|
.toList();
|
|
}
|
|
|
|
static String? _selectRandomWord(List<String> words) {
|
|
if (words.isEmpty) {
|
|
return null;
|
|
}
|
|
final random = Random();
|
|
return words[random.nextInt(words.length)];
|
|
}
|
|
|
|
static Future<String?> getWordOfLength(int length) async {
|
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
var language = prefs.getString('selectedLanguage') ?? "english";
|
|
List<String> words = await loadWordList(language);
|
|
List<String> filteredWords = _filterWordsByLength(words, length);
|
|
String? word = _selectRandomWord(filteredWords);
|
|
print(word);
|
|
return word;
|
|
}
|
|
}
|