Now that we have a button, we need to figure out how to create a new randomized game grid.
Add a new class variable to the GridFactory class.
Object subclass: #GridFactory
instanceVariableNames: ''
classVariableNames: 'RandomNumberGenerator'
poolDictionaries: ''
category: 'Laser-Game-Model'
Make a new class method on GridFactory to initialize our new randomizer if it's being accessed the very first time.
randomNumberGenerator
RandomNumberGenerator isNil ifTrue: [
RandomNumberGenerator := Random new.
RandomNumberGenerator seed: Time totalSeconds].
^RandomNumberGenerator
We're going to want a mechanism to re-seed our random number generator in the future. Add the following class method.
reSeed
self randomNumberGenerator seed: Time totalSeconds
Here are a bunch of new class methods to handle randomization of components for our game.
emptyRandomLocationsFor: aGrid
| dict |
dict := Dictionary new.
1 to: aGrid numberOfColumns do: [:x |
1 to: aGrid numberOfRows do: [:y |
| pt |
pt := x@y.
dict at: pt put: false]].
dict at: 5@1 put: true. "Target Cell"
^dict
unusedRandomLocationIn: list forGrid: aGrid
| x y pt |
[
x := self randomNumberGenerator nextInt: aGrid numberOfColumns.
y := self randomNumberGenerator nextInt: aGrid numberOfRows.
pt := x@y.
list includesKey: pt
] whileTrue: [].
list at: pt put: true.
^pt
randomBoolean
| int |
int := self randomNumberGenerator nextInt: 2.
^int > 1
randomizedMirrorCell
^self randomBoolean
ifTrue: [MirrorCell leanLeft]
ifFalse: [MirrorCell leanRight]
Now we add a new class method that will randomize a given Grid.
randomizeGrid: aGrid
| emptyList loc howMany |
emptyList := self emptyRandomLocationsFor: aGrid.
aGrid at: 5@1 put: TargetCell new.
howMany := 10.
howMany timesRepeat: [
loc := self unusedRandomLocationIn: emptyList forGrid: aGrid.
aGrid at: loc put: self randomizedMirrorCell]