sourcegames/sudoku/play.xtl
1⍝!/usr/bin/env xetal
2⍝# Sudoku at the terminal. Choose a puzzle (1 easiest, 4 hardest), then
3⍝# type a row, a column and a digit ("1 3 4"; digit 0 clears the cell),
4⍝# h for a hint, c and a row and a column for a cell's candidates
5⍝# ("c 1 3"), s to see the solution, q to stop. The rules are those of
6⍝# SudokuGrid.xtl.
7ˢ⁼u̲se< "SudokuGrid"
8ᵖ⁼u̲se< "Play"
9said ← p̲rint! "SUDOKU: EVERY ROW, COLUMN AND BOX HOLDS 1 TO 9"
10
11ᵘp̲uzzle ← { @ →
12 n ← ᵖn̲umber "PUZZLE 1 TO 4 ?"
13 (n ≥ 1) ∧ n ≤ 4 ? n◆ ᵘp̲uzzle @
14}
15⍝# Why a move was refused (w from s:w_hy), as the player reads it.
16ᵘr̲efused ← { w d →
17 1 = w ? "ROW, COLUMN AND DIGIT ARE 1 TO 9 (DIGIT 0 CLEARS)"
18 2 = w ? "THAT CELL IS GIVEN"
19 @ f̲ormat< "{d} IS ALREADY IN THAT ROW, COLUMN OR BOX"
20}
21ᵘh̲int ← { s →
22 h ← ˢh̲int s
23 0 = f̲irst h ? "A DIGIT IS WRONG SOMEWHERE: THE GRID HAS NO SOLUTION"
24 @ f̲ormat< "TRY ROW {f_irst h} COLUMN {2 s_elect h}: {3 s_elect h}"
25}
26ᵘc̲ell ← { s rc →
27 k ← 1 + (9 × (f̲irst rc) − 1) + (2 s̲elect rc) − 1
28 @ f̲ormat< "ROW {f_irst rc} COLUMN {2 s_elect rc}: {w_here k s_elect s:l_egal s}"
29}
30⍝# A turn: the grid, then commands until a move changes it.
31ᵘt̲urn ← { s →
32 said ← p̲rint! ""
33 shown ← p̲rint! ˢv̲iew s
34 1 = ˢs̲tatus s ? "SOLVED!"
35 ᵘa̲sk s
36}
37⍝# A command: a letter (h, c, s, q) or a move, with its numbers. A
38⍝# hint, a cell's candidates or a refusal is printed and asked again.
39ᵘa̲sk ← { s →
40 line ← ᵖl̲ine "ROW COL DIGIT, H, C ROW COL, S OR Q ?"
41 v ← ᵖn̲umbersIn line
42 cmd ← (1 + "hHcCsSqQ" i̲ndexOf f̲irst line c̲at " ") d̲iv 2
43 4 = cmd ? "STOPPED"
44 3 = cmd ? ᵘs̲olution s
45 1 = cmd ? s ᵘs̲ay ᵘh̲int s
46 (2 = cmd) ∧ 2 = t̲ally v ? s ᵘs̲ay s ᵘc̲ell v
47 3 ≠ t̲ally v ? s ᵘs̲ay "TYPE A ROW, A COLUMN AND A DIGIT, OR A LETTER"
48 w ← s ˢw̲hy v
49 0 = w ? ᵘt̲urn s ˢm̲ove v
50 s ᵘs̲ay w ᵘr̲efused 3 s̲elect v
51}
52ᵘs̲ay ← { s text →
53 said ← p̲rint! text
54 ᵘa̲sk s
55}
56⍝# The puzzle's solution, and the game is over.
57ᵘs̲olution ← { s →
58 shown ← p̲rint! ˢs̲hown ˢs̲olve ˢg̲ivens s
59 "THE SOLUTION"
60}
61ᵘt̲urn ˢn̲ew ᵘp̲uzzle @
f̲ormat< expands to
"TRY ROW " c̲at (f̲ormat (f̲irst h)) c̲at " COLUMN " c̲at (f̲ormat (2 s̲elect h)) c̲at ": " c̲at (f̲ormat (3 s̲elect h))
f̲ormat< expands to
"ROW " c̲at (f̲ormat (f̲irst rc)) c̲at " COLUMN " c̲at (f̲ormat (2 s̲elect rc)) c̲at ": " c̲at (f̲ormat (w̲here k s̲elect ˢl̲egal s))