Newsqueak2 'Sudoku' class SudokuGame usingPlatform: platform hopscotchExtensions: hopscotchExtensions = NewspeakObject ( "Copyright 2010-2011 Vadim Tsushko. 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. " | Presenter = hopscotchExtensions PresenterExt. Subject = platform hopscotch core Subject. protected Time = platform Time. protected Random = platform Random. Color = platform Color. Row = platform brazil containers Row. Grid = platform brazil containers Grid. Set = platform collections Set. boardPresenter HopscotchWindow = hopscotchExtensions HopscotchWindowExt. SubmenuItem = platform brazil menus SubmenuItem. MenuItem = platform brazil menus MenuItem. Menu = platform brazil menus Menu. SeparatorItem = platform brazil menus SeparatorItem. currentLanguage::='English'. Dictionary = platform collections Dictionary. i18nEngine = I18n new. showConflictMode::=false. | ) ( class BoardGridPresenter onSubject: s = Presenter onSubject: s ( ) ('as yet unclassified' cellForRow: r column: c bigRow: bigRow bigColumn: bigColumn = ( |column row| column:: ((bigColumn-1)* 3) + c. row:: ((bigRow-1)* 3) + r. ^cellPresenter: (subject model atCol: column row: row) ) cellPresenter: cell = ( ^(CellSubject onModel: cell) presenter ) definition = ( |grid| grid:: gridWithRows: 3 columns: 3 cellFragmentBlock: [:r :c| grid3x3AtRow: r column: c]. ^(padded: grid with: {4. 4. 4. 4.}) color: Color black. ) fragmentForRow: r column: c = ( ^cellPresenter: (subject model atCol: c row: r) ) grid3x3AtRow: bigRow column: bigColumn = ( |grid| grid:: gridWithRows: 3 columns: 3 cellFragmentBlock: [:r :c| cellForRow: r column: c bigRow: bigRow bigColumn: bigColumn] copy fixTemps. ^(padded: grid with: {2. 2. 2. 2.}) color: Color black. ) ) class BoardSubject onModel: m = Subject onModel: m( | startedAt = Time now. level | ) ('as yet unclassified' createPresenter = ( ^BoardPresenter onSubject: self. ) ) : ( 'as yet unclassified' newValidBoardWithDifficulty: level = ( |board| board:: Board new generateValidBoard. board setDifficultyLevel: level. ^BoardSubject onModel: board. ) randomBoard = ( ^BoardSubject onModel: Board new generateRandomBoard. ) ) class Cell withValue: v col: c row: r = ( "Describe the class in this comment." | value currentValue row column region enabled inConflict revealed availableValues | value:: v. column:: c. row:: r. region:: regionForCol: c row: r. enabled:: true. revealed:: false. inConflict: false. currentValue:: 0. ) ('as yet unclassified' displayValue = ( |res| res:: currentValue = 0 ifTrue: ['...'] ifFalse: [currentValue printString] . ^res ) isPreopened = ( ^enabled not and: [revealed not] ) open = ( currentValue:: value. enabled: false. ) printOn: aStream = ( aStream nextPutAll: 'SudokuGame::Cell(value:'. value printOn:aStream. aStream nextPutAll:', currentValue: ' . currentValue printOn: aStream. aStream nextPutAll:', row: ' . row printOn: aStream. aStream nextPutAll:', column: ' . column printOn: aStream. aStream nextPutAll: ')') regionForCol: col row: row = ( (col between: 1 and: 3) & (row between: 1 and: 3) ifTrue: [^1]. (col between: 4 and: 6) & (row between: 1 and: 3) ifTrue: [^2]. (col between: 7 and: 9) & (row between: 1 and: 3) ifTrue: [^3]. (col between: 1 and: 3) & (row between: 4 and: 6) ifTrue: [^4]. (col between: 4 and: 6) & (row between: 4 and: 6) ifTrue: [^5]. (col between: 7 and: 9) & (row between: 4 and: 6) ifTrue: [^6]. (col between: 1 and: 3) & (row between: 7 and: 9) ifTrue: [^7]. (col between: 4 and: 6) & (row between: 7 and: 9) ifTrue: [^8]. (col between: 7 and: 9) & (row between: 7 and: 9) ifTrue: [^9]. error: ''. ) reveal = ( open. revealed: true. ) ) class SudokuWindow = HopscotchWindow( ) ('as yet unclassified' addMenuBarItemsTo: menu = ( ^self. " menu add: (SubmenuItem label: '&Navigator' submenu: (Menu new add: (MenuItem label: '&New' action: [respondToNew]); add: SeparatorItem new; add: (MenuItem label: '&Refresh' action: [refresh]); add: (MenuItem label: '&Close' action: [respondToClose]); yourself )). menu add: (SubmenuItem label: '&Go' submenu: (Menu new add: (MenuItem label: '&Back' action: [goBack]); add: (MenuItem label: '&Forward' action: [goForward]); add: SeparatorItem new; add: (MenuItem label: '&Home' action: [goHome]); add: (MenuItem label: 'Hi&story' action: [showHistory]); yourself )). menu add: (SubmenuItem label: '&Help' submenu: (Menu new add: (MenuItem label: 'User''s Guide' action: []); add: SeparatorItem new; add: (MenuItem label: 'About' action: []); yourself )). " ) addToolbarItemsTo: toolbar = ( pastButton:: buildDropDown: [selectFromPast]. toolbar add: (wrapToAlignToBottomCenter: pastButton). toolbar addBlankSize: 3. backButton:: toolbar add: buildBackButton. forwardButton:: toolbar add: buildForwardButton. toolbar addBlankSize: 3. futureButton:: buildDropDown: [selectFromFuture]. toolbar add: (wrapToAlignToBottomCenter: futureButton). toolbar addBlankSize: 10. toolbar add: buildHistoryButton. toolbar addBlankSize: 2. homeButton:: toolbar add: buildHomeButton. toolbar addBlankSize: 10. toolbar add: buildRefreshButton. toolbar addBlankSize: 2. toolbar add: buildNewButton. showOutline ifTrue: [toolbar addBlankSize: 10. toolbar add: buildToggleOutlineButton] ) homePresenter = ( ^HomePresenter ) homeSubject = ( ^HomeSubject ) initialExtent ^ = ( ^370 @ 470 ) ) : ( 'as yet unclassified' openSubject: aSubject = ( ^openSubjectFromBlock: [:instance | aSubject] ) openSubjectFromBlock: aBlock = ( ^(withSubjectFromBlock: aBlock) open ) withSubjectFromBlock: aBlock = ( | instance | #BOGUS yourself. "copied from HopscotchShell" instance:: self new. instance subject: (aBlock value: instance). ^instance ) ) class I18n = ( "Describe the class in this comment." | russian = Dictionary new. |{ 'English' -> 'Àíãëèéñêèé'. 'Russian' -> 'Ðóññêèé'. 'Hard' -> 'Ñëîæíûé'. 'Medium' -> 'Ñðåäíèé'. 'Easy' -> '˸ãêèé'. 'Start new game' -> 'Íà÷àòü íîâóþ èãðó'. 'Difficulty level' -> 'Óðîâåíü ñëîæíîñòè'. 'Interface language' -> 'ßçûê èíòåðôåéñà'. 'Contgratulations! Puzzle solved' -> 'Ïîçäðàâëÿåì! Ñóäîêó ðåøåíà'. 'Return to game' -> 'Âåðíóòüñÿ ê èãðå'. 'Show conflicts' -> 'Ïîêàçàòü êîíôëèêòû'. 'Sudoku. Difficulty: ' -> 'Ñóäîêó. Ñëîæíîñòü: '. '. Started at ' -> '. Íà÷àëî â ' . 'Reveal' -> 'Îòêðûòü' . 'Empty' -> 'Îáíóëèòü' . } do: [:elt| russian add: elt]. ) ('as yet unclassified' translate: aStr = ( currentLanguage = 'English' ifTrue: [^aStr]. currentLanguage = 'Russian' ifTrue: [^russian at: aStr ifAbsent: [aStr]] ) ) class CellPresenter onSubject: s = Presenter onSubject: s( | cellX | ) ('as yet unclassified' buildButton = ( cellX:: button: subject model displayValue action: [showCellMenu]. subject model revealed ifTrue: [cellX enabled: false]. ) buildLabel = ( cellX:: (label: subject model displayValue). cellX:: centered:cellX. cellX:: column: { blank: 8 . cellX. blank: 8}. ) cellDefinition = ( |clr| (showConflictMode or: [subject model enabled not]) ifTrue: [buildLabel] ifFalse: [buildButton]. clr:: subject model inConflict ifTrue: [Color lightRed] ifFalse: [ subject model revealed ifTrue: [Color lightYellow] ifFalse: [Color veryVeryLightGray]]. cellX:: (row: {cellX width: 32}) color: clr. cellX:: (padded: cellX with: {1. 1. 1. 1}) color: Color black. ^cellX ) cellMenu = ( |col| col:: ((1 to: 9) collect: [:idx| idx printString -> [setCellValue: idx] copy fixTemps]) asOrderedCollection. col add: (i18n: 'Reveal') -> [revealValue]. col add: (i18n: 'Empty') -> [setCellValue: 0]. ^menuWithLabelsAndActions: col ) definition = ( ^holder: [cellDefinition]. ) revealValue = ( subject model reveal. refresh. ) setCellValue: val = ( subject model currentValue: val. refresh. ) showCellMenu = ( |menu | menu:: cellMenu. menu ownerVisual: visual. menu openIn: visual desktop. ) ) class Board = ( "Describe the class in this comment." | cells = Array new: 81. rnd = Random new seed: (Time now seconds). difficultyLevel | ) ('as yet unclassified' atCol: col row: row = ( ^cells at: (indexForCol: col row: row). ) atCol: col row: row put: aCell = ( cells at: (indexForCol: col row: row) put: aCell. ) currentValueInConflictWith: cell = ( ^((cells select: [:elt| elt currentValue ~= 0]) copyWithout: cell) anySatisfy: [:elt| (elt currentValue = cell currentValue) and: [(elt row = cell row) or: [(elt column = cell column) or: [elt region = cell region]]]]. ) difficultyLabel = ( ^i18n: (difficultyLevel = 1 ifTrue: ['Easy'] ifFalse: [difficultyLevel = 2 ifTrue: ['Medium'] ifFalse: ['Hard']]) ) generateRandomBoard = ( |cell| (1 to: 9) do: [:c| (1 to: 9) do: [:r| cell:: Cell withValue: (rnd nextInt: 9) col: c row: r. atCol: c row: r put: cell. ]]. 1 to: 40 do: [:idx| cell:: cells atRandom: rnd.cell reveal.idx odd ifTrue: [cell revealed: false]]. (cells select: [:elt| elt currentValue ~= 0]) do: [:elt| (self currentValueInConflictWith: elt) ifTrue: [elt inConflict: true]] ) generateValidBoard = ( " Simple backtracking algorithm ported from http://www.codeproject.com/KB/game/SudokuGen.aspx " |cell currentIndex| (1 to: 9) do: [:c| (1 to: 9) do: [:r| cell:: Cell withValue: 0 col: c row: r. cell availableValues: (1 to: 9 ) asSet. atCol: c row: r put: cell. ]]. currentIndex:: 1. [currentIndex < 82] whileTrue: [ cell:: cells at: currentIndex. cell availableValues isEmpty ifTrue: [cell availableValues: (1 to: 9 ) asSet. cell value: 0. currentIndex: currentIndex-1.] ifFalse: [ cell value: (cell availableValues atRandom: rnd). cell availableValues remove: cell value. (valueInConflictWith: cell) ifFalse: [currentIndex:: currentIndex+1]]] ) indexForCol: col row: row = ( ^((row-1) * 9) + col. ) readyToCheck = ( ^cells allSatisfy: [:elt| elt currentValue ~= 0] ) resetConflicts = ( showConflictMode ifTrue: [ cells do: [:elt| elt inConflict: (currentValueInConflictWith: elt) ]] ifFalse: [ cells do: [:elt| elt inConflict: false]] ) setDifficultyLevel: level = ( |cellsToOpen cell| difficultyLevel:: level. cellsToOpen:: level = 1 ifTrue: [40] ifFalse: [level = 2 ifTrue: [32] ifFalse: [26]]. level = 0 ifTrue: [cells do: [:elt| elt reveal]. ^self]. 1 to: cellsToOpen do: [:idx| cell:: (cells atRandom: rnd). [cell isPreopened] whileTrue: [cell:: (cells atRandom: rnd).]. cell open. ]. ) solved = ( ^showConflictMode and: [(cells anySatisfy: [:elt| elt inConflict or: [elt currentValue = 0]]) not] ) valueInConflictWith: cell = ( ^((cells select: [:elt| elt value ~= 0]) copyWithout: cell) anySatisfy: [:elt| (elt value = cell value) and: [(elt row = cell row) or: [(elt column = cell column) or: [elt region = cell region]]]]. ) ) class HomeSubject onModel: m = Subject onModel: m( | difficultyLevel::=1. | ) ('as yet unclassified' createPresenter = ( ^HomePresenter onSubject: self. ) difficultyLabel = ( ^i18n: (difficultyLevel = 1 ifTrue: ['Easy'] ifFalse: [difficultyLevel = 2 ifTrue: ['Medium'] ifFalse: ['Hard']]) ) ) : ( 'as yet unclassified' new = ( ^onModel:nil ) ) class CellSubject onModel: m = Subject onModel: m( "Describe the class in this comment." | | ) ('as yet unclassified' createPresenter = ( ^CellPresenter onSubject: self. ) ) : ( 'as yet unclassified' sample = ( |cell| cell:: Cell withValue: 5 col: 3 row: 8. ^CellSubject onModel: cell. ) sampleLabel = ( |cell| cell:: Cell withValue: 5 col: 3 row: 8. cell isEnabled: false. ^CellSubject onModel: cell. ) ) class HomePresenter onSubject: s = Presenter onSubject: s( | difficultyHolder| ) ('as yet unclassified' definition = ( ^holder: [column: { blank: 20. centered: (link: (i18n: 'Start new game') action: [startNewGame]) hugeFont. blank: 20. centered: (row: { label: (i18n: 'Difficulty level'), ' - '. blank: 4. label: (i18n: subject difficultyLabel). blank: 4. dropDownMenu: [setDifficultyMenu]. } ). blank: 20. centered: (row: { label: (i18n: 'Interface language') , ' - '. blank: 4. label: (i18n: currentLanguage). blank: 4. dropDownMenu: [setLanguageMenu]. } ) }] ) setDifficultyMenu = ( ^menuWithLabelsAndActions: { (i18n: 'Easy') -> [subject difficultyLevel: 1. refresh]. (i18n: 'Medium') -> [subject difficultyLevel: 2. refresh]. (i18n: 'Hard') -> [subject difficultyLevel: 3. refresh]. } ) setLanguageMenu = ( ^menuWithLabelsAndActions: { (i18n: 'English') -> [currentLanguage: 'English'. refresh]. (i18n: 'Russian') -> [currentLanguage: 'Russian'. refresh]. } ) startNewGame = ( enterPresenter: (BoardPresenter onSubject: (BoardSubject newValidBoardWithDifficulty: subject difficultyLevel)) ) title = ( ^i18n: 'Home page' ) ) class BoardPresenter onSubject: s = Presenter onSubject: s( | |boardPresenter:: self. showConflictMode:: false. ) ('as yet unclassified' actionsMenu = ( ^menuWithLabelsAndActions: { 'Inspect in Squeak' -> [respondToInspectInSqueak]. 'Explore in Squeak' -> [respondToExploreInSqueak]. 'Inspect Presenter' -> [respondToInspectPresenter]. } ) checkSolutionFragment = ( ^showConflictMode ifTrue: [subject model solved ifTrue: [label: (i18n: 'Contgratulations! Puzzle solved')] ifFalse: [link: (i18n: 'Return to game' ) action: [showOrHideConflicts]]] ifFalse: [link: (i18n: 'Show conflicts') action: [showOrHideConflicts]] ) definition = ( ^column: { toolbarDefinition. blank: 5. BoardGridPresenter onSubject: subject. } ) showOrHideConflicts = ( showWaitCursorWhile: [ showConflictMode:: showConflictMode not. subject model resetConflicts. self refresh.] ) showOrHideLabel = ( ^showConflictMode ifTrue: ['Hide conflicts'] ifFalse: ['Show conflicts'] ) title = ( ^(i18n: 'Sudoku. Difficulty: ') , subject model difficultyLabel , (i18n: '. Started at ') , subject startedAt print24 ) toolbarDefinition = ( ^row: { blank: 5. holder: [checkSolutionFragment]. } ) )'as yet unclassified' i18n: aStr = ( ^i18nEngine translate: aStr. ) )