Read data from an input file

This commit is contained in:
Yohann D'ANELLO 2022-04-28 22:57:20 +02:00
parent 0ea390fcae
commit 4ecbe2540e
Signed by: ynerant
GPG Key ID: 3A75C55819C8CF85
2 changed files with 44 additions and 7 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
cemantix-charm
.ssh
cemantics.txt

50
main.go
View File

@ -12,11 +12,12 @@ import (
bm "github.com/charmbracelet/wish/bubbletea"
lm "github.com/charmbracelet/wish/logging"
"github.com/gliderlabs/ssh"
"io/ioutil"
"log"
"math"
"math/rand"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
@ -84,9 +85,31 @@ func teaHandler(s ssh.Session) (tea.Model, []tea.ProgramOption) {
ti.Focus()
ti.CharLimit = 26
ti.Width = 26
content, err := ioutil.ReadFile("cemantics.txt")
if err != nil {
log.Printf("Error while opening cemantics.txt: %s", err)
return nil, nil
}
var dictionary = map[string]word{}
for i, line := range strings.Split(string(content), "\n") {
if line == "" || line[0] == '#' {
continue
}
s := strings.SplitN(line, " ", 2)
w := s[0]
dist, _ := strconv.ParseFloat(s[1], 64)
dictionary[w] = word{w, dist, 1000 - i}
}
m := model{
textInput: ti,
err: nil,
dictionary: dictionary,
textInput: ti,
ip: s.RemoteAddr().String(),
words: []word{},
progressBar: progress.New(progress.WithScaledGradient("#FF7CCB", "#FDFF8C")),
@ -105,6 +128,7 @@ type word struct {
type model struct {
ready bool
err error
dictionary map[string]word
textInput textinput.Model
ip string
words []word
@ -147,7 +171,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
lineWidth := lipgloss.Width(fmt.Sprintf(
"* %s %s %s %4d ",
strings.Repeat(" ", m.maxLength),
"-00.00",
"-100.00",
" ",
42,
))
@ -181,20 +205,27 @@ func InsertWord(arr []word, w word) []word {
func (m model) InputWord() (model, tea.Cmd) {
input := m.textInput.Value()
w, found := m.dictionary[input]
if !found {
m.err = fmt.Errorf("le mot %s n'existe pas", input)
m.textInput.SetValue("")
m.textInput.CursorStart()
return m, nil
}
m.lastWord = input
if utf8.RuneCountInString(input) > m.maxLength {
m.maxLength = utf8.RuneCountInString(input)
}
// TODO: Get distance and ranking from a file
w := word{input, 200*rand.Float64() - 100, rand.Intn(1000)}
m.words = InsertWord(m.words, w)
lineWidth := lipgloss.Width(fmt.Sprintf(
"* %s %s %s %4d ",
"* %s %s %s %5d ",
strings.Repeat(" ", m.maxLength),
"-00.00",
" ",
42,
1000,
))
m.progressBar.Width = m.wordsViewport.Width - lineWidth
@ -202,6 +233,8 @@ func (m model) InputWord() (model, tea.Cmd) {
m.textInput.SetValue("")
m.textInput.CursorStart()
m.err = nil
return m, nil
}
@ -233,6 +266,9 @@ func (w word) View(m model) string {
if w.distance >= 0 {
distStr = " " + distStr
}
if math.Abs(w.distance) < 100 {
distStr = " " + distStr
}
return fmt.Sprintf(
"* %s %s %s %4d %s\n",