101 lines
1.7 KiB
Go
101 lines
1.7 KiB
Go
package game
|
|
|
|
import (
|
|
"strings"
|
|
)
|
|
|
|
type Wordle interface {
|
|
Guess(string) int
|
|
GetState() string
|
|
GetSecret() string
|
|
ValidLength(string) bool
|
|
}
|
|
|
|
type wordle struct {
|
|
secret string
|
|
maxAttempts int
|
|
history []string
|
|
}
|
|
|
|
func NewWordle(secret string, maxAttempts int) Wordle {
|
|
return &wordle{
|
|
secret: secret,
|
|
maxAttempts: maxAttempts,
|
|
history: make([]string, 0),
|
|
}
|
|
}
|
|
|
|
func (w *wordle) Guess(guess string) int {
|
|
guess = strings.ToUpper(guess)
|
|
line, yes := wordleCompare([]rune(guess), []rune(w.secret))
|
|
w.history = append(w.history, line)
|
|
st := 0
|
|
if yes {
|
|
st = 1
|
|
} else if len(w.history) >= w.maxAttempts {
|
|
st = -1
|
|
}
|
|
return st
|
|
}
|
|
|
|
func wordleCompare(guess, secret []rune) (string, bool) {
|
|
yes := true
|
|
leng := len(secret)
|
|
state := make([]int, leng)
|
|
result := strings.Builder{}
|
|
for n := 0; n < leng; n++ {
|
|
if guess[n] == secret[n] {
|
|
state[n] = 2
|
|
secret[n] = ' '
|
|
} else {
|
|
yes = false
|
|
}
|
|
}
|
|
for n := 0; n < leng; n++ {
|
|
if state[n] == 0 {
|
|
for n2 := 0; n2 < leng; n2++ {
|
|
if n == n2 {
|
|
continue
|
|
} else if guess[n] == secret[n2] {
|
|
state[n] = 1
|
|
secret[n2] = ' '
|
|
break
|
|
}
|
|
}
|
|
}
|
|
start := '.'
|
|
end := '.'
|
|
if state[n] == 1 {
|
|
start = '('
|
|
end = ')'
|
|
}
|
|
if state[n] == 2 {
|
|
start = '['
|
|
end = ']'
|
|
}
|
|
result.WriteRune(start)
|
|
result.WriteRune(guess[n])
|
|
result.WriteRune(end)
|
|
}
|
|
return result.String(), yes
|
|
}
|
|
|
|
func (w *wordle) GetState() string {
|
|
state := strings.Builder{}
|
|
for n, h := range w.history {
|
|
state.WriteString(h)
|
|
if n != len(w.history)-1 {
|
|
state.WriteRune('\n')
|
|
}
|
|
}
|
|
return state.String()
|
|
}
|
|
|
|
func (w *wordle) GetSecret() string {
|
|
return w.secret
|
|
}
|
|
|
|
func (w *wordle) ValidLength(s string) bool {
|
|
return len(s) == len(w.secret)
|
|
}
|