Skip to content

Instantly share code, notes, and snippets.

@Vrixyz
Created January 6, 2023 14:06
Show Gist options
  • Save Vrixyz/4974ccd29d5307cf9a18da7b3e59b6d8 to your computer and use it in GitHub Desktop.
Save Vrixyz/4974ccd29d5307cf9a18da7b3e59b6d8 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class WordsLoader
{
public static int wordMaximumLength = 50;
public static int numberOfLettersInAlphabet = 26;
public string wordsFilename = "Words-fr.txt";
int totalWords = 0;
public int TotalWords
{
get
{
return totalWords;
}
}
// authorized words are indexed onto their length, so if a word in the dictionary is longer than 50 characters, game will crash.
// [0] will always be empty, but it's not a great lose of performance and better to read.. an accessor would fix it but let's keep codebase at minimum
List<string>[] authorizedWordsForLength = new List<string>[wordMaximumLength + 1];
List<string>[] authorizedWordsForLetter = new List<string>[numberOfLettersInAlphabet];
bool isLoaded = false;
public bool IsLoaded
{
get
{
return isLoaded;
}
}
public List<string> getAuthorizedWordsForLength(int length)
{
return authorizedWordsForLength[length];
}
public List<string> getAuthorizedWordsForLetter(char letter)
{
return authorizedWordsForLetter[letter - 'a'];
}
public IEnumerator LoadWords(bool force = false)
{
if (force || !IsLoaded)
{
this.isLoaded = false;
authorizedWordsForLength = new List<string>[wordMaximumLength];
string filepath = System.IO.Path.Combine(Application.streamingAssetsPath, wordsFilename);
if (!File.Exists(filepath))
{
MonoBehaviour.print("Couldn't load file: " + filepath);
yield break;
}
for (int i = 0; i < numberOfLettersInAlphabet; i++)
{
authorizedWordsForLetter[i] = new List<string>();
}
using (StreamReader sr = new StreamReader(filepath))
{
int i = 0;
string line;
while ((line = sr.ReadLine()) != null && line.Length > 0)
{
if (authorizedWordsForLength[line.Length] == null)
{
authorizedWordsForLength[line.Length] = new List<string>();
}
string lineLower = line.ToLower();
authorizedWordsForLength[line.Length].Add(lineLower);
authorizedWordsForLetter[lineLower[0] - 'a'].Add(lineLower);
if (i % 5000 == 0)
{
yield return null;
}
i++;
}
totalWords = i;
}
this.isLoaded = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment