Section 4

Add Move Counter And Randomizer

We're going to keep adding enhancements to our LaserGame. Here's how it looks today.

We will be adding 2 new features. The first will be a Moves counter. The moves counter will show the total number of cell clicks on the game board. The idea is that the player will want to minimize this count as they solve the puzzle.

The second feature will be to add a random game generator. This will allow us to include a "New Game" button which will generate a new randomized mix of Mirror Cells on our board game grid.

Let's get started. The first thing to do is add a way to keep track of the moves count. We will accomplish this by adding a new instance variable "moves" to the LaserGame class definition.

Create the accessors that includes #moves and #moves:. The #initialize method should be modified to set "moves" to zero.

initialize
    super initialize.
    self moves: 0.
    self grid: GridFactory demoGrid.
    self boardForm: (Form extent: (self class boardExtentFor: self grid) depth: Display depth).
    self boardForm fillColor: LaserGameColors gameBoardBackgroundColor.
    self setExtent.
    self setupMorphs.
    self drawGameBoard.

Now we add something to create a control panel to display the "moves".

makeMovesCounterMorph
    | count |
    count := LedMorph new
            digits: 3;
            extent: 3 * 10 @ 15;
            setBalloonText: ''.
    count color: (Color r: 0.674 g: 0.674 b: 0.96).
    count name: 'moves'.
    ^ self wrapPanel: count label: 'Moves'

Modify the #addCountersToPanel: method to include the new panel.

addCountersToPanel: panel
    panel
        addMorph: self makeLaserPathCounterMorph
        fullFrame: (LayoutFrame
            fractions: (0 @ 0 corner: 1 @ 0)
            offsets: (4 @ 4 corner: -8 @ 44));

        addMorph: self makeMovesCounterMorph
        fullFrame: (LayoutFrame
            fractions: (0 @ 0 corner: 1 @ 0)
            offsets: (4 @ 48 corner: -8 @ 92))

Since we'll be updating the moves counter we'll need a new instance method to help us find it.

findMovesCounter
    ^self allMorphs detect: [:m | m knownName = 'moves'] ifNone: []

Modify the method that updates our counters.

updateCounters
    | led |
    led := self findLaserPathCounter.
    led notNil ifTrue: [
        self laserActive
            ifTrue: [led
                highlighted: true;
                value: self grid laserBeamPath size]
            ifFalse: [led
                highlighted: false;
                value: 0]
            ].
    led := self findMovesCounter.
    led notNil ifTrue: [
        led
            highlighted: false;
            value: self moves asString]

Add in a new instance method to increment the moves counter.

incrementMoves
    self moves: self moves + 1

Index Page Next Page

Copyright © 2007, 2008, 2009, 2010 Stephan B Wessels    stevewessels@me.com