-
Notifications
You must be signed in to change notification settings - Fork 0
/
card.go
90 lines (75 loc) · 2.19 KB
/
card.go
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
87
88
89
90
package flashcards
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
"github.com/sirupsen/logrus"
)
// Card is a single card in the deck
type Card struct {
ID ID `json:"-"`
Phrase *Phrase `json:"phrase,omitempty"`
}
// ShuffleCards reorders items in the slice of cards using a PRNG
func ShuffleCards(cards []*Card) {
for i := range cards {
j := rand.Intn(i + 1)
cards[i], cards[j] = cards[j], cards[i]
}
}
// NewCard generates a new card to represdent a single phrase
func NewCard(p *Phrase) *Card {
return &Card{
ID: NewID(),
Phrase: p,
}
}
// PrintQuestion is a pretty formatter for command line version of rendering the card
func (c *Card) PrintQuestion(deck *Deck) string {
if deck.Know == "" || deck.Learning == "" {
panic(fmt.Sprintf("Something isn't set -- Know: %s -- Learning: %s", deck.Know, deck.Learning))
}
var options []*Card
options = append(options, deck.GetIncorrectGuesses(c, 3)...)
options = append(options, c)
ShuffleCards(options)
learning := c.Phrase.Language(deck.Learning)
percentage := learning.Stats.Percentage * 100
weighting := learning.Stats.Weighting
msg := fmt.Sprintf("Translate: %s %s (%.1f %s %.1f)",
learning.Value, learning.GetPhonetic(deck.Know).Value, percentage, "%", weighting)
for i, o := range options {
msg = fmt.Sprintf("%s \n \t %d) %s", msg, i+1, o.Phrase.Language(deck.Know).Value)
}
return msg
}
// AttemptAnswer accepts an answer from a user and checks whether it is correct
func (c *Card) AttemptAnswer(know, learning Language, attempt string) {
if attempt == "" {
attempt = readString()
}
phrase := c.Phrase
knowT := phrase.Language(know)
learningT := phrase.Language(learning)
if strings.EqualFold(attempt, knowT.Value) {
c.Phrase.Language(learning).Stats.CorrectAttempt()
} else {
c.Phrase.Language(learning).Stats.WrongAttempt()
logrus.Errorf("\t | \t %s \t | \t %s \t | \t %s \t | \t %s",
attempt,
learningT.Value,
learningT.GetPhonetic(know).Value,
knowT.Value,
)
}
}
func readString() string {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Type your answer: ")
input, _ := reader.ReadString('\n')
input = strings.Trim(input, " ")
input = strings.Trim(input, "\n")
return input
}