-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.R
executable file
·86 lines (79 loc) · 2.33 KB
/
main.R
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
library(rjson)
library(argparser, quietly = TRUE)
source("src/parseUserInput.R")
source("src/stats.R")
source("src/cli.R")
source("src/wordMap.R")
argvals <- parse_args(argParser())
parsedArgs <- validateArgs(argvals)
wordsMap <-
rjson::fromJSON(file = file.path("resources", paste0(parsedArgs$wordlist, ".json")))
cacheFile <- paste0(parsedArgs$wordlist, ".rds")
cacheFile <-
ifelse(parsedArgs$reverse, paste0("reverse_", cacheFile) , cacheFile)
serializedWordWeightsFile <- file.path(".cache", cacheFile)
if(parsedArgs$reverse){
wordsMap<- reverseWordMap(wordsMap)
}
loadWordWeights(serializedWordWeightsFile, wordsMap, stats)
stats$wordWeights <-
stats$wordWeights[order(names(stats$wordWeights))]
wordsMap <- wordsMap[order(names(wordsMap))]
stdIn <- file("stdin")
while (TRUE) {
wordToBeAsked <-
names(sample(wordsMap, size = 1, prob = stats$wordWeights))
sampleProbability <-
round(stats$wordWeights[[wordToBeAsked]] / sum(unlist(stats$wordWeights)) * 100, 2)
message(sprintf(
"Do translate the word %s [p=%s] (or press enter to skip)",
toupper(wordToBeAsked),
paste0(sampleProbability, "%")
))
inputAnswer <- parseUserInput(
scan(
file = stdIn,
what = "character",
n = 1,
nlines = 1,
quiet = T,
sep = "\n",
skipNul = T,
skip = 0
)
)
if (length(inputAnswer) > 0 && inputAnswer == "summary") {
message(stats$formatStats())
next
}
if (length(inputAnswer) > 0 && inputAnswer == "exit") {
message("Quitting! Remember: Practice makes perfect.")
message("Performance:")
message(stats$formatStats())
saveRDS(stats$wordWeights, file = serializedWordWeightsFile)
closeAllConnections()
quit(save = "no")
}
stats$totalAnswers <- stats$totalAnswers + 1
if (length(inputAnswer) > 0 &&
inputAnswer %in% wordsMap[[wordToBeAsked]]) {
message("Correct! :D")
stats$registerCorrectAnswer(wordToBeAsked)
}
else {
stats$registerMistake(wordToBeAsked)
correctAnswers <-
paste(toupper(wordsMap[[wordToBeAsked]]), collapse = " or ")
if (length(inputAnswer) == 0) {
message(sprintf("Skipping! It means: '%s'.", correctAnswers))
} else {
message(
sprintf(
"Wrong! The right answer is NOT '%s', but '%s'.",
inputAnswer,
correctAnswers
)
)
}
}
}