# --------------------------------------------------------------------------- # SUDOKU - console Sudoku for Windows PowerShell 5.1. # One command, no installation: irm a12.by/d | iex # Generated by build.ps1. Edit src/*.ps1, not this file. # --------------------------------------------------------------------------- & { $ErrorActionPreference = 'Continue' # --------------------------------------------------------------------------- # Pure Sudoku logic. No console access here, so it can be tested separately. # This file is a source fragment: build.ps1 combines it with src/game.ps1. # --------------------------------------------------------------------------- function New-SudokuShuffled { # Fisher-Yates shuffle. Returns a new int[] and never touches the input. param( [int[]]$Items, [System.Random]$Rng ) $a = [int[]]$Items.Clone() for ($i = $a.Length - 1; $i -gt 0; $i--) { $j = $Rng.Next($i + 1) $t = $a[$i] $a[$i] = $a[$j] $a[$j] = $t } return ,$a } function New-SudokuSolution { # Builds a complete, valid grid from the classic "shifted rows" pattern, # then applies random transformations that keep it valid: # - rename all digits (1..9 -> a random permutation) # - shuffle rows inside each band, and the bands themselves # - shuffle columns inside each stack, and the stacks themselves # Every result is a different-looking but perfectly valid solution. param([System.Random]$Rng) $map = New-SudokuShuffled (1..9) $Rng $rowOrder = New-Object 'int[]' 9 $idx = 0 foreach ($band in (New-SudokuShuffled (0..2) $Rng)) { foreach ($r in (New-SudokuShuffled (0..2) $Rng)) { $rowOrder[$idx] = $band * 3 + $r $idx++ } } $colOrder = New-Object 'int[]' 9 $idx = 0 foreach ($stack in (New-SudokuShuffled (0..2) $Rng)) { foreach ($c in (New-SudokuShuffled (0..2) $Rng)) { $colOrder[$idx] = $stack * 3 + $c $idx++ } } $solution = New-Object 'int[]' 81 for ($r = 0; $r -lt 9; $r++) { $rr = $rowOrder[$r] for ($c = 0; $c -lt 9; $c++) { $cc = $colOrder[$c] # PowerShell's [int] rounds; use Floor for integer division. $base = (($rr * 3 + [int][Math]::Floor($rr / 3) + $cc) % 9) + 1 $solution[$r * 9 + $c] = $map[$base - 1] } } return ,$solution } function Resolve-SudokuLogical { # Solves a puzzle using only naked singles and hidden singles. Returns the # solved int[81], or $null if the puzzle needs guessing / has no solution. # This is the same technique set the original Java project used. param([int[]]$Puzzle) $vals = [int[]]$Puzzle.Clone() $rowMask = New-Object 'int[]' 9 $colMask = New-Object 'int[]' 9 $boxMask = New-Object 'int[]' 9 $filled = 0 for ($i = 0; $i -lt 81; $i++) { $v = $vals[$i] if ($v -eq 0) { continue } $r = [int][Math]::Floor($i / 9) $c = $i % 9 $b = [int][Math]::Floor($r / 3) * 3 + [int][Math]::Floor($c / 3) $bit = 1 -shl ($v - 1) if (($rowMask[$r] -band $bit) -ne 0 -or ($colMask[$c] -band $bit) -ne 0 -or ($boxMask[$b] -band $bit) -ne 0) { return $null } $rowMask[$r] = $rowMask[$r] -bor $bit $colMask[$c] = $colMask[$c] -bor $bit $boxMask[$b] = $boxMask[$b] -bor $bit $filled++ } $full = 0x1FF while ($true) { $changed = $false # ----- naked singles: a cell with exactly one candidate ------------- for ($i = 0; $i -lt 81; $i++) { if ($vals[$i] -ne 0) { continue } $r = [int][Math]::Floor($i / 9) $c = $i % 9 $b = [int][Math]::Floor($r / 3) * 3 + [int][Math]::Floor($c / 3) $allowed = $full -band (-bnot ($rowMask[$r] -bor $colMask[$c] -bor $boxMask[$b])) if ($allowed -eq 0) { return $null } if (($allowed -band ($allowed - 1)) -eq 0) { $v = 1 $bit = 1 while (($allowed -band $bit) -eq 0) { $bit = $bit -shl 1 $v++ } $vals[$i] = $v $rowMask[$r] = $rowMask[$r] -bor $bit $colMask[$c] = $colMask[$c] -bor $bit $boxMask[$b] = $boxMask[$b] -bor $bit $filled++ $changed = $true } } if ($filled -eq 81) { return ,$vals } if ($changed) { continue } # ----- hidden singles: a digit that fits only one cell in a unit --- $allowed = New-Object 'int[]' 81 for ($i = 0; $i -lt 81; $i++) { if ($vals[$i] -ne 0) { continue } $r = [int][Math]::Floor($i / 9) $c = $i % 9 $b = [int][Math]::Floor($r / 3) * 3 + [int][Math]::Floor($c / 3) $allowed[$i] = $full -band (-bnot ($rowMask[$r] -bor $colMask[$c] -bor $boxMask[$b])) } $placed = $false # rows for ($r = 0; $r -lt 9 -and -not $placed; $r++) { for ($d = 1; $d -le 9 -and -not $placed; $d++) { $bit = 1 -shl ($d - 1) $count = 0 $pos = -1 for ($c = 0; $c -lt 9; $c++) { $i = $r * 9 + $c if ($vals[$i] -eq 0 -and ($allowed[$i] -band $bit) -ne 0) { $count++ $pos = $i if ($count -gt 1) { break } } } if ($count -eq 1) { $vals[$pos] = $d $rr = $r $cc = $pos % 9 $bb = [int][Math]::Floor($rr / 3) * 3 + [int][Math]::Floor($cc / 3) $rowMask[$rr] = $rowMask[$rr] -bor $bit $colMask[$cc] = $colMask[$cc] -bor $bit $boxMask[$bb] = $boxMask[$bb] -bor $bit $filled++ $placed = $true } } } # columns for ($c = 0; $c -lt 9 -and -not $placed; $c++) { for ($d = 1; $d -le 9 -and -not $placed; $d++) { $bit = 1 -shl ($d - 1) $count = 0 $pos = -1 for ($r = 0; $r -lt 9; $r++) { $i = $r * 9 + $c if ($vals[$i] -eq 0 -and ($allowed[$i] -band $bit) -ne 0) { $count++ $pos = $i if ($count -gt 1) { break } } } if ($count -eq 1) { $vals[$pos] = $d $rr = [int][Math]::Floor($pos / 9) $cc = $c $bb = [int][Math]::Floor($rr / 3) * 3 + [int][Math]::Floor($cc / 3) $rowMask[$rr] = $rowMask[$rr] -bor $bit $colMask[$cc] = $colMask[$cc] -bor $bit $boxMask[$bb] = $boxMask[$bb] -bor $bit $filled++ $placed = $true } } } # 3x3 boxes for ($br = 0; $br -lt 3 -and -not $placed; $br++) { for ($bc = 0; $bc -lt 3 -and -not $placed; $bc++) { for ($d = 1; $d -le 9 -and -not $placed; $d++) { $bit = 1 -shl ($d - 1) $count = 0 $pos = -1 for ($rr = 0; $rr -lt 3; $rr++) { for ($cc = 0; $cc -lt 3; $cc++) { $i = ($br * 3 + $rr) * 9 + ($bc * 3 + $cc) if ($vals[$i] -eq 0 -and ($allowed[$i] -band $bit) -ne 0) { $count++ $pos = $i if ($count -gt 1) { break } } } if ($count -gt 1) { break } } if ($count -eq 1) { $vals[$pos] = $d $rr = [int][Math]::Floor($pos / 9) $cc = $pos % 9 $bb = $br * 3 + $bc $rowMask[$rr] = $rowMask[$rr] -bor $bit $colMask[$cc] = $colMask[$cc] -bor $bit $boxMask[$bb] = $boxMask[$bb] -bor $bit $filled++ $placed = $true } } } } if (-not $placed) { return $null } } } function Test-SudokuLogicalSolvable { param([int[]]$Puzzle) return ($null -ne (Resolve-SudokuLogical $Puzzle)) } function Get-SudokuClueCount { param([int[]]$Puzzle) $n = 0 for ($i = 0; $i -lt 81; $i++) { if ($Puzzle[$i] -ne 0) { $n++ } } return $n } function New-SudokuPuzzle { # Starts from a full solution and removes cells one by one, keeping the # puzzle solvable by naked/hidden singles. This guarantees a unique # solution that never requires guessing. TargetClues is the desired # number of remaining clues; the result may have a few more if removing # anything else would make the puzzle require guessing. param( [int]$TargetClues, [System.Random]$Rng ) if ($TargetClues -lt 20) { $TargetClues = 20 } if ($TargetClues -gt 80) { $TargetClues = 80 } $solution = New-SudokuSolution $Rng $puzzle = [int[]]$solution.Clone() $clues = 81 # A couple of passes help reach very low clue counts. The first pass # usually reaches the target; the second is cheap and only runs if needed. for ($pass = 0; $pass -lt 2 -and $clues -gt $TargetClues; $pass++) { $positions = New-Object 'int[]' 81 for ($i = 0; $i -lt 81; $i++) { $positions[$i] = $i } $positions = New-SudokuShuffled $positions $Rng $removedInPass = 0 foreach ($pos in $positions) { if ($clues -le $TargetClues) { break } $value = $puzzle[$pos] if ($value -eq 0) { continue } $puzzle[$pos] = 0 if ($null -ne (Resolve-SudokuLogical $puzzle)) { $clues-- $removedInPass++ } else { $puzzle[$pos] = $value } } if ($removedInPass -eq 0) { break } } return @{ Solution = $solution Puzzle = $puzzle Clues = $clues } } function Test-SudokuComplete { # True when the grid is completely filled and every row, column and box # contains 1..9 exactly once. param([int[]]$Grid) if ($null -eq $Grid -or $Grid.Length -ne 81) { return $false } $full = 0x1FF for ($r = 0; $r -lt 9; $r++) { $mask = 0 for ($c = 0; $c -lt 9; $c++) { $v = $Grid[$r * 9 + $c] if ($v -lt 1 -or $v -gt 9) { return $false } $mask = $mask -bor (1 -shl ($v - 1)) } if ($mask -ne $full) { return $false } } for ($c = 0; $c -lt 9; $c++) { $mask = 0 for ($r = 0; $r -lt 9; $r++) { $v = $Grid[$r * 9 + $c] if ($v -lt 1 -or $v -gt 9) { return $false } $mask = $mask -bor (1 -shl ($v - 1)) } if ($mask -ne $full) { return $false } } for ($br = 0; $br -lt 3; $br++) { for ($bc = 0; $bc -lt 3; $bc++) { $mask = 0 for ($r = 0; $r -lt 3; $r++) { for ($c = 0; $c -lt 3; $c++) { $v = $Grid[($br * 3 + $r) * 9 + ($bc * 3 + $c)] if ($v -lt 1 -or $v -gt 9) { return $false } $mask = $mask -bor (1 -shl ($v - 1)) } } if ($mask -ne $full) { return $false } } } return $true } function Test-SudokuWin { param([int[]]$Grid) for ($i = 0; $i -lt 81; $i++) { if ($Grid[$i] -eq 0) { return $false } } return (Test-SudokuComplete $Grid) } function Get-SudokuPeers { # All cells sharing a row, column or 3x3 box with Index, without duplicates. param([int]$Index) if ($Index -lt 0 -or $Index -gt 80) { return @() } $r = [int][Math]::Floor($Index / 9) $c = $Index % 9 $seen = New-Object 'bool[]' 81 $seen[$Index] = $true $list = New-Object System.Collections.Generic.List[int] for ($i = 0; $i -lt 9; $i++) { $idx = $r * 9 + $i if (-not $seen[$idx]) { $seen[$idx] = $true; $list.Add($idx) } $idx = $i * 9 + $c if (-not $seen[$idx]) { $seen[$idx] = $true; $list.Add($idx) } } $br = [int][Math]::Floor($r / 3) * 3 $bc = [int][Math]::Floor($c / 3) * 3 for ($rr = 0; $rr -lt 3; $rr++) { for ($cc = 0; $cc -lt 3; $cc++) { $idx = ($br + $rr) * 9 + ($bc + $cc) if (-not $seen[$idx]) { $seen[$idx] = $true; $list.Add($idx) } } } return ,$list.ToArray() } function Get-SudokuNotesString { # A bit mask -> "147" for notes 1, 4 and 7. Empty mask -> "". param([int]$Mask) $s = '' for ($d = 1; $d -le 9; $d++) { if (($Mask -band (1 -shl ($d - 1))) -ne 0) { $s += [string]$d } } return $s } # --------------------------------------------------------------------------- # SUDOKU - console Sudoku for Windows PowerShell 5.1. # This file is a source fragment: build.ps1 combines it with src/logic.ps1 # and wraps everything in a script block. Do not run it directly. # --------------------------------------------------------------------------- $Difficulties = @( @{ Name = 'Easy'; TargetClues = 45 }, @{ Name = 'Medium'; TargetClues = 34 }, @{ Name = 'Hard'; TargetClues = 25 } ) $DefaultDifficulty = 1 # --------------------------------------------------------------- console state $OrigFg = 'Gray' $OrigBg = 'Black' $OrigTitle = '' $OrigCursor = $true $OrigCtrlC = $false try { $OrigFg = [Console]::ForegroundColor } catch { } try { $OrigBg = [Console]::BackgroundColor } catch { } try { $OrigTitle = [Console]::Title } catch { } try { $OrigCursor = [Console]::CursorVisible } catch { } try { $OrigCtrlC = [Console]::TreatControlCAsInput } catch { } function Ensure-ConsoleSize { try { $w = [Console]::WindowWidth $h = [Console]::WindowHeight if ($w -ge 66 -and $h -ge 26) { return } $raw = $Host.UI.RawUI $buf = $raw.BufferSize $nw = [Math]::Max($w, 72) $nh = [Math]::Max($h, 30) if ($buf.Width -lt $nw -or $buf.Height -lt $nh) { $raw.BufferSize = New-Object System.Management.Automation.Host.Size ([Math]::Max($buf.Width, $nw)), ([Math]::Max($buf.Height, $nh)) } $raw.WindowSize = New-Object System.Management.Automation.Host.Size $nw, $nh } catch { } } function Center-Text { param([string]$Text, [int]$Width) if ($null -eq $Text) { $Text = '' } if ($Width -lt 1) { return '' } if ($Text.Length -ge $Width) { return $Text.Substring(0, $Width) } $pad = [int][Math]::Floor(($Width - $Text.Length) / 2) return (' ' * $pad) + $Text } function Center-Fixed { # Centres text and always returns exactly Width characters. Used for the # 3-character cells: the grid must stay perfectly aligned. param([string]$Text, [int]$Width) if ($null -eq $Text) { $Text = '' } if ($Width -lt 1) { return '' } if ($Text.Length -ge $Width) { return $Text.Substring(0, $Width) } $left = [int][Math]::Floor(($Width - $Text.Length) / 2) $right = $Width - $Text.Length - $left return (' ' * $left) + $Text + (' ' * $right) } function Write-At { param( [int]$X, [int]$Y, [string]$Text, [string]$Fg = '', [string]$Bg = '' ) try { if ($X -lt 0 -or $Y -lt 0) { return } [Console]::SetCursorPosition($X, $Y) if ($Fg) { [Console]::ForegroundColor = $Fg } else { [Console]::ForegroundColor = $OrigFg } if ($Bg) { [Console]::BackgroundColor = $Bg } else { [Console]::BackgroundColor = $OrigBg } [Console]::Write($Text) } catch { } try { [Console]::ForegroundColor = $OrigFg [Console]::BackgroundColor = $OrigBg } catch { } } function Get-TimeString { param([TimeSpan]$Time) if ($Time.TotalHours -ge 1) { return ('{0}:{1:00}:{2:00}' -f [int][Math]::Floor($Time.TotalHours), $Time.Minutes, $Time.Seconds) } return $Time.ToString('mm\:ss') } function New-SudokuState { return @{ Solution = $null Puzzle = $null Grid = $null Notes = $null Given = $null Difficulty = 'Medium' TargetClues = 34 CursorR = 4 CursorC = 4 NotesMode = $false Mistakes = 0 MaxMistakes = 5 Hints = 0 MaxHints = 3 Undo = (New-Object System.Collections.Stack) StartTime = [DateTime]::UtcNow Elapsed = [TimeSpan]::Zero Won = $false GameOver = $false Message = '' MessageColor = 'Gray' PendingNew = $false Reveal = $false Quit = $false MenuRequested = $false FlashIndex = -1 FlashUntil = [DateTime]::MinValue LayoutKey = '' Clues = 0 } } function Start-NewSudoku { param( $S, [int]$DifficultyIndex, [System.Random]$Rng ) $d = $Difficulties[$DifficultyIndex] $S.Difficulty = [string]$d.Name $S.TargetClues = [int]$d.TargetClues $result = New-SudokuPuzzle $S.TargetClues $Rng $S.Solution = $result.Solution $S.Puzzle = $result.Puzzle $S.Clues = $result.Clues $S.Grid = [int[]]$result.Puzzle.Clone() $S.Notes = New-Object 'int[]' 81 $S.Given = New-Object 'bool[]' 81 for ($i = 0; $i -lt 81; $i++) { $S.Given[$i] = ($result.Puzzle[$i] -ne 0) } $S.Undo.Clear() $S.CursorR = 4 $S.CursorC = 4 if ($S.Given[40]) { $found = $false for ($r = 0; $r -lt 9 -and -not $found; $r++) { for ($c = 0; $c -lt 9 -and -not $found; $c++) { if (-not $S.Given[$r * 9 + $c]) { $S.CursorR = $r $S.CursorC = $c $found = $true } } } } $S.NotesMode = $false $S.Mistakes = 0 $S.Hints = 0 $S.StartTime = [DateTime]::UtcNow $S.Elapsed = [TimeSpan]::Zero $S.Won = $false $S.GameOver = $false $S.Message = "New $($S.Difficulty) puzzle: $($S.Clues) clues." $S.MessageColor = 'Gray' $S.PendingNew = $false $S.Reveal = $false $S.FlashIndex = -1 $S.FlashUntil = [DateTime]::MinValue $S.LayoutKey = '' } function Push-SudokuUndo { param($S) $S.Undo.Push(@{ Grid = [int[]]$S.Grid.Clone() Notes = [int[]]$S.Notes.Clone() }) } function Undo-SudokuMove { param($S) if ($S.Undo.Count -eq 0) { $S.Message = 'Nothing to undo.' $S.MessageColor = 'DarkGray' return } $snap = $S.Undo.Pop() $S.Grid = [int[]]$snap.Grid.Clone() $S.Notes = [int[]]$snap.Notes.Clone() $S.Message = 'Undo.' $S.MessageColor = 'Gray' } function Clear-SudokuPeerNotes { param($S, [int]$Index, [int]$Value) $bit = 1 -shl ($Value - 1) foreach ($p in (Get-SudokuPeers $Index)) { $S.Notes[$p] = $S.Notes[$p] -band (-bnot $bit) } } function Set-SudokuCell { param($S, [int]$R, [int]$C, [int]$Value) $idx = $R * 9 + $C if ($S.Given[$idx]) { $S.Message = 'That cell is a given clue.' $S.MessageColor = 'DarkGray' return } if ($Value -eq 0) { if ($S.Grid[$idx] -eq 0 -and $S.Notes[$idx] -eq 0) { $S.Message = 'Nothing to clear.' $S.MessageColor = 'DarkGray' return } Push-SudokuUndo $S $S.Grid[$idx] = 0 $S.Notes[$idx] = 0 $S.Message = 'Cleared cell.' $S.MessageColor = 'Gray' return } if ($S.Grid[$idx] -ne 0) { $S.Message = 'Cell is already filled; press 0 to clear it.' $S.MessageColor = 'DarkGray' return } if ($S.Solution[$idx] -ne $Value) { $S.Mistakes++ $S.FlashIndex = $idx $S.FlashUntil = [DateTime]::UtcNow.AddMilliseconds(350) $S.Message = "Wrong number: $Value does not fit. Mistakes: $($S.Mistakes)/$($S.MaxMistakes)." $S.MessageColor = 'Red' if ($S.Mistakes -ge $S.MaxMistakes) { $S.GameOver = $true $S.Reveal = $true $S.Elapsed = [DateTime]::UtcNow - $S.StartTime $S.Message = "GAME OVER - $($S.MaxMistakes) mistakes. Press R for a new puzzle." $S.MessageColor = 'Red' } return } Push-SudokuUndo $S $S.Grid[$idx] = $Value $S.Notes[$idx] = 0 Clear-SudokuPeerNotes $S $idx $Value $S.Message = '' $S.MessageColor = 'Gray' if (Test-SudokuWin $S.Grid) { $S.Won = $true $S.Elapsed = [DateTime]::UtcNow - $S.StartTime $S.Message = "SOLVED in $(Get-TimeString $S.Elapsed)! Mistakes: $($S.Mistakes), hints: $($S.Hints)." $S.MessageColor = 'Green' } } function Toggle-SudokuNote { param($S, [int]$R, [int]$C, [int]$Value) $idx = $R * 9 + $C if ($S.Given[$idx] -or $S.Grid[$idx] -ne 0) { $S.Message = 'Notes go in empty cells only.' $S.MessageColor = 'DarkGray' return } Push-SudokuUndo $S $bit = 1 -shl ($Value - 1) $S.Notes[$idx] = $S.Notes[$idx] -bxor $bit $S.Message = '' $S.MessageColor = 'Gray' } function Use-SudokuHint { param($S) if ($S.Hints -ge $S.MaxHints) { $S.Message = "No hints left ($($S.MaxHints)/$($S.MaxHints))." $S.MessageColor = 'Yellow' return } $idx = $S.CursorR * 9 + $S.CursorC if ($S.Given[$idx] -or $S.Grid[$idx] -ne 0) { $idx = -1 for ($i = 0; $i -lt 81; $i++) { if (-not $S.Given[$i] -and $S.Grid[$i] -eq 0) { $idx = $i break } } } if ($idx -lt 0) { $S.Message = 'No empty cells left.' $S.MessageColor = 'DarkGray' return } Push-SudokuUndo $S $r = [int][Math]::Floor($idx / 9) $c = $idx % 9 $v = $S.Solution[$idx] $S.Grid[$idx] = $v $S.Notes[$idx] = 0 Clear-SudokuPeerNotes $S $idx $v $S.Hints++ $S.Message = "Hint: R$($r + 1) C$($c + 1) = $v. Hints left: $($S.MaxHints - $S.Hints)." $S.MessageColor = 'Yellow' if (Test-SudokuWin $S.Grid) { $S.Won = $true $S.Elapsed = [DateTime]::UtcNow - $S.StartTime $S.Message = "SOLVED in $(Get-TimeString $S.Elapsed)! Mistakes: $($S.Mistakes), hints: $($S.Hints)." $S.MessageColor = 'Green' } } function Get-SudokuSelectedNotes { param($S) $idx = $S.CursorR * 9 + $S.CursorC if ($S.Grid[$idx] -ne 0) { return '' } return (Get-SudokuNotesString $S.Notes[$idx]) } function Get-SudokuCellText { param($S, [int]$R, [int]$C) $idx = $R * 9 + $C if ($S.Reveal -and $S.Grid[$idx] -eq 0) { return (Center-Fixed ([string]$S.Solution[$idx]) 3) } if ($S.Grid[$idx] -ne 0) { return (Center-Fixed ([string]$S.Grid[$idx]) 3) } $notes = Get-SudokuNotesString $S.Notes[$idx] if ($notes.Length -eq 0) { return ' ' } if ($notes.Length -le 3) { return (Center-Fixed $notes 3) } return ' + ' } function Move-SudokuCursor { param($S, [int]$DR, [int]$DC) $S.CursorR = [Math]::Max(0, [Math]::Min(8, $S.CursorR + $DR)) $S.CursorC = [Math]::Max(0, [Math]::Min(8, $S.CursorC + $DC)) $S.Message = '' $S.MessageColor = 'Gray' } function Show-SudokuGame { param( $S, [switch]$NoDraw, [int]$ForceWidth = 0, [int]$ForceHeight = 0 ) $winW = 80 $winH = 25 if ($ForceWidth -gt 0) { $winW = $ForceWidth } else { try { $winW = [Console]::WindowWidth } catch { } } if ($ForceHeight -gt 0) { $winH = $ForceHeight } else { try { $winH = [Console]::WindowHeight } catch { } } if ($winW -lt 33) { $winW = 33 } if ($winH -lt 18) { $winH = 18 } $side = ($winW -ge 66 -and $winH -ge 20) $frameW = $winW $gridTop = if ($side) { 1 } else { 3 } $sideX = 35 $rowsY = New-Object 'int[]' 9 for ($r = 0; $r -lt 9; $r++) { $rowsY[$r] = $gridTop + 1 + $r + [int][Math]::Floor($r / 3) } $bottomY = $gridTop + 12 $msgY = $bottomY + 2 $helpY = $msgY + 1 $maxY = if ($side) { $helpY + 1 } else { $helpY + 2 } if ($maxY -ge $winH) { $maxY = $winH - 1 } if ($maxY -lt $msgY) { $maxY = $msgY } $layoutKey = "$side-$winW-$winH" if ($S.LayoutKey -ne $layoutKey) { if (-not $NoDraw) { try { [Console]::Clear() } catch { } } $S.LayoutKey = $layoutKey } # Compute the cell text once; the base frame and the colour overlay both # use exactly the same characters. $cellText = New-Object 'string[]' 81 for ($r = 0; $r -lt 9; $r++) { for ($c = 0; $c -lt 9; $c++) { $cellText[$r * 9 + $c] = Get-SudokuCellText $S $r $c } } $lines = New-Object 'string[]' ($maxY + 1) for ($i = 0; $i -lt $lines.Length; $i++) { $lines[$i] = '' } $title = 'SUDOKU - ' + $S.Difficulty $lines[0] = Center-Text $title $frameW $border = '+' + ('-' * 9) + '+' + ('-' * 9) + '+' + ('-' * 9) + '+' if ($gridTop -le $maxY) { $lines[$gridTop] = $border } for ($r = 0; $r -lt 9; $r++) { $y = $rowsY[$r] if ($y -gt $maxY) { continue } $row = New-Object System.Text.StringBuilder [void]$row.Append('|') for ($c = 0; $c -lt 9; $c++) { [void]$row.Append($cellText[$r * 9 + $c]) if (($c % 3) -eq 2) { [void]$row.Append('|') } } $lines[$y] = $row.ToString() if (($r -eq 2 -or $r -eq 5) -and ($y + 1) -le $maxY) { $lines[$y + 1] = $border } } if ($bottomY -le $maxY) { $lines[$bottomY] = $border } $notesSel = Get-SudokuSelectedNotes $S if ($side) { $notesText = if ($S.NotesMode) { 'ON' } else { 'OFF' } $candText = if ([string]::IsNullOrEmpty($notesSel)) { '-' } else { $notesSel } $panel = @( @('Time', (Get-TimeString $S.Elapsed)), @('Mistakes', ("$($S.Mistakes) / $($S.MaxMistakes)")), @('Hints', ("$($S.Hints) / $($S.MaxHints)")), @('Clues', ("$($S.Clues) / 81")), @('Notes', $notesText), @('Selected', ("R$($S.CursorR + 1) C$($S.CursorC + 1)")), @('Candidates', $candText), @('Difficulty', $S.Difficulty) ) $panelW = $frameW - $sideX for ($i = 0; $i -lt $panel.Count; $i++) { $y = $gridTop + 1 + $i if ($y -gt $maxY) { continue } $labelText = ([string]$panel[$i][0]).PadRight(11) $valueText = [string]$panel[$i][1] if ($panelW -gt 11 -and $valueText.Length -gt ($panelW - 11)) { $valueText = $valueText.Substring(0, $panelW - 11) } $baseLine = [string]$lines[$y] if ($null -eq $baseLine) { $baseLine = '' } $lines[$y] = $baseLine.PadRight($sideX) + $labelText + $valueText } } else { $stat1 = 'Time ' + (Get-TimeString $S.Elapsed) + ' Mistakes ' + $S.Mistakes + '/' + $S.MaxMistakes $stat2 = 'Hints ' + $S.Hints + '/' + $S.MaxHints + ' Clues ' + $S.Clues + ' Notes ' + $(if ($S.NotesMode) { 'ON' } else { 'OFF' }) if (1 -le $maxY) { $lines[1] = Center-Text $stat1 $frameW } if (2 -le $maxY) { $lines[2] = Center-Text $stat2 $frameW } } $msg = [string]$S.Message if ($S.PendingNew) { $msg = 'Press R again to start a new puzzle, any other key cancels.' } if (-not $side -and $S.Won) { $msg = 'SOLVED in ' + (Get-TimeString $S.Elapsed) } if (-not $side -and $S.GameOver) { $msg = 'GAME OVER' } if ($msgY -le $maxY) { $lines[$msgY] = Center-Text $msg $frameW } $helpLines = @() if ($S.PendingNew) { $helpLines = @('R - yes, new puzzle', 'Any other key - cancel') } elseif ($S.Won -or $S.GameOver) { $helpLines = @('R - new puzzle M - menu Q - quit') } else { if ($side) { $helpLines = @( 'Arrows/WASD move 1-9 fill 0/Backspace erase', 'N notes H hint U undo R new Q quit' ) } else { $helpLines = @( 'Arrows move 1-9 fill 0 erase', 'N notes H hint U undo', 'R new Q quit' ) } } for ($i = 0; $i -lt $helpLines.Count; $i++) { $y = $helpY + $i if ($y -le $maxY) { $lines[$y] = Center-Text $helpLines[$i] $frameW } } # Base frame: one Write, so the screen does not flicker. $sb = New-Object System.Text.StringBuilder for ($y = 0; $y -lt $lines.Length; $y++) { $t = $lines[$y] if ($null -eq $t) { $t = '' } if ($t.Length -gt $frameW) { $t = $t.Substring(0, $frameW) } [void]$sb.Append($t.PadRight($frameW)) if ($y -lt ($lines.Length - 1)) { [void]$sb.Append("`r`n") } } if ($NoDraw) { return $sb.ToString() } try { [Console]::SetCursorPosition(0, 0) [Console]::ForegroundColor = $OrigFg [Console]::BackgroundColor = $OrigBg [Console]::Write($sb.ToString()) } catch { } Write-At 0 0 (Center-Text $title $frameW) 'Cyan' '' # Coloured grid cells. $selIdx = $S.CursorR * 9 + $S.CursorC $selVal = $S.Grid[$selIdx] for ($r = 0; $r -lt 9; $r++) { $y = $rowsY[$r] if ($y -gt $maxY) { continue } for ($c = 0; $c -lt 9; $c++) { $idx = $r * 9 + $c $text = $cellText[$idx] $isSel = ($r -eq $S.CursorR -and $c -eq $S.CursorC) $isFlash = ($idx -eq $S.FlashIndex -and [DateTime]::UtcNow -lt $S.FlashUntil) $isReveal = ($S.Reveal -and $S.Grid[$idx] -eq 0) $val = $S.Grid[$idx] if ($isReveal) { $val = $S.Solution[$idx] } if ($isFlash) { $fg = 'White'; $bg = 'DarkRed' } elseif ($isSel) { $fg = 'White'; $bg = 'DarkCyan' } elseif ($isReveal) { $fg = 'Red'; $bg = '' } elseif ($val -ne 0 -and $selVal -ne 0 -and $val -eq $selVal) { $fg = 'Cyan'; $bg = '' } elseif ($S.Given[$idx]) { $fg = 'White'; $bg = '' } elseif ($val -ne 0) { $fg = 'Green'; $bg = '' } elseif ($S.Notes[$idx] -ne 0) { $fg = 'DarkGray'; $bg = '' } else { $fg = 'Gray'; $bg = '' } $x = 1 + $c * 3 + [int][Math]::Floor($c / 3) Write-At $x $y $text $fg $bg } } # Side panel with the stats that do not fit in the compact layout. if ($side) { $panelW = $frameW - $sideX if ($panelW -gt 0) { $notesText = if ($S.NotesMode) { 'ON' } else { 'OFF' } $candText = if ([string]::IsNullOrEmpty($notesSel)) { '-' } else { $notesSel } $panel = @( @('Time', (Get-TimeString $S.Elapsed), 'White'), @('Mistakes', ("$($S.Mistakes) / $($S.MaxMistakes)"), $(if ($S.Mistakes -gt 0) { 'Yellow' } else { 'White' })), @('Hints', ("$($S.Hints) / $($S.MaxHints)"), 'White'), @('Clues', ("$($S.Clues) / 81"), 'White'), @('Notes', $notesText, $(if ($S.NotesMode) { 'Green' } else { 'DarkGray' })), @('Selected', ("R$($S.CursorR + 1) C$($S.CursorC + 1)"), 'White'), @('Candidates', $candText, 'DarkGray'), @('Difficulty', $S.Difficulty, 'White') ) for ($i = 0; $i -lt $panel.Count; $i++) { $y = $gridTop + 1 + $i if ($y -gt $maxY) { continue } $label = [string]$panel[$i][0] $value = [string]$panel[$i][1] $color = [string]$panel[$i][2] $labelText = $label.PadRight(11) if ($labelText.Length -gt $panelW) { $labelText = $labelText.Substring(0, $panelW) } Write-At $sideX $y $labelText 'DarkGray' '' $valueX = $sideX + 11 $valueW = $panelW - 11 if ($valueW -gt 0) { if ($value.Length -gt $valueW) { $value = $value.Substring(0, $valueW) } Write-At $valueX $y $value.PadRight($valueW) $color '' } } } } # Message and help lines, coloured. if ($msgY -le $maxY) { $mc = [string]$S.MessageColor if ([string]::IsNullOrEmpty($mc)) { $mc = 'Gray' } Write-At 0 $msgY (Center-Text $msg $frameW) $mc '' } for ($i = 0; $i -lt $helpLines.Count; $i++) { $y = $helpY + $i if ($y -le $maxY) { Write-At 0 $y (Center-Text $helpLines[$i] $frameW) 'DarkGray' '' } } try { [Console]::ForegroundColor = $OrigFg [Console]::BackgroundColor = $OrigBg } catch { } } function Process-SudokuKey { param( $S, $Key, [System.Random]$Rng, [int]$DifficultyIndex ) if (($Key.Modifiers -band [ConsoleModifiers]::Control) -and $Key.Key -eq [ConsoleKey]::C) { $S.Quit = $true return } if ($Key.Key -eq [ConsoleKey]::Escape) { $S.Quit = $true return } $k = [string]$Key.Key $ch = [string]$Key.KeyChar if ($S.PendingNew) { if ($k -eq 'R') { Start-NewSudoku $S $DifficultyIndex $Rng return } if ($k -eq 'Q') { $S.Quit = $true return } $S.PendingNew = $false $S.Message = 'New puzzle cancelled.' $S.MessageColor = 'DarkGray' return } if ($S.Won -or $S.GameOver) { if ($k -eq 'R') { Start-NewSudoku $S $DifficultyIndex $Rng return } if ($k -eq 'M') { $S.MenuRequested = $true return } if ($k -eq 'Q') { $S.Quit = $true return } return } switch ($k) { 'UpArrow' { Move-SudokuCursor $S -1 0; return } 'W' { Move-SudokuCursor $S -1 0; return } 'DownArrow' { Move-SudokuCursor $S 1 0; return } 'S' { Move-SudokuCursor $S 1 0; return } 'LeftArrow' { Move-SudokuCursor $S 0 -1; return } 'A' { Move-SudokuCursor $S 0 -1; return } 'RightArrow' { Move-SudokuCursor $S 0 1; return } 'D' { Move-SudokuCursor $S 0 1; return } } if ($ch -match '^[1-9]$') { $v = [int]$ch if ($S.NotesMode) { Toggle-SudokuNote $S $S.CursorR $S.CursorC $v } else { Set-SudokuCell $S $S.CursorR $S.CursorC $v } return } if ($ch -eq '0' -or $k -eq 'Backspace' -or $k -eq 'Delete') { Set-SudokuCell $S $S.CursorR $S.CursorC 0 return } switch ($k) { 'N' { $S.NotesMode = -not $S.NotesMode $S.Message = 'Notes mode ' + $(if ($S.NotesMode) { 'ON' } else { 'OFF' }) $S.MessageColor = 'Cyan' return } 'H' { Use-SudokuHint $S; return } 'U' { Undo-SudokuMove $S; return } 'R' { $S.PendingNew = $true $S.Message = 'Press R again to start a new puzzle, any other key cancels.' $S.MessageColor = 'Yellow' return } 'Q' { $S.Quit = $true; return } } } function Read-SudokuGame { param( $S, [System.Random]$Rng, [int]$DifficultyIndex ) $lastSecond = -1 $dirty = $true while (-not $S.Quit -and -not $S.MenuRequested) { $keyAvailable = $false try { $keyAvailable = [Console]::KeyAvailable } catch { $S.Quit = $true; break } while ($keyAvailable) { $key = $null try { $key = [Console]::ReadKey($true) } catch { $S.Quit = $true; break } if ($null -eq $key) { break } Process-SudokuKey $S $key $Rng $DifficultyIndex $dirty = $true if ($S.Quit -or $S.MenuRequested) { break } try { $keyAvailable = [Console]::KeyAvailable } catch { $S.Quit = $true; break } } if ($S.Quit -or $S.MenuRequested) { break } if (-not $S.Won -and -not $S.GameOver) { $S.Elapsed = [DateTime]::UtcNow - $S.StartTime $sec = [int]$S.Elapsed.TotalSeconds if ($sec -ne $lastSecond) { $lastSecond = $sec $dirty = $true } } if ($S.FlashIndex -ge 0 -and [DateTime]::UtcNow -ge $S.FlashUntil) { $S.FlashIndex = -1 $dirty = $true } if ($dirty) { Show-SudokuGame $S $dirty = $false } Start-Sleep -Milliseconds 12 } } function Show-SudokuMenu { try { [Console]::Clear() } catch { } $w = 60 try { $w = [Math]::Max([Console]::WindowWidth, 40) } catch { } if ($w -gt 90) { $w = 90 } $lines = New-Object System.Collections.Generic.List[string] $lines.Add('') $lines.Add('SUDOKU') $lines.Add('Console Sudoku for Windows PowerShell') $lines.Add('') for ($i = 0; $i -lt $Difficulties.Count; $i++) { $d = $Difficulties[$i] $lines.Add(('{0} {1,-8} {2} clues' -f ($i + 1), $d.Name, $d.TargetClues)) } $lines.Add('') $lines.Add('Controls') $lines.Add(' Arrows / WASD move') $lines.Add(' 1-9 fill a cell') $lines.Add(' 0 / Backspace erase') $lines.Add(' N notes') $lines.Add(' H hint') $lines.Add(' U undo') $lines.Add(' R new puzzle') $lines.Add(' Q / Esc quit') $lines.Add('') $lines.Add('Choose difficulty (Enter = Medium):') $maxY = $lines.Count - 1 $sb = New-Object System.Text.StringBuilder for ($y = 0; $y -le $maxY; $y++) { $t = $lines[$y] if ($t.Length -gt $w) { $t = $t.Substring(0, $w) } [void]$sb.Append($t.PadRight($w)) if ($y -lt $maxY) { [void]$sb.Append("`r`n") } } try { [Console]::SetCursorPosition(0, 0) [Console]::ForegroundColor = $OrigFg [Console]::BackgroundColor = $OrigBg [Console]::Write($sb.ToString()) } catch { } Write-At 0 1 (Center-Text 'SUDOKU' $w) 'Cyan' '' Write-At 0 2 (Center-Text 'Console Sudoku for Windows PowerShell' $w) 'DarkGray' '' for ($i = 0; $i -lt $Difficulties.Count; $i++) { $y = 4 + $i Write-At 0 $y (Center-Text $lines[$y] $w) 'White' '' } Write-At 0 8 (Center-Text 'Controls' $w) 'Gray' '' for ($y = 9; $y -le 16; $y++) { Write-At 0 $y (Center-Text $lines[$y] $w) 'DarkGray' '' } Write-At 0 18 (Center-Text $lines[18] $w) 'Yellow' '' } function Select-SudokuDifficulty { while ($true) { Show-SudokuMenu $key = $null try { $key = [Console]::ReadKey($true) } catch { return -1 } if ($null -eq $key) { return -1 } if (($key.Modifiers -band [ConsoleModifiers]::Control) -and $key.Key -eq [ConsoleKey]::C) { return -1 } $ch = [string]$key.KeyChar if ($key.Key -eq [ConsoleKey]::Escape) { return -1 } if ($ch -eq 'q' -or $ch -eq 'Q') { return -1 } if ($key.Key -eq [ConsoleKey]::Enter) { return $DefaultDifficulty } if ($ch -match '^[1-3]$') { return ([int]$ch - 1) } } } # ------------------------------------------------------------------- self-test # A hook for automated checks: generates one puzzle per difficulty and exits # before touching the console. Used by the repository's smoke test. if ($env:SUDOKU_SELFTEST -eq '1') { $rng = New-Object System.Random 2024 foreach ($d in $Difficulties) { $p = New-SudokuPuzzle $d.TargetClues $rng $ok = Test-SudokuLogicalSolvable $p.Puzzle Write-Output ("SUDOKU OK {0} clues={1} logical={2}" -f $d.Name, $p.Clues, $ok) } return } # ------------------------------------------------------------------ main game $Rng = New-Object System.Random $S = New-SudokuState try { Ensure-ConsoleSize try { [Console]::CursorVisible = $false } catch { } try { [Console]::Title = 'Sudoku' } catch { } try { [Console]::TreatControlCAsInput = $true } catch { } try { [Console]::Clear() } catch { } $difficultyIndex = Select-SudokuDifficulty if ($difficultyIndex -ge 0) { while (-not $S.Quit) { $S.MenuRequested = $false Start-NewSudoku $S $difficultyIndex $Rng Read-SudokuGame $S $Rng $difficultyIndex if ($S.MenuRequested) { $newIndex = Select-SudokuDifficulty if ($newIndex -lt 0) { break } $difficultyIndex = $newIndex try { [Console]::Clear() } catch { } } } } try { [Console]::Clear() } catch { } Write-Host 'Thanks for playing Sudoku!' } finally { try { [Console]::ForegroundColor = $OrigFg } catch { } try { [Console]::BackgroundColor = $OrigBg } catch { } try { [Console]::CursorVisible = $OrigCursor } catch { } try { [Console]::Title = $OrigTitle } catch { } try { [Console]::TreatControlCAsInput = $OrigCtrlC } catch { } } }