gordle/cmd/cli/main.go

101 lines
2 KiB
Go
Raw Permalink Normal View History

2023-08-12 00:40:50 +02:00
//nolint:forbidigo
2023-08-07 20:54:08 +02:00
package main
2023-08-12 00:40:50 +02:00
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"strings"
"github.com/Crocmagnon/gordle/lib/gordle"
)
const (
defaultWordLength = 5
defaultMaxAttempts = 5
)
2023-08-07 20:54:08 +02:00
func main() {
2023-08-12 00:40:50 +02:00
wordLength := flag.Int("l", defaultWordLength, "word length")
dictionary := flag.String("f", "", "dictionary file")
maxAttempts := flag.Int("m", defaultMaxAttempts, "maximum number of attempts")
cheat := flag.Bool("c", false, "cheat mode (prints word at the beginning)")
2023-08-12 00:40:50 +02:00
flag.Parse()
if !validateInput(dictionary, wordLength, maxAttempts) {
os.Exit(1)
}
file, err := os.Open(*dictionary)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
word, err := gordle.PickWord(file, *wordLength)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Printf("length %d ; you have %d attempts\n", *wordLength, *maxAttempts)
if *cheat {
fmt.Printf("word: %s\n", word)
}
2023-08-12 00:40:50 +02:00
scanner := bufio.NewScanner(os.Stdin)
game := gordle.New(*maxAttempts, word)
play(game, scanner, word, wordLength)
}
func play(game *gordle.Game, scanner *bufio.Scanner, word string, wordLength *int) {
2023-08-12 00:40:50 +02:00
for !game.Over() && scanner.Scan() {
var feedback gordle.FullFeedback
text := strings.ToUpper(scanner.Text())
feedback, err := game.TryWord(text)
2023-08-12 00:40:50 +02:00
switch {
case errors.Is(err, gordle.ErrGameWon):
fmt.Println(feedback)
2023-08-16 20:26:27 +02:00
fmt.Println("🎉 you won")
2023-08-12 00:40:50 +02:00
case errors.Is(err, gordle.ErrGameLost):
fmt.Println(feedback)
2023-08-16 20:26:27 +02:00
fmt.Printf("😔 you lost, the correct word was %s\n", word)
case errors.Is(err, gordle.ErrRunesCount):
fmt.Printf("🤔 please provide a %d-letters word\n", *wordLength)
default:
fmt.Println(feedback)
2023-08-12 00:40:50 +02:00
}
}
}
func validateInput(dictionary *string, wordLength *int, maxAttempts *int) bool {
ok := true //nolint:varnamelen
if *dictionary == "" {
fmt.Println("dictionary file is mandatory")
ok = false
}
if *wordLength <= 0 {
fmt.Println("word length must be positive")
ok = false
}
if *maxAttempts <= 0 {
fmt.Println("max attempts must be positive")
ok = false
}
return ok
2023-08-07 20:54:08 +02:00
}