-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDictionaryService.cs
67 lines (60 loc) · 2.07 KB
/
DictionaryService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Reflection;
using System.Text;
namespace Hangman.model
{
internal class DictionaryService
{
private static DictionaryService? instance = null;
private List<string> words = new List<string>();
Random random = new Random();
private DictionaryService()
{
words = new List<string>([
"библиотека",
"самосвал",
"машина",
"кенгуру",
"абберация",
"карандаш",
"мишень",
"программирование"
]);
}
public static DictionaryService getInstance()
{
if (instance == null)
{
instance = new DictionaryService();
instance.LoadWords();
}
return instance;
}
public void LoadWords()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var encoding = Encoding.GetEncoding("windows-1251");
try
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Hangman.resources.ru.txt"))
using (var reader = new StreamReader(stream, encoding))
{
string word;
while ((word = reader.ReadLine()) != null)
{
words.Add(word.ToLower());
}
}
}
catch
{
Console.WriteLine("Ее удалось загрузить словарик из ресурсов.");
}
}
public string GetRandomWord(int minWordLength = 4, int maxWordLength = 8)
{
var suitableWords = words.FindAll(word => word.Length >= minWordLength && word.Length <= maxWordLength);
var selectedWordIndex = random.Next(0, suitableWords.Count);
return suitableWords[selectedWordIndex];
}
}
}