Puzzle on a User Form

The final example in this chapter is a familiar sliding puzzle, displayed on a UserForm (see Figure 15-28). This puzzle was invented by Noyes Chapman in the late 1800s.

Sliding Tile Puzzle

1

2

9

8

6

3

4

13

5

7

12

10

15

11

Figure 15-28: A sliding tile puzzle in a UserForm.

The goal is to arrange the shuffled tiles (commandButton controls) in numerical order. Click a button next to the empty space, and the button moves to the empty space. The comboBox control lets the user choose from three configurations: 3x3, 4x4, and 5x5. The New button shuffles the tiles, and a Label control keeps track of the number of moves.

This application uses a class module to handle all the button events (see "Handling Multiple UserForm Controls with One Event Handler," earlier in this chapter).

The VBA code is rather lengthy, so it's not listed here. Here are a few points to keep in mind when examining the code:

■ The CommandButton controls are added to the UserForm via code. The number and size of the buttons are determined by the ComboBox value.

■ The tiles are shuffled by simulating a few thousand random clicks on the buttons. Another option is to simply assign random numbers, but that would result in some unsolvable games.

■ The blank space is actually a CommandButton with its Visible property set to False.

■ The class module contains one event procedure (Mouseup), which is executed whenever the user clicks a tile.

■ When the user clicks a CommandButton tile, its caption is swapped with the hidden button. No buttons are actually moved.

CD- This workbook, named sliding tile puzzle.xlsm, is available on the companion ROM CD-ROM.

4 PREV

0 0

Post a comment