Compare commits

...
7 Commits
Author SHA1 Message Date
cjdenio d50b572fb5 license 2026-10-02 09:11:04 -06:00
cjdenio 7b35f86e32 fix issues 2026-10-01 16:07:45 -06:00
cjdenio 419f0ae3cf handle empty copyright 2026-10-01 10:40:54 -06:00
cjdenio b918c5be23 parse rebus cells 2026-09-29 22:50:24 -04:00
cjdenio 60d1bd644c reveal/check/clear 2026-09-29 22:26:49 -04:00
cjdenio 50be9ab605 refactor .puz parser + detect rebuses 2026-09-29 21:20:13 -04:00
cjdenio b7c64dabe3 fix ipuz bug 2026-09-29 14:39:48 -04:00
7 changed files with 350 additions and 62 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Caleb Denio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-3
View File
@@ -11,9 +11,6 @@ Very silly terminal-based crossword solver. It can play .puz / .ipuz files from
todo
- timer
- reveal grid/word
- .puz checksums
- fix shift+enter / shift+tab in other terminals
- clear grid
- rebus
- detect rebus for .puz files
+122 -27
View File
@@ -20,16 +20,26 @@ const (
Solved
)
type UIState int
const (
StateGame UIState = iota
StateRebusConfirmation
StateMenu
StateRevealMenu
StateCheckMenu
)
type State struct {
Puzzle *puz.Puzzle
PuzzleState []rune
SelectedCell int
SelectedClue *puz.Clue
LastKeySequence string
DebugMode bool
SolveState SolveState
CheckState []rune
RebusConfirmation bool
Puzzle *puz.Puzzle
PuzzleState []rune
SelectedCell int
SelectedClue *puz.Clue
LastKeySequence string
DebugMode bool
SolveState SolveState
CheckState []rune
UIState UIState
}
func RenderWithLineWrap(s string, width int) (out string, lines int) {
@@ -74,13 +84,17 @@ func RenderWithLineWrap(s string, width int) (out string, lines int) {
}
func NewState(puzzle *puz.Puzzle) *State {
state := StateGame
if puzzle.HasRebus {
state = StateRebusConfirmation
}
return &State{
Puzzle: puzzle,
PuzzleState: []rune(puzzle.State),
SelectedClue: puzzle.Clues[0],
SelectedCell: puzzle.Clues[0].Cells[0],
CheckState: make([]rune, len(puzzle.State)),
RebusConfirmation: puzzle.HasRebus,
Puzzle: puzzle,
PuzzleState: []rune(puzzle.State),
SelectedClue: puzzle.Clues[0],
SelectedCell: puzzle.Clues[0].Cells[0],
CheckState: make([]rune, len(puzzle.State)),
UIState: state,
}
}
@@ -284,8 +298,25 @@ func (state *State) CheckWord(clue *puz.Clue) {
}
}
func (state *State) RevealWord(clue *puz.Clue) {
for i, cellIdx := range clue.Cells {
state.PuzzleState[cellIdx] = rune(clue.Solution[i])
state.CheckState[cellIdx] = 'y'
}
}
func (state *State) RevealPuzzle() {
for i, cell := range state.PuzzleState {
if cell == '.' {
continue
}
state.PuzzleState[i] = rune(state.Puzzle.Solution[i])
state.CheckState[i] = 'y'
}
}
func (state *State) RenderUI(w io.Writer, width int) int {
if state.RebusConfirmation {
if state.UIState == StateRebusConfirmation {
fmt.Fprint(w, "This puzzle contains a rebus. This tool does not support rebuses.\r\nPress 'y' to continue anyway, or press any other key to exit.\r\n")
return 2
}
@@ -310,8 +341,25 @@ func (state *State) RenderUI(w io.Writer, width int) int {
io.WriteString(w, "\r\n")
uiHeight += 1
}
fmt.Fprintf(w, "%s\r\n", state.Puzzle.Copyright)
uiHeight += 1
if state.Puzzle.Copyright != "" {
fmt.Fprintf(w, "%s\r\n\r\n", state.Puzzle.Copyright)
uiHeight += 2
}
switch state.UIState {
case StateGame:
fmt.Fprint(w, AnsiDimmed("[enter]/[tab]: next word | [ctrl+a]: menu | [ctrl+c]: exit\r\n"))
uiHeight += 1
case StateMenu:
fmt.Fprint(w, AnsiDimmed("[c]: check puzzle/word | [r]: reveal puzzle/word | [x]: clear grid | [q]: exit menu\r\n"))
uiHeight += 1
case StateCheckMenu:
fmt.Fprint(w, AnsiDimmed("[w]: check word | [p]: check puzzle | [q]: exit menu\r\n"))
uiHeight += 1
case StateRevealMenu:
fmt.Fprint(w, AnsiDimmed("[w]: reveal word | [p]: reveal puzzle | [q]: exit menu\r\n"))
uiHeight += 1
}
switch state.SolveState {
case FilledNotSolved:
@@ -471,26 +519,73 @@ func (state *State) SwitchDirections() bool {
return false
}
func (state *State) ClearGrid() {
for i, cell := range state.PuzzleState {
if cell != '.' {
state.PuzzleState[i] = '-'
state.CheckState[i] = '\x00'
}
}
}
func (state *State) HandleInput(buffer []byte) (exited bool) {
if len(buffer) == 0 {
return false
}
if state.RebusConfirmation {
if buffer[0] == 'y' {
state.RebusConfirmation = false
return false
} else {
return true
}
}
state.LastKeySequence = fmt.Sprintf("%v", buffer)
if buffer[0] == 3 {
return true
}
switch state.UIState {
case StateRebusConfirmation:
if buffer[0] == 'y' {
state.UIState = StateGame
return false
} else {
return true
}
case StateMenu:
switch buffer[0] {
case 'c':
state.UIState = StateCheckMenu
case 'r':
state.UIState = StateRevealMenu
case 'x':
state.ClearGrid()
state.UIState = StateGame
default:
state.UIState = StateGame
}
return false
case StateCheckMenu:
switch buffer[0] {
case 'w':
state.CheckWord(state.SelectedClue)
case 'p':
state.CheckPuzzle()
}
state.UIState = StateGame
return false
case StateRevealMenu:
switch buffer[0] {
case 'w':
state.RevealWord(state.SelectedClue)
case 'p':
state.RevealPuzzle()
return true
}
state.UIState = StateGame
return false
}
if buffer[0] == '\x01' {
state.UIState = StateMenu
return false
}
if buffer[0] == ' ' {
state.SwitchDirections()
}
+35 -14
View File
@@ -27,6 +27,27 @@ type iPuzFile struct {
Clues map[string][]iPuzClue `json:"clues"`
}
func unwrapCell(cell any) (any, error) {
switch c := cell.(type) {
case string:
if c == "#" {
return "#", nil
} else if i, err := strconv.Atoi(c); err == nil {
return i, nil
} else {
return nil, errors.New("invalid string")
}
case float64:
return int(c), nil
case map[string]any:
if unwrappedCell, ok := c["cell"]; ok {
return unwrapCell(unwrappedCell) // recursion babyyyyyy
}
}
return nil, errors.New("unknown type")
}
func ParseIPuz(file []byte) (*Puzzle, error) {
var parsed iPuzFile
err := json.Unmarshal(file, &parsed)
@@ -42,6 +63,8 @@ func ParseIPuz(file []byte) (*Puzzle, error) {
puzzle := new(Puzzle)
puzzle.RebusCells = make(map[int]string)
puzzle.Title = parsed.Title
puzzle.Author = parsed.Author
puzzle.Copyright = parsed.Copyright
@@ -56,33 +79,31 @@ func ParseIPuz(file []byte) (*Puzzle, error) {
state := strings.Builder{}
for y, row := range parsed.Puzzle {
for x, cell := range row {
switch c := cell.(type) {
unwrappedCell, err := unwrapCell(cell)
if err != nil {
return nil, err
}
switch c := unwrappedCell.(type) {
case string:
if c == "#" {
state.WriteRune('.')
} else {
if i, err := strconv.Atoi(c); err == nil {
clueToCellMap[i] = [2]int{x, y}
}
state.WriteRune('-')
}
case float64:
clueToCellMap[int(c)] = [2]int{x, y}
state.WriteRune('.')
case int:
clueToCellMap[c] = [2]int{x, y}
state.WriteRune('-')
default:
state.WriteRune('-')
return nil, errors.New("unexpected type in .ipuz file")
}
}
}
puzzle.State = state.String()
solution := strings.Builder{}
for _, row := range parsed.Solution {
for _, cell := range row {
for y, row := range parsed.Solution {
for x, cell := range row {
if cell == "#" {
solution.WriteRune('.')
} else if len(cell) > 1 {
solution.WriteByte(cell[0])
puzzle.RebusCells[y*puzzle.Width+x] = cell
puzzle.HasRebus = true
} else if len(cell) == 1 {
solution.WriteString(cell)
+154 -14
View File
@@ -5,7 +5,10 @@ import (
"bytes"
"encoding/binary"
"errors"
"io"
"math"
"regexp"
"strconv"
"strings"
"golang.org/x/text/encoding/charmap"
@@ -61,33 +64,128 @@ func readText(b *bufio.Reader, version string) (string, error) {
}
}
type ExtraBlock struct {
Name string
Data []byte
}
func readExtraBlock(r *bufio.Reader) (*ExtraBlock, error) {
name := make([]byte, 4)
_, err := r.Read(name)
if err != nil {
return nil, err
}
length := make([]byte, 2)
_, err = r.Read(length)
if err != nil {
return nil, err
}
_, err = r.Discard(2)
if err != nil {
return nil, err
}
data := make([]byte, binary.LittleEndian.Uint16(length))
_, err = r.Read(data)
if err != nil {
return nil, err
}
// consume trailing null byte
_, err = r.Discard(1)
if err != nil {
return nil, err
}
return &ExtraBlock{
Name: string(name),
Data: data,
}, nil
}
func ParsePuz(file []byte) (*Puzzle, error) {
r := bytes.NewReader(file)
_, err := r.Seek(2, io.SeekStart) // consume the checksum
if err != nil {
return nil, err
}
// read magic bytes
magic := string(file[2:14])
if magic != "ACROSS&DOWN\x00" {
magic := make([]byte, 12)
_, err = r.Read(magic)
if err != nil {
return nil, err
}
if !bytes.Equal(magic, []byte("ACROSS&DOWN\x00")) {
return nil, errors.New("not a valid .puz file")
}
puzzle := new(Puzzle)
puzzle.RebusCells = make(map[int]string)
_, err = r.Seek(10, io.SeekCurrent)
if err != nil {
return nil, err
}
// read header
version := string(file[0x18:0x1B])
puzzle.Width = int(file[0x2C])
puzzle.Height = int(file[0x2D])
puzzle.ClueCount = int(binary.LittleEndian.Uint16(file[0x2E:0x30]))
version := make([]byte, 4)
_, err = r.Read(version)
if err != nil {
return nil, err
}
_, err = r.Seek(16, io.SeekCurrent)
if err != nil {
return nil, err
}
width, err := r.ReadByte()
if err != nil {
return nil, err
}
height, err := r.ReadByte()
if err != nil {
return nil, err
}
puzzle.Width = int(width)
puzzle.Height = int(height)
clueCount := make([]byte, 2)
_, err = r.Read(clueCount)
if err != nil {
return nil, err
}
puzzle.ClueCount = int(binary.LittleEndian.Uint16(clueCount))
puzzleSize := puzzle.Width * puzzle.Height
solutionStart := 0x34
solutionEnd := 0x34 + puzzleSize
stateStart := solutionEnd
stateEnd := stateStart + puzzleSize
_, err = r.Seek(4, io.SeekCurrent)
if err != nil {
return nil, err
}
puzzle.Solution = string(file[solutionStart:solutionEnd])
puzzle.State = string(file[stateStart:stateEnd])
solution := make([]byte, puzzleSize)
_, err = r.Read(solution)
if err != nil {
return nil, err
}
state := make([]byte, puzzleSize)
_, err = r.Read(state)
if err != nil {
return nil, err
}
// read text
buf := bufio.NewReader(bytes.NewReader(file[stateEnd:]))
puzzle.Solution = string(solution)
puzzle.State = string(state)
// read text fields
buf := bufio.NewReader(r)
title, err := readText(buf, string(version[0]))
if err != nil {
@@ -117,6 +215,48 @@ func ParsePuz(file []byte) (*Puzzle, error) {
clues = append(clues, clue)
}
// read the "note" field, currently unused
_, err = readText(buf, string(version[0]))
if err != nil {
return nil, err
}
extraBlocks := make(map[string]*ExtraBlock)
for {
extra, err := readExtraBlock(buf)
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
extraBlocks[extra.Name] = extra
}
grbs, grbsOk := extraBlocks["GRBS"]
trbl, trblOk := extraBlocks["RTBL"]
if grbsOk && trblOk {
puzzle.HasRebus = true
rebusCellMap := make(map[int][]int)
for i, b := range grbs.Data {
if b > 0 {
rebusCellMap[int(b)-1] = append(rebusCellMap[int(b)-1], i)
}
}
rebusData := regexp.MustCompile(`\s*(\d+):(\w+);\s*`).FindAllStringSubmatch(string(trbl.Data), -1)
for _, rebus := range rebusData {
cell, err := strconv.Atoi(rebus[1])
if err != nil {
continue
}
for _, c := range rebusCellMap[cell] {
puzzle.RebusCells[c] = rebus[2]
}
}
}
// assign clue numbers
puzzle.Clues = make([]*Clue, 0, puzzle.ClueCount)
puzzle.Cells = make([][2]*Clue, len(puzzle.Solution))
+2
View File
@@ -38,6 +38,8 @@ type Puzzle struct {
Cells [][2]*Clue
HasRebus bool
RebusCells map[int]string
}
func LoadPuzzle(r io.Reader) (*Puzzle, error) {
+16 -4
View File
@@ -39,8 +39,20 @@ func main() {
io.WriteString(s, "\x1b[?25h")
}()
pty, _, _ := s.Pty() // TODO: actually handle terminal size changes
uiHeight := state.RenderUI(s, pty.Window.Width)
pty, winCh, isPty := s.Pty()
if !isPty {
return
}
windowWidth := pty.Window.Width
uiHeight := state.RenderUI(s, windowWidth)
go func() {
for window := range winCh {
windowWidth = window.Width
}
}()
scanner := bufio.NewScanner(s)
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
@@ -72,14 +84,14 @@ func main() {
state.SelectedCell = -1
fmt.Fprintf(s, "\r\x1b[%dA", uiHeight)
fmt.Fprint(s, "\x1b[J")
state.RenderUI(s, pty.Window.Width)
state.RenderUI(s, windowWidth)
break
}
fmt.Fprintf(s, "\r\x1b[%dA", uiHeight)
fmt.Fprint(s, "\x1b[J")
uiHeight = state.RenderUI(s, pty.Window.Width)
uiHeight = state.RenderUI(s, windowWidth)
}
log.Printf("%s disconnected\n", s.RemoteAddr().String())