Select Git revision
game_utils.dart
-
Benoît Harrault authoredBenoît Harrault authored
game_utils.dart 3.08 KiB
import '../provider/data.dart';
import '../utils/random_pick_word.dart';
class GameUtils {
static Future<void> quitGame(Data myProvider) async {
myProvider.updateGameIsRunning(false);
}
static Future<void> startGame(Data myProvider) async {
print('Starting game (' +
myProvider.lang +
' / ' +
myProvider.length +
' / ' +
myProvider.level +
' )');
myProvider.resetGame();
await pickWord(myProvider);
myProvider.updateGameIsRunning(true);
}
static Future<void> pickWord(Data myProvider) async {
RandomPickWord randomPickWord;
String word = '';
int attempts = 0;
do {
randomPickWord = RandomPickWord();
int wordLength = int.parse(myProvider.length);
await randomPickWord.init(myProvider.lang, wordLength, myProvider.level);
if (randomPickWord.word != '') {
word = randomPickWord.word;
}
attempts++;
if ((word != '') && !myProvider.isRecentlyPicked(word)) {
myProvider.updateWord(word);
}
} while (myProvider.word != word && attempts < 10);
print('Picked word: ' + word);
}
static void addLetter(Data myProvider, String letter) {
myProvider.currentGuessAddLetter(letter);
}
static void removeLetter(Data myProvider) {
myProvider.currentGuessRemoveLetter();
}
static List<String> getTips(Data myProvider, String candidate) {
String word = myProvider.word;
int wordLength = int.parse(myProvider.length);
List<String> tips = List<String>.filled(wordLength, '', growable: false);
if ((word.length != wordLength) ||
(candidate.length != wordLength) ||
(!RandomPickWord.checkWordExists(candidate))) {
return List<String>.filled(wordLength, 'wrong', growable: false);
}
String replaceCharAt(String oldString, int index, String newChar) {
return oldString.substring(0, index) + newChar + oldString.substring(index + 1);
}
// Check correctly placed letters
for (int i = 0; i < wordLength; i++) {
if ((tips[i] == '') && (word[i] == candidate[i])) {
myProvider.addFoundLetter(word[i], i);
word = replaceCharAt(word, i, ' ');
candidate = replaceCharAt(candidate, i, ' ');
tips[i] = 'good';
}
}
// Check misplaced letters
for (int i = 0; i < wordLength; i++) {
for (int j = 0; j < wordLength; j++) {
if ((candidate[j] != ' ') && (candidate[j] == word[i])) {
word = replaceCharAt(word, i, ' ');
candidate = replaceCharAt(candidate, j, ' ');
tips[j] = 'misplaced';
}
}
}
return tips;
}
static void submitWord(Data myProvider) {
if (GameUtils.checkCurrentlyGuessedWordExists(myProvider)) {
print('Ok word allowed: "' + myProvider.currentGuess + '".');
myProvider.currentGuessSubmitWord();
} else {
print('Unknown word: "' + myProvider.currentGuess + '".');
myProvider.currentGuessSubmitWrongWord();
}
}
static bool checkCurrentlyGuessedWordExists(Data myProvider) {
return RandomPickWord.checkWordExists(myProvider.currentGuess);
}
}