Object subclass: #LPFSearch instanceVariableNames: 'width height walls start goal frontier closed discovered parents distances path current state algorithm expanded peak' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Pathfinding'! Morph subclass: #LPFApp instanceVariableNames: 'search grid window info status mode running comparison' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Pathfinding'! Morph subclass: #LPFGrid instanceVariableNames: 'app cellSize drawing visited' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Pathfinding'! SystemWindow subclass: #LPFWindow instanceVariableNames: 'fixedExtent' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Pathfinding'! !LPFWindow methodsFor: 'tutorial'! fixedExtent: point fixedExtent := point. super extent: point ! ! !LPFWindow methodsFor: 'tutorial'! extent: point super extent: (fixedExtent ifNil: [point]) ! ! !LPFSearch methodsFor: 'tutorial'! initialize super initialize. width := 18. height := 12. walls := Set new. start := 2@6. goal := 17@6. algorithm := #bfs. self resetSearch ! ! !LPFSearch methodsFor: 'tutorial'! resetSearch frontier := OrderedCollection new. closed := Set new. discovered := Set new. parents := Dictionary new. distances := Dictionary new. path := OrderedCollection new. current := nil. state := #idle. expanded := 0. peak := 0 ! ! !LPFSearch methodsFor: 'tutorial'! width ^ width ! ! !LPFSearch methodsFor: 'tutorial'! height ^ height ! ! !LPFSearch methodsFor: 'tutorial'! start ^ start ! ! !LPFSearch methodsFor: 'tutorial'! goal ^ goal ! ! !LPFSearch methodsFor: 'tutorial'! state ^ state ! ! !LPFSearch methodsFor: 'tutorial'! algorithm ^ algorithm ! ! !LPFSearch methodsFor: 'tutorial'! current ^ current ! ! !LPFSearch methodsFor: 'tutorial'! expanded ^ expanded ! ! !LPFSearch methodsFor: 'tutorial'! peak ^ peak ! ! !LPFSearch methodsFor: 'tutorial'! frontierCount ^ frontier size ! ! !LPFSearch methodsFor: 'tutorial'! pathLength ^ path isEmpty ifTrue: [nil] ifFalse: [path size - 1] ! ! !LPFSearch methodsFor: 'tutorial'! walls ^ walls copy ! ! !LPFSearch methodsFor: 'tutorial'! frontier ^ frontier copy ! ! !LPFSearch methodsFor: 'tutorial'! closed ^ closed copy ! ! !LPFSearch methodsFor: 'tutorial'! path ^ path copy ! ! !LPFSearch methodsFor: 'tutorial'! validCell: cell ^ cell isPoint and: [cell x isInteger and: [cell y isInteger and: [cell x between: 1 and: width] and: [cell y between: 1 and: height]]] ! ! !LPFSearch methodsFor: 'tutorial'! blocked: cell ^ (self validCell: cell) not or: [walls includes: cell] ! ! !LPFSearch methodsFor: 'tutorial'! neighborsOf: cell ^ {cell + (1@0). cell + (0@1). cell + (-1@0). cell + (0@ -1)} select: [:neighbor | (self blocked: neighbor) not] ! ! !LPFSearch methodsFor: 'tutorial'! wallAt: cell put: blocked ((self validCell: cell) and: [cell ~= start and: [cell ~= goal and: [blocked == true or: [blocked == false]]]]) ifFalse: [^ false]. blocked ifTrue: [walls add: cell] ifFalse: [walls remove: cell ifAbsent: []]. self resetSearch. ^ true ! ! !LPFSearch methodsFor: 'tutorial'! start: cell (self blocked: cell) ifTrue: [^ false]. start := cell. self resetSearch. ^ true ! ! !LPFSearch methodsFor: 'tutorial'! goal: cell (self blocked: cell) ifTrue: [^ false]. goal := cell. self resetSearch. ^ true ! ! !LPFSearch methodsFor: 'tutorial'! begin self resetSearch. frontier add: start. discovered add: start. distances at: start put: 0. state := #searching. peak := 1 ! ! !LPFSearch methodsFor: 'tutorial'! nextCell | best score bestScore | algorithm = #bfs ifTrue: [^ frontier removeFirst]. best := frontier first. bestScore := (distances at: best) + (self heuristic: best). frontier do: [:cell | score := (distances at: cell) + (self heuristic: cell). (score < bestScore or: [score = bestScore and: [(self heuristic: cell) < (self heuristic: best)]]) ifTrue: [best := cell. bestScore := score]]. frontier remove: best. ^ best ! ! !LPFSearch methodsFor: 'tutorial'! expand: cell | nextDistance | nextDistance := (distances at: cell) + 1. (self neighborsOf: cell) do: [:neighbor | (closed includes: neighbor) ifFalse: [ ((distances at: neighbor ifAbsent: [width * height + 1]) > nextDistance) ifTrue: [ parents at: neighbor put: cell. distances at: neighbor put: nextDistance. (discovered includes: neighbor) ifFalse: [discovered add: neighbor. frontier add: neighbor]]]]. peak := peak max: frontier size ! ! !LPFSearch methodsFor: 'tutorial'! stepSearch state = #searching ifFalse: [^ false]. frontier isEmpty ifTrue: [state := #noPath. ^ false]. current := self nextCell. closed add: current. expanded := expanded + 1. current = goal ifTrue: [self reconstructPath. state := #found. ^ true]. self expand: current. frontier isEmpty ifTrue: [state := #noPath]. ^ true ! ! !LPFSearch methodsFor: 'tutorial'! reconstructPath | cell | path := OrderedCollection new. cell := goal. [path addFirst: cell. cell ~= start] whileTrue: [cell := parents at: cell] ! ! !LPFSearch methodsFor: 'tutorial'! solve self begin. 1 to: width * height do: [:ignored | state = #searching ifTrue: [self stepSearch]]. ^ state ! ! !LPFSearch methodsFor: 'tutorial'! cancel state = #searching ifTrue: [state := #cancelled] ! ! !LPFSearch methodsFor: 'tutorial'! algorithm: symbol (#(bfs astar) includes: symbol) ifFalse: [^ false]. algorithm := symbol. self resetSearch. ^ true ! ! !LPFSearch methodsFor: 'tutorial'! heuristic: cell ^ (cell x - goal x) abs + (cell y - goal y) abs ! ! !LPFSearch methodsFor: 'tutorial'! copyMap | other | other := self class new. other start: start; goal: goal. walls do: [:cell | other wallAt: cell put: true]. ^ other ! ! !LPFSearch methodsFor: 'tutorial'! comparison | bfs astar | bfs := self copyMap. astar := self copyMap. bfs algorithm: #bfs; solve. astar algorithm: #astar; solve. ^ {bfs. astar} ! ! !LPFSearch methodsFor: 'tutorial'! clearMap walls removeAll. start := 2@6. goal := 17@6. self resetSearch ! ! !LPFSearch methodsFor: 'tutorial'! sampleMap self clearMap. 2 to: 11 do: [:y | y = 9 ifFalse: [walls add: 7@y]]. 2 to: 11 do: [:y | y = 4 ifFalse: [walls add: 12@y]]. self resetSearch ! ! !LPFSearch methodsFor: 'tutorial'! sealedMap self clearMap. 1 to: height do: [:y | walls add: 9@y]. self resetSearch ! ! !LPFApp methodsFor: 'tutorial'! initialize super initialize. self extent: 900@600; color: (Color fromString: '#EBF1F7'). search := LPFSearch new. mode := #wall. running := false. comparison := ''. self addLabel: 'Pathfinding Lab' at: 24@14 size: 24. self addLabel: ('Checkpoint ', self stage printString, ' / 9 - ', self stageTitle) at: 25@49 size: 14. grid := LPFGrid new app: self; position: self position + (24@145). self addMorph: grid. info := self addLabel: '' at: 24@547 size: 14. status := self addLabel: '' at: 24@575 size: 12. self addLegend. self buildToolbar. self refresh ! ! !LPFApp methodsFor: 'tutorial'! addLabel: text at: point size: size | label | label := StringMorph contents: text font: (TextStyle default fontOfSize: size). label position: self position + point; color: (Color fromString: '#18334B'). self addMorph: label. ^ label ! ! !LPFApp 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. ^ button ! ! !LPFApp methodsFor: 'tutorial'! search ^ search ! ! !LPFApp methodsFor: 'tutorial'! grid ^ grid ! ! !LPFApp methodsFor: 'tutorial'! window ^ window ! ! !LPFApp methodsFor: 'tutorial'! mode ^ mode ! ! !LPFApp methodsFor: 'tutorial'! running ^ running ! ! !LPFApp methodsFor: 'tutorial'! comparisonText ^ comparison ! ! !LPFApp class methodsFor: 'tutorial'! open ^ self new open ! ! !LPFApp methodsFor: 'tutorial'! open window ifNotNil: [window comeToFront. ^ self]. window := LPFWindow new model: self; setLabel: 'Pathfinding Lab'. window addMorph: self fullFrame: (LayoutFrame fractions: (0@0 corner: 1@1)). window fixedExtent: 910@633. window openInWorld. ^ self ! ! !LPFApp methodsFor: 'tutorial'! okToClose ^ true ! ! !LPFApp methodsFor: 'tutorial'! release ^ self ! ! !LPFApp methodsFor: 'tutorial'! windowIsClosing self stopActivity. grid endDrawing. World hands do: [:hand | hand keyboardFocus == grid ifTrue: [hand newKeyboardFocus: nil]]. window := nil ! ! !LPFApp methodsFor: 'tutorial'! status: text status contents: text ! ! !LPFApp methodsFor: 'tutorial'! refresh | stateText algorithmText | stateText := search state asString. (self stage >= 5 and: [search state = #searching]) ifTrue: [stateText := stateText, (running ifTrue: [' / running'] ifFalse: [' / paused'])]. algorithmText := search algorithm = #astar ifTrue: ['A*'] ifFalse: ['BFS']. grid changed. info contents: (algorithmText, ' | ', stateText, ' | expanded ', search expanded printString, ' | frontier ', search frontierCount printString, ' | path ', (search pathLength ifNil: ['-'] ifNotNil: [:n | n printString]), ' moves'). status contents: (comparison isEmpty ifTrue: ['Tool: ', mode asString, ' | S = start, G = goal | orthogonal moves cost 1'] ifFalse: [comparison]). self changed ! ! !LPFApp methodsFor: 'tutorial'! addLegend | row | row := 153. #(('Start / S' '#28A67A') ('Goal / G' '#ED795D') ('Wall' '#243950') ('Frontier' '#EFBF45') ('Expanded' '#A8CCED') ('Shortest path' '#9565CB') ('Current cell' '#2973BA')) do: [:entry | | swatch | swatch := Morph new color: (Color fromString: entry second); extent: 19@19; position: self position + (637@row). self addMorph: swatch. self addLabel: entry first at: 669@row size: 14. row := row + 36]. self addLabel: '18 x 12 = 216 vertices' at: 637@439 size: 14. self addLabel: '4 neighbors per cell' at: 637@464 size: 14. self addLabel: 'No diagonals / no weights' at: 637@489 size: 12 ! ! !LPFApp methodsFor: 'tutorial'! chooseMode: symbol (#(wall erase start goal) includes: symbol) ifFalse: [^ false]. mode := symbol. self refresh. ^ true ! ! !LPFApp methodsFor: 'tutorial'! editCell: cell | result | self stage >= 5 ifTrue: [self stopActivity]. result := mode = #start ifTrue: [search start: cell] ifFalse: [ mode = #goal ifTrue: [search goal: cell] ifFalse: [search wallAt: cell put: mode = #wall]]. result ifTrue: [comparison := '']. self refresh. ^ result ! ! !LPFApp methodsFor: 'tutorial'! stepOnce self stopActivity. search state = #idle ifTrue: [search begin]. search stepSearch. self refresh ! ! !LPFApp methodsFor: 'tutorial'! run window ifNil: [^ self]. running ifTrue: [^ self]. (#(found noPath cancelled) includes: search state) ifTrue: [^ self]. search state = #idle ifTrue: [search begin]. running := true. self startStepping. self refresh ! ! !LPFApp methodsFor: 'tutorial'! stepTime ^ 80 ! ! !LPFApp methodsFor: 'tutorial'! step running ifFalse: [^ self]. search stepSearch. search state = #searching ifFalse: [self stopActivity]. self refresh ! ! !LPFApp methodsFor: 'tutorial'! stopActivity running := false. self stopStepping ! ! !LPFApp methodsFor: 'tutorial'! pause self stopActivity. self refresh ! ! !LPFApp methodsFor: 'tutorial'! cancel self stopActivity. search cancel. self refresh ! ! !LPFApp methodsFor: 'tutorial'! reset self stopActivity. search resetSearch. comparison := ''. self refresh ! ! !LPFApp methodsFor: 'tutorial'! chooseAlgorithm: symbol self stopActivity. search algorithm: symbol. comparison := ''. self refresh ! ! !LPFApp methodsFor: 'tutorial'! compare | results bfs astar | self stopActivity. results := search comparison. bfs := results first. astar := results second. comparison := 'BFS: ', bfs expanded printString, ' expanded / ', (bfs pathLength ifNil: ['no path'] ifNotNil: [:n | n printString, ' moves']), ' A*: ', astar expanded printString, ' expanded / ', (astar pathLength ifNil: ['no path'] ifNotNil: [:n | n printString, ' moves']). self refresh. ^ results ! ! !LPFApp methodsFor: 'tutorial'! fixture: symbol (#(sample sealed clear) includes: symbol) ifFalse: [^ false]. self stopActivity. symbol = #sample ifTrue: [search sampleMap]. symbol = #sealed ifTrue: [search sealedMap]. symbol = #clear ifTrue: [search clearMap]. comparison := ''. self refresh. ^ true ! ! !LPFGrid methodsFor: 'tutorial'! initialize super initialize. cellSize := 32. drawing := false. visited := Set new. self extent: 576@384; color: (Color fromString: '#C7D4E2') ! ! !LPFGrid methodsFor: 'tutorial'! app: anApp app := anApp ! ! !LPFGrid methodsFor: 'tutorial'! drawOn: canvas | origin cell shade model route pending done | super drawOn: canvas. model := app search. route := model path asSet. pending := model frontier asSet. done := model closed. 1 to: model height do: [:y | 1 to: model width do: [:x | cell := x@y. origin := self position + ((cell - (1@1)) * cellSize). shade := Color white. (done includes: cell) ifTrue: [shade := Color fromString: '#A8CCED']. (pending includes: cell) ifTrue: [shade := Color fromString: '#EFBF45']. (route includes: cell) ifTrue: [shade := Color fromString: '#9565CB']. cell = model current ifTrue: [shade := Color fromString: '#2973BA']. (model blocked: cell) ifTrue: [shade := Color fromString: '#243950']. cell = model start ifTrue: [shade := Color fromString: '#28A67A']. cell = model goal ifTrue: [shade := Color fromString: '#ED795D']. canvas fillRectangle: (origin extent: 31@31) color: shade. cell = model start ifTrue: [canvas drawString: 'S' at: origin + (9@6) font: (TextStyle default fontOfSize: 14) color: Color white]. cell = model goal ifTrue: [canvas drawString: 'G' at: origin + (9@6) font: (TextStyle default fontOfSize: 14) color: Color white]] ] ! ! !LPFGrid methodsFor: 'tutorial'! handlesMouseDown: event ^ true ! ! !LPFGrid methodsFor: 'tutorial'! handlesMouseMove: event ^ drawing ! ! !LPFGrid methodsFor: 'tutorial'! mouseDown: event World activeHand newKeyboardFocus: self. drawing := true. visited removeAll. self editAt: event position ! ! !LPFGrid methodsFor: 'tutorial'! mouseMove: event drawing ifTrue: [self editAt: event position] ! ! !LPFGrid methodsFor: 'tutorial'! mouseUp: event self endDrawing ! ! !LPFGrid methodsFor: 'tutorial'! endDrawing drawing := false. visited removeAll. World hands do: [:hand | hand mouseFocus == self ifTrue: [hand newMouseFocus: nil]] ! ! !LPFGrid methodsFor: 'tutorial'! editAt: point | local cell | local := point - self position. ((0@0 extent: self extent) containsPoint: local) ifFalse: [^ false]. cell := ((local x // cellSize) + 1) @ ((local y // cellSize) + 1). (visited includes: cell) ifTrue: [^ false]. visited add: cell. ^ app editCell: cell ! ! !LPFGrid methodsFor: 'tutorial'! handlesKeyboard: event ^ true ! ! !LPFGrid methodsFor: 'tutorial'! handlesKeyboardFocusChange: event ^ true ! ! !LPFGrid methodsFor: 'tutorial'! keyStroke: event | key | key := event keyValue. key = 32 ifTrue: [app running ifTrue: [app pause] ifFalse: [app run]]. key = 27 ifTrue: [app cancel]. (#(110 78) includes: key) ifTrue: [app stepOnce]. (#(114 82) includes: key) ifTrue: [app reset] ! ! !LPFApp methodsFor: 'tutorial'! stage ^ 9 ! ! !LPFApp methodsFor: 'tutorial'! stageTitle ^ 'Finish keyboard and lifecycle' ! ! !LPFApp methodsFor: 'tutorial'! buildToolbar self button: 'Wall' at: 24@85 action: #chooseMode: arguments: {#wall}. self button: 'Erase' at: 87@85 action: #chooseMode: arguments: {#erase}. self button: 'Set S' at: 155@85 action: #chooseMode: arguments: {#start}. self button: 'Set G' at: 225@85 action: #chooseMode: arguments: {#goal}. self button: 'Step' at: 302@85 action: #stepOnce arguments: #(). self button: 'Run' at: 362@85 action: #run arguments: #(). self button: 'Pause' at: 417@85 action: #pause arguments: #(). self button: 'Cancel' at: 487@85 action: #cancel arguments: #(). self button: 'Reset' at: 566@85 action: #reset arguments: #(). self button: 'BFS' at: 645@85 action: #chooseAlgorithm: arguments: {#bfs}. self button: 'A*' at: 703@85 action: #chooseAlgorithm: arguments: {#astar}. self button: 'Compare' at: 757@85 action: #compare arguments: #(). self button: 'Sample' at: 24@116 action: #fixture: arguments: {#sample}. self button: 'Sealed' at: 104@116 action: #fixture: arguments: {#sealed}. self button: 'Clear' at: 183@116 action: #fixture: arguments: {#clear}. self addLabel: 'Click grid for keys: Space run/pause | N step | R reset | Esc cancel' at: 275@119 size: 12. ! ! !LPFSearch methodsFor: 'tutorial'! reachableCount | queue seen cell | queue := OrderedCollection with: start. seen := Set with: start. [queue notEmpty] whileTrue: [ cell := queue removeFirst. (self neighborsOf: cell) do: [:neighbor | (seen includes: neighbor) ifFalse: [seen add: neighbor. queue add: neighbor]]]. ^ seen size ! !