Object subclass: #LQSearch
 instanceVariableNames: 'size queens nextColumns row phase candidate conflicts state event note events attempts backtracks solutions allMode' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-EightQueens'!

Morph subclass: #LQApp
 instanceVariableNames: 'search board window running delay batch info noteLine phaseLine countLine probeLine solutionLine buttons probe viewing' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-EightQueens'!

Morph subclass: #LQBoard
 instanceVariableNames: 'app cellSize' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-EightQueens'!

SystemWindow subclass: #LQWindow
 instanceVariableNames: 'fixedExtent' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-EightQueens'!

!LQSearch methodsFor: 'tutorial'!
initialize
 super initialize. size := 8. allMode := false. self reset
! !

!LQSearch methodsFor: 'tutorial'!
reset
 queens := Array new: size withAll: 0. nextColumns := Array new: size withAll: 1.
 row := 1. phase := #candidate. candidate := nil. conflicts := #(). state := #ready.
 event := #ready. note := 'Ready: try columns left to right, one row at a time.'.
 events := 0. attempts := 0. backtracks := 0. solutions := OrderedCollection new
! !

!LQSearch methodsFor: 'tutorial'!
size
 ^ size
! !

!LQSearch methodsFor: 'tutorial'!
row
 ^ row
! !

!LQSearch methodsFor: 'tutorial'!
phase
 ^ phase
! !

!LQSearch methodsFor: 'tutorial'!
state
 ^ state
! !

!LQSearch methodsFor: 'tutorial'!
event
 ^ event
! !

!LQSearch methodsFor: 'tutorial'!
note
 ^ note
! !

!LQSearch methodsFor: 'tutorial'!
candidate
 ^ candidate
! !

!LQSearch methodsFor: 'tutorial'!
events
 ^ events
! !

!LQSearch methodsFor: 'tutorial'!
attempts
 ^ attempts
! !

!LQSearch methodsFor: 'tutorial'!
backtracks
 ^ backtracks
! !

!LQSearch methodsFor: 'tutorial'!
allMode
 ^ allMode
! !

!LQSearch methodsFor: 'tutorial'!
solutionCount
 ^ solutions size
! !

!LQSearch methodsFor: 'tutorial'!
queens
 ^ queens copy
! !

!LQSearch methodsFor: 'tutorial'!
nextColumns
 ^ nextColumns copy
! !

!LQSearch methodsFor: 'tutorial'!
conflicts
 ^ conflicts copy
! !

!LQSearch methodsFor: 'tutorial'!
validCell: cell
 ^ cell isPoint and: [cell x isInteger and: [cell y isInteger and: [(cell x between: 1 and: size) and: [cell y between: 1 and: size]]]]
! !

!LQSearch methodsFor: 'tutorial'!
queenAtRow: index
 ^ queens at: index
! !

!LQSearch methodsFor: 'tutorial'!
loadPrefix: columns
 | old |
 (columns isArray and: [columns size <= size and: [columns allSatisfy: [:c | c isInteger and: [c between: 1 and: size]]]]) ifFalse: [^ false].
 old := queens. queens := Array new: size withAll: 0.
 columns withIndexDo: [:c :r | queens at: r put: c].
 self legalPrefix ifFalse: [queens := old. ^ false].
 self reset. columns withIndexDo: [:c :r | queens at: r put: c. nextColumns at: r put: c + 1].
 row := columns size + 1. note := 'Loaded a legal prefix; remaining rows are empty.'. ^ true
! !

!LQSearch methodsFor: 'tutorial'!
attacks: firstCell with: secondCell
 ^ firstCell x = secondCell x
  or: [firstCell y = secondCell y
  or: [(firstCell x - secondCell x) abs = (firstCell y - secondCell y) abs]]
! !

!LQSearch methodsFor: 'tutorial'!
legalPrefix
 | gap |
 gap := false.
 1 to: size do: [:r |
  (queens at: r) = 0 ifTrue: [gap := true] ifFalse: [
   gap ifTrue: [^ false].
   1 to: r - 1 do: [:previous |
    (self attacks: (queens at: previous)@previous with: (queens at: r)@r) ifTrue: [^ false]]]].
 ^ true
! !

!LQSearch methodsFor: 'tutorial'!
conflictsAt: cell
 | result |
 result := OrderedCollection new.
 (self validCell: cell) ifFalse: [^ result asArray].
 1 to: size do: [:r | | q |
  q := (queens at: r)@r.
  ((queens at: r) > 0 and: [q ~= cell and: [self attacks: q with: cell]]) ifTrue: [result add: q]].
 ^ result asArray
! !

!LQSearch methodsFor: 'tutorial'!
safeAt: cell
 (self validCell: cell) ifFalse: [^ false].
 (queens at: cell y) = 0 ifFalse: [^ false].
 ^ (self conflictsAt: cell) isEmpty
! !

!LQApp methodsFor: 'tutorial'!
initialize
 super initialize. self extent: 964@668; color: (Color fromString: '#F1F5FA').
 search := LQSearch new. running := false. delay := 120. batch := 1. probe := nil. viewing := 0. buttons := Dictionary new.
 self addLabel: 'Eight Queens Lab' at: 24@10 size: 26.
 self addLabel: ('Checkpoint ', self stage printString, ' / 10 - ', self stageTitle) at: 26@47 size: 14.
 self addLabel: 'One queen per row. No shared columns. No shared diagonals.' at: 26@74 size: 12.
 self buildToolbar.
 board := LQBoard new app: self; position: self position + (22@152). self addMorph: board.
 self addLabel: 'SEARCH NOTEBOOK' at: 558@159 size: 15.
 info := self addLabel: '' at: 558@193 size: 13.
 phaseLine := self addLabel: '' at: 558@224 size: 12.
 countLine := self addLabel: '' at: 558@254 size: 12.
 self addLabel: 'Columns by row (0 means empty)' at: 558@297 size: 12.
 solutionLine := self addLabel: '' at: 558@326 size: 17.
 self addLabel: 'Green Q: placed  /  gold: candidate' at: 558@375 size: 12.
 self addLabel: 'Coral: conflict  /  orange: removed' at: 558@398 size: 12.
 self addLabel: 'Blue rays: cells attacked by a probe' at: 558@421 size: 12.
 probeLine := self addLabel: '' at: 558@463 size: 12.
 self addLabel: 'The model owns decisions and search history.' at: 558@506 size: 12.
 self addLabel: 'The board reads it; buttons send messages.' at: 558@529 size: 12.
 noteLine := self addLabel: '' at: 26@606 size: 12.
 self addLabel: 'Click a square to inspect attacks; probe clicks never move a queen.' at: 26@636 size: 11.
 self refresh
! !

!LQApp methodsFor: 'tutorial'!
addLabel: text at: point size: pointSize
 | label |
 label := StringMorph contents: text font: (TextStyle default fontOfSize: pointSize).
 label position: self position + point; color: (Color fromString: '#17334B').
 self addMorph: label. ^ label
! !

!LQApp methodsFor: 'tutorial'!
button: text at: point action: selector arguments: args
 | button |
 button := SimpleButtonMorph new label: text; target: self; actionSelector: selector; arguments: args; color: Color white; yourself.
 button position: self position + point. self addMorph: button. buttons at: text put: button. ^ button
! !

!LQApp methodsFor: 'tutorial'!
search
 ^ search
! !

!LQApp methodsFor: 'tutorial'!
board
 ^ board
! !

!LQApp methodsFor: 'tutorial'!
window
 ^ window
! !

!LQApp methodsFor: 'tutorial'!
running
 ^ running
! !

!LQApp methodsFor: 'tutorial'!
delay
 ^ delay
! !

!LQApp methodsFor: 'tutorial'!
batch
 ^ batch
! !

!LQApp methodsFor: 'tutorial'!
probe
 ^ probe
! !

!LQApp methodsFor: 'tutorial'!
viewing
 ^ viewing
! !

!LQApp methodsFor: 'tutorial'!
buttonNamed: text
 ^ buttons at: text
! !

!LQApp class methodsFor: 'tutorial'!
open
 ^ self new open
! !

!LQApp methodsFor: 'tutorial'!
open
 window ifNotNil: [window comeToFront. ^ self].
 window := LQWindow new model: self; setLabel: 'Eight Queens Lab - LearnSqueak'.
 window addMorph: self fullFrame: (LayoutFrame fractions: (0@0 corner: 1@1)).
 window fixedExtent: 974@701. window openInWorld. ^ self
! !

!LQApp methodsFor: 'tutorial'!
okToClose
 ^ true
! !

!LQApp methodsFor: 'tutorial'!
release
 ^ self
! !

!LQApp methodsFor: 'tutorial'!
windowIsClosing
 self stopActivity.
 World hands do: [:hand | hand keyboardFocus == board ifTrue: [hand newKeyboardFocus: nil]].
 window := nil
! !

!LQWindow methodsFor: 'tutorial'!
fixedExtent: point
 fixedExtent := point. super extent: point
! !

!LQWindow methodsFor: 'tutorial'!
extent: point
 super extent: (fixedExtent ifNil: [point])
! !

!LQApp methodsFor: 'tutorial'!
displayQueens
 ^ search queens
! !

!LQApp methodsFor: 'tutorial'!
refresh
 | status |
 status := search state asString.
 running ifTrue: [status := status, ' / running'].
 info contents: ('State: ', status, '   |   row ', (search row min: search size) printString).
 phaseLine contents: ('Last: ', search event asString, '   |   next: ', ((#(solution complete blocked) includes: search state) ifTrue: ['none'] ifFalse: [search phase asString])).
 countLine contents: ('Tries ', search attempts printString, '  /  backtracks ', search backtracks printString, '  /  events ', search events printString).
 solutionLine contents: self displayQueens printString.
 probeLine contents: (probe ifNil: [self stage = 1 ifTrue: ['Coordinates: column @ row'] ifFalse: ['Probe: click any board square']] ifNotNil: ['Probe: column ', probe x printString, ', row ', probe y printString]).
 noteLine contents: search note. board changed. self changed
! !

!LQApp methodsFor: 'tutorial'!
inspectCell: cell
 (search validCell: cell) ifFalse: [^ false].
 self stopActivity. probe := cell. self refresh. ^ true
! !

!LQApp methodsFor: 'tutorial'!
clearProbe
 probe := nil. self refresh
! !

!LQApp methodsFor: 'tutorial'!
stopActivity
 running := false. self stopStepping
! !

!LQApp methodsFor: 'tutorial'!
reset
 self stopActivity. probe := nil. viewing := 0. search reset. self refresh
! !

!LQBoard methodsFor: 'tutorial'!
initialize
 super initialize. cellSize := 54. self extent: 510@442; color: (Color fromString: '#F1F5FA')
! !

!LQBoard methodsFor: 'tutorial'!
app: anApp
 app := anApp
! !

!LQBoard methodsFor: 'tutorial'!
cellRectangle: cell
 ^ (self position + (42@4) + ((cell - (1@1)) * cellSize)) extent: cellSize@cellSize
! !

!LQBoard methodsFor: 'tutorial'!
cellAt: screenPoint
 | local |
 local := screenPoint - self position - (42@4).
 ((0@0 extent: (cellSize * 8)@(cellSize * 8)) containsPoint: local) ifFalse: [^ nil].
 ^ ((local x // cellSize) + 1)@((local y // cellSize) + 1)
! !

!LQBoard methodsFor: 'tutorial'!
drawOn: canvas
 | rect shade font queens cell label model highlight |
 super drawOn: canvas. model := app search. queens := app displayQueens. font := TextStyle default fontOfSize: 16.
 1 to: 8 do: [:r | 1 to: 8 do: [:c |
  cell := c@r. rect := self cellRectangle: cell.
  shade := (r + c) even ifTrue: [Color fromString: '#E8EDF1'] ifFalse: [Color fromString: '#CAD7E1'].
  app probe ifNotNil: [:p | (model attacks: p with: cell) ifTrue: [shade := Color fromString: '#A8CCE2']].
  app viewing = 0 ifTrue: [
   (model conflicts includes: cell) ifTrue: [shade := Color fromString: '#EDAEA0'].
   model candidate = cell ifTrue: [shade := Color fromString: (model event = #reject ifTrue: ['#EB9C89'] ifFalse: [model event = #backtrack ifTrue: ['#EFBA80'] ifFalse: ['#F1D178']])]].
  app probe = cell ifTrue: [shade := Color fromString: '#80B5D7'].
  canvas fillRectangle: rect color: shade.
  (queens at: r) = c ifTrue: [
   canvas fillOval: (rect insetBy: 9) color: (Color fromString: '#248A74').
   canvas drawString: 'Q' at: rect origin + (20@15) font: (TextStyle default fontOfSize: 21) color: Color white].
  (app viewing = 0 and: [model candidate = cell and: [(queens at: r) ~= c]]) ifTrue: [
   highlight := model event = #reject ifTrue: ['X'] ifFalse: [model event = #backtrack ifTrue: ['-'] ifFalse: ['?']].
   canvas drawString: highlight at: rect origin + (20@15) font: (TextStyle default fontOfSize: 21) color: (Color fromString: '#17334B')]]].
  1 to: 8 do: [:index |
   label := index printString.
   canvas drawString: label at: (self cellRectangle: 1@index) origin - (24@ -17) font: font color: (Color fromString: '#17334B').
   canvas drawString: label at: (self cellRectangle: index@8) bottomLeft + (21@1) font: font color: (Color fromString: '#17334B')]
! !

!LQBoard methodsFor: 'tutorial'!
handlesMouseDown: event
 ^ true
! !

!LQBoard methodsFor: 'tutorial'!
mouseDown: event
 | cell |
 World activeHand newKeyboardFocus: self. cell := self cellAt: event position.
 cell ifNotNil: [app inspectCell: cell]
! !

!LQApp methodsFor: 'tutorial'!
stage
 ^ 3
! !

!LQApp methodsFor: 'tutorial'!
stageTitle
 ^ 'Ask whether a placement is safe'
! !

!LQApp methodsFor: 'tutorial'!
buildToolbar
 self button: 'Reset' at: 26@108 action: #reset arguments: #().
 self button: 'Clear probe' at: 100@108 action: #clearProbe arguments: #().
! !

