12. Arrays and Array Processing

12.12. A GUI-Based Game (Optional Graphics)

Most modern computer games do not use a command-line interface. This section addresses this shortcoming by expanding our ComputerGame hi- erarchy so that it works with Graphical User Interfaces (GUIs) as well as Command-Line User Interfaces (CLUIs).

The Sliding Tile Puzzle is a puzzle game. It is played by one player, a human. The puzzle consists of six tiles arranged on a board contain- ing seven spaces. Three of the tiles are labeled L and three are labeled R. Initially the tiles are arranged as RRR LLL. In other words, the R tiles are arranged to the left of the L tiles, with the blank space in the middle. The object of the puzzle is to rearrange the tiles into LLL RRR. The rules are that tiles labeled R can only move right. Tiles labeled L can only move left. Tiles may move directly into the blank space or they can jump over one tile into the blank space.

Our purpose in this section is to develop a GUI that plays this game. An appropriate GUI is shown Figure 9.35. Here the tiles and the blank space are represented by an array of buttons. To make a move the user clicks on the ’tile’ he or she wishes to move. The GUI will assume that the user wants to move that tile into the blank space. If the proposed move

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure9.36:The GUIPlayableGame interface extends the IGame interface.


is legal, the GUI will carry out the move. Otherwise, it will just ignore it. For example, if the user were to click on the third R button from the left, a legal move, the GUI would rearrange the labels on the buttons so that their new configuration would be RR RLLL. On the other hand, if the user were to click on the rightmost L button, the GUI would ignore that move, because it is illegal.

The GUIPlayableGame Interface

How should we extend our game-playing hierarchy to accommodate GUI-based games? As we learned in Chapter 4, one difference between GUI-based applications and CLUI-based applications, is the locus of con- trol. In a CLUI-based application, control resides in the computational ob- ject which, for games, is the game object. That’s why the play() method in our CLUI-based games contains the game’s control loop. By contrast, control resides in the GUI’s event loop in GUI-based applications. That’s why, we learned how to manage Java’s event hierarchy in Chapter 4. Thus, in the GUI shown in Figure 9.35, the GUI will listen and take action when the user clicks one of its buttons.

However, given that control will reside in the GUI, there is still a need for communication between the GUI and the game object. In the CLUI- based games, we have used the CLUIPlayableGame interface to man- age the communication between the game and the user interface. We will follow the same design strategy in this case. Thus, we will design a GUIPlayableGame interface that can be implemented by any game that wishes to use a GUI (Fig. 9.36).

What method(s) should this interface contain? One way to answer this question is to think about the type of interaction that must take place when the user clicks one of the tiles. If the user clicks the third R button, the GUI should pass this information to the game. The game should then decide whether or not that is a legal move and communicate this back to the GUI. Assuming it is a legal move, the game should also update its representation of the game’s state to reflect that the tile array has changed. And it should somehow make communicate the game’s state to the GUI.

Because it is impossible to know in advance just what form of data a game’s moves might take, we will use Java Strings to communicate between the user interface and the game object. Thus, a method with the following signature will enable us to submit a String representing the user’s move to the game and receive in return a String representing the game object’s response to the move:

,,

 

 

J

In addition to this method, a GUI interface could use the reportGame- State() and getGamePrompt() methods that are part of the IGame interface. Th design shown in Figure 9.36 leads to the following definition for the GUIPlayableGame interface:

,,

 

 

J

 

Because it extends IGame, this interface inherits the getGamePrompt() and reportGameState() from the IGame interface. The GUI should be able to communicate with any game that implements this interface.

 

 

 

The SlidingTilePuzzle

 

 

 

Let’s now discuss the design and details of the SlidingTilePuzzle it- self. Its design is summarized in Figure 9.37. Most of the methods should be familiar to you, because the design closely follows the design we em- ployed in the WordGuess example. It has implementations of inher- ited methods from the ComputerGame class and the GUIPlayableGame interface.

We will represent the sliding tile puzzle in a one-dimensional array of char. We will store the puzzle’s solution in a Java String and we will use an int variable to keep track of where the blank space is in the array. This leads to the following class-level declarations:

,

 

 

 

Note how we initialize the puzzle array with the initial configuration of seven characters. Taken together, these statements initialize the puzzle’s state.

Because a puzzle is a one-person game and our sliding tile puzzle will be played by a human, this leads to a very simple constructor definition:

,

 

 

 

We call the super() constructor (ComputerGame()) to create a one- person game.

The puzzle’s state needs to be communicated to the GUI as a String.

This is the purpose of the reportGameState() method:

,


JFigure9.37:The

SlidingTilePuzzleisa

ComputerGame that implements the GUIPlayableGame interface.

 

,

 

 

 

 

J

We use a StringBuffer() to convert the puzzle, a char array, into a

String.

 

The most important method for communicating with the GUI is the

submitUserMove() method:

,,

 

 

 

 

 

 

 

 

 

J

This is the method that processes the user’s move, which is communi- cated through the GUI. As we saw, the puzzle’s ’tiles’ are represented by an array of buttons in the GUI. The buttons are indexed 0 through 6 in the array. When the user clicks a button, the GUI should pass its index, repre- sented as a String to the submitUserMove() method. Given the index number of the tile that was selected by the user, this method determines if the move is legal.

The Integer.parseInt() method is used to extract the tile’s index from the method’s parameter. This index is used to get a ’tile’ from the puzzle array. The logic in this method reflects the rules of the game. If the tile is an L, then it can only move into a blank space that is either 1 or 2 spaces to its left. Similarly, an R tile can only move into a blank space that is 1 or 2 spaces to its right. All other moves are illegal. For legal moves, we simply swap the tile and the blank space in the array, a task handled by the swap() method. In either case, the method returns a string reporting whether the move was legal or illegal.

Figure 9.38 shows the full implementation for the SlidingTilePuzzle, the remaining details of which are straight forward.

 

The SlidingGUI Class

 

 

Let’s now implement a GUI that can be used to play the sliding tile puzzle. We will model the GUI itself after those we designed in Chapter 4.

Figure 9.39 provides a summary of the design. As an implemen- tor of the ActionListener interface, SlidingGUI implements the actionPerformed() method, which is where the code that controls the puzzle is located. The main data structure is an array of seven JButtons, representing the seven tiles in the puzzles. The buttons’ labels will reflect the state of the puzzle. They will be rearranged after every legal move by the user. The reset button is used to reinitialize the game. This allows users to play again or to start over if they get stuck.

The puzzleState is a String variable that stores the puzzle’s current state, which is updated repeatedly from the SlidingTilePuzzle by calling its reportGameState() method. The private labelButtons() method will read the puzzleState and use its letters to set the labels of the GUI’s buttons.

The implementation of SlidingGUI is shown in Figure 9.40. Its con- structor and buildGUI() methods are responsible for setting up the GUI. We use of a for loop in buildGUI() to create the JButtons, asso- ciate an ActionListener with them, and add them to the GUI. Except for the fact that we have an array of buttons, this is very similar to the GUI created in Chapter 4. Recall that associating an ActionListener with the buttons allows the program to respond to button clicks in its actionPerformed() method.

Note how an instance of the SlidingTilePuzzle is created in the constructor, and how its state is retrieved and stored in the puzzleState variable:


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 9.39:The SlidingGUI

class.

 

,,

 

J

The labelButtons() method transfers the letters in puzzleState

onto the buttons.

The most important method in the GUI is the actionPerformed() method. This method controls the GUI’s actions and is called automat- ically whenever one of the GUI’s buttons is clicked. First, we check whether the reset button has been clicked. If so, we reset the puzzle by creating a new instance of SlidingTilePuzzle and re-initializing the prompt label.

Next we use a for loop to check whether one of the tile buttons has been clicked. If so, we use the loop index, k, as the tile’s identification and submit this to the puzzle as the user’s move:

,,

 

J

The cast operation is necessary here because we declared sliding as a SlidingTilePuzzle rather than as a GUIPlayableGame. Note also that we have to convert k to a String when passing it to submitUserMove().

 

As a result of this method call, the puzzle returns a result, which is checked to see if the user’s move was illegal. If result contains the word “illegal”, the computer beeps to signal an error:

,,

 

J

The java.awt.Toolkit is a class that contains lots of useful meth- ods, including the beep() method. Note that no matter what action is performed, a reset or a tile click, we update puzzleState by call- ing reportGameState() and use it to relabel the tile buttons. The last task in the actionPerformed() method is to invoke the puzzle’s gameOver() method to check if the user has successfully completed the puzzle. If so, we display a congratulatory message in the GUI’s window.

Finally, the main() for a GUI is very simple, consisting of a single line of code:

,,

 

J

Once a SlidingGUI is created, with the title of “Sliding Tile Puzzle,” it will open a window and manage the control of the puzzle.

 

 

 

 

 

 

CHAPTER SUMMARYTechnical Terms

array array

initializer array length binary search data structure element element type


 

insertion sort multidimensional

array

one-dimensional array

polymorphic sort method

selection sort


 

sequential search sorting

subscript

two-dimensional array

 

 

 

Summary of Important Points

An array is a named collection of contiguous storage locations, each of which stores a data item of the same data type. Each element of an array is referred to by a subscript—that is, by its position in the array. If the array contains N elements, then its length is N and its indexes are 0, 1, ...N-1.

Array elements are referred to using the following subscript notation

arrayname[subscript], where arrayname is any valid identifier, and sub- script is an integer value in the range 0 to arrayname.length - 1. The array’s length instance variable can be used as a bound for loops that process the array.

 

An array declaration provides the name and type of the array. An array instantiation uses the keyword new and causes the compiler to allocate memory for the array’s elements:

,,

 

J

Multidimensional arrays have arrays as their components:

,,

 

J

An array’s values must be initialized by assigning values to each array location. An initializer expression may be included as part of the array declaration.

Insertion sort and selection sort are examples of array sorting algo- rithms. Both algorithms require several passes over the array.

When an array is passed as a argument to a method, a reference to the array is passed rather than the entire array itself.

Swapping two elements of an array, or any two locations in memory, requires the use of a temporary variable.

Sequential search and binary search are examples of array searching algorithms. Binary search requires that the array be sorted.

For multidimensional arrays, each dimension of the array has its own

length variable.

Inheritance and polymorphism are useful design features for develop- ing a hierarchy of computer games.

 

 

 

 

SOLUTION 9.1 Space (in bytes) allocated for each of the following?

int a[] = new int[5];// 5 * 4 = 20 bytes

double b[] = new double[10];// 10 * 8 = 80 bytes

char c[] = new char[30];// 30 * 2 = 60 bytes

String s[] = new String[10];// 10 * 4 (reference) = 40 bytes

Student s[] = new Student[5]; // 5 * 4 (reference) = 20 bytes

SOLUTION 9.2 An array containing 10 floats, 1.0 to 10.0.

,,


SOLUTIONS TO

SELF-STUDY EXERCISES

 

 

J

SOLUTION 9.3 Prints the first element of farr.

,,

 

J

SOLUTION 9.4 Assigns 100.0 to the last element in farr.

,,

 

J

 

SOLUTION 9.5 A loop to print all of the elements of farr.

,

 

J

 

 

SOLUTION 9.6 An array containing the first 100 square roots.

,

 

 

J

 

 

SOLUTION 9.7 Analyzing the letter frequencies in a file.

,

 

 

 

 

 

 

 

 

 

 

 

 

 

J

 

 

SOLUTION 9.8 Sort 24 18 90 1 0 85 34 18 with insertion sort.

,,

 

 

 

 

 

\J

 

SOLUTION 9.9 Sort 24 18 90 1 0 85 34 18 with selection sort.

,,

 

 

 

 

 

J

SOLUTION 9.10 Code to swap two Students.

,,

 

 

\J

 

 

 

 

 

 

 

 

 

 

 

 

J

SOLUTION 9.12 After mystery(myArr,k), myArr will store 1,2,3,5,5 and k

will store 3.

SOLUTION 9.13 Binary search trace for 21 in 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22,

24, 26, 28:

,,

 

 

 

 

 

\J

SOLUTION 9.14 A two-dimensional array with 5 rows of 10 integers.

,,

 

J

 

SOLUTION 9.15 Prints the last integer in the third row int2d and assigns 100 to its last element.

,,

 

J

 

 

SOLUTION 9.16 Prints all of the elements of int2d.

,,

 

 

 

J

 

 

SOLUTION 9.17 A 52 × 7 two-dimensional array of int.

,,

 

 

 

J

 

 

SOLUTION 9.18 A method to calculate average number of newspapers per week.

,,

 

 

 

 

 

J

 

 

SOLUTION 9.19 A method to calculate average Sunday newspapers.

,,

 

 

 

 

J

 

SOLUTION 9.20 A compareTo() for LetterFreq.

,,

 

 

 

 

 

J

SOLUTION 9.21 A sort() for AnalyzeFreq.

,,

 

 

J

SOLUTION 9.22 A new AnalyzeFreq.main() that uses sort().

,,

 

 

 

 

 

J

 

 

 

EXERCISE 9.1 Explain the difference between the following pairs of terms:

An element and an element type.

A subscript and an array element.

A one-dimensional array and two-dimensional array.

An array and a vector.

A insertion sort and a selection sort.

A binary search and a sequential search. EXERCISE 9.2 Fill in the blanks.

The process of arranging an array’s elements into a particular order is known as.

One of the preconditions of the binary search method is that the array has to be

.

Anis an object that can store a collection of elements of the same type.

Anis like an array except that it can grow.

For an array, itsis represented by an instance variable.

An expression that can be used during array instantiation to assign values to the array is known as an.


EXERCISES

Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.

 

Ais an array of arrays.

A sort method that can be used to sort different types of data is known as a

method.

To instantiate an array you have to use theoperator.

An array of objects storesto the objects.

 

EXERCISE 9.3 Make each of the following array declarations:

A 4 × 4 array of doubles.

A 20 × 5 array of Strings.

A 3 × 4 array of char initialized to ‘*’;

A 2 × 3 × 2 array of boolean initialized to true.

A 3 × 3 array of Students.

A 2 × 3 array of Strings initialized to “one,” “two,” and so on.

EXERCISE 9.4 Identify and correct the syntax error in each of the following expressions:

int arr = new int[15];

int arr[] = new int(15);

float arr[] = new [3];

float arr[] = new float {1.0,2.0,3.0};

e. int arr[] = {1.1,2.2,3.3};

f. int arr[][] = new double[5][4];

g. int arr[][] = { {1.1,2.2}, {3.3, 1} };

 

EXERCISE 9.5 Evaluate each of the following expressions, some of which may be erroneous:

,,

 

 

 

arr[4]

arr[ arr.length ]

arr[ arr[0] ]

arr[ arr.length / 2 ]

arr[ arr[1] ]


J

arr[ 5 % 2 ]

arr[ arr[ arr[0] ] ]

h. arr[ 5 / 2.0 ]

arr[ 1 + (int) Math.random() ]

arr[ arr[3] / 2 ]

 

 

EXERCISE 9.6 What would be printed by the following code segment?

,,

 

 

J

 

EXERCISE 9.7 What would be printed by the following code segment?

,,

 

 

 

J

 

EXERCISE 9.8 What would be printed by the following code segment?

,,

 

 

 

J

EXERCISE 9.9 What’s wrong with the following code segment, which is sup- posed to swap the values of the int variables, n1 and n2?

,,

 

 

J

EXERCISE 9.10 Explain why the following method does not successfully swap the values of its two parameters? Hint: Think about the difference between value and reference parameters.

,,

 

 

 

J

EXERCISE 9.11 Declare and initialize an array to store the following two- dimensional table of values:

,,

 

 

J

EXERCISE 9.12 For the two-dimensional array you created in the previous ex- ercise, write a nested for loop to print the values in the following order: 1 5 9 2 6 10 3 7 11 4 8 12. That is, print the values going down the columns instead of going across the rows.

EXERCISE 9.13 Define an array that would be suitable for storing the following values:

The GPAs of 2,000 students.

The lengths and widths of 100 rectangles.

A week’s worth of hourly temperature measurements, stored so that it is easy to calculate the average daily temperature.

A board for a tic-tac-toe game.

The names and capitals of the 50 states.

EXERCISE 9.14 Write a code segment that will compute the sum of all the ele- ments of an array of int.

EXERCISE 9.15 Write a code segment that will compute the sum of the elements in a two-dimensional array of int.

 

EXERCISE 9.16 Write a method that will compute the average of all the ele- ments of a two-dimensional array of float.

 

EXERCISE 9.17 Write a method that takes two parameters, an int array and an integer, and returns the location of the last element of the array that is greater than or equal to the second parameter.

 

EXERCISE 9.18 Write a program that tests whether a 3 3 array, input by the user, is a magic square. A magic square is an N N matrix of numbers in which every number from 1 to N2 must appear just once, and every row, column, and diagonal must add up to the same total—for example,

,,

 

 

J

 

EXERCISE 9.19 Revise the program in the previous exercise so that it allows the user to input the dimensions of the array, up to 4 × 4.

EXERCISE 9.20 Modify the AnalyzeFreq program so that it can display the relative frequencies of the 10 most frequent and 10 least frequent letters.

 

EXERCISE 9.21 The merge sort algorithm takes two collections of data that have been sorted and merges them together. Write a program that takes two 25-element int arrays, sorts them, and then merges them, in order, into one 50-element array.

 

EXERCISE 9.22 Challenge: Design and implement a BigInteger class that can add and subtract integers with up to 25 digits. Your class should also include methods for input and output of the numbers. If you’re really ambitious, include methods for multiplication and division.

 

EXERCISE 9.23 Challenge: Design a data structure for this problem: As man- ager of Computer Warehouse, you want to track the dollar amount of purchases made by those clients that have regular accounts. The accounts are numbered from 0, 1, ..., N. The problem is that you don’t know in advance how many purchases each account will have. Some may have one or two purchases. Others may have 50 purchases.

 

EXERCISE 9.24 An anagram is a word made by rearranging the letters of another word. For example, act is an anagram of cat, and aegllry is an anagram of allergy. Write a Java program that accepts two words as input and determines if they are anagrams.

 

EXERCISE 9.25 Challenge: An anagram dictionary is a dictionary that organizes words together with their anagrams. Write a program that lets the user enter up to 100 words (in a TextField, say). After each word is entered, the program should display (in a TextArea perhaps) the complete anagram dictionary for the words entered. Use the following sample format for the dictionary. Here the words entered by the user were: felt, left, cat, act, opt, pot, top.

,,

 

 

J

 

EXERCISE 9.26 Acme Trucking Company has hired you to write software to help dispatch its trucks. One important element of this software is knowing the distance between any two cities that it services. Design and implement a Distance class that stores the distances between cities in a two-dimensional ar- ray. This class will need some way to map a city name, Boise, into an integer that can be used as an array subscript. The class should also contain methods that would make it useful for looking up the distance between two cities. Another useful method would tell the user the closest city to a given city.

EXERCISE 9.27 Rewrite the main() method for the WordGuess example so that it allows the user to input the number of players and whether each players is a computer or a human. Use a KeyboardReader.

EXERCISE 9.28 Write a smarter version of the WordGuesser class that “knows” which letters of the English language are most frequent. HINT: Rather than using random guesses, store the player’s guesses in a string in order of decreasing frequency: ”ETAONRISHLGCMFBDGPUKJVWQXYZ”.

EXERCISE 9.29 Write a CLUI version of the SlidingTilePuzzle. You will need to make modifications to the SlidingTilePuzzle class.

 

 

 

 

 

 

 

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

//

S o r t

a n d

p r i n t

I n t e g e r s

//

S o r t

a n d

p r i n t

F l o a t s

 

 

J

Figure 9.26: TestSort uses the polymorphic sort() method to sort either Integers or Floats.

 

 

 

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 9.28: Demonstration of the Vector class.

 

 

 

 

 

 

 

Figure 9.29:Overview of the

ComputerGame class hierarchy.

 

 

 

 

 

,,

public a b s t r a c t c l a s s ComputerGame

protected in t n Players ;

protected in t addedPlayers = 0 ;

protected in t whoseTurn ;

protected Player player [ ] ;// An a r r a y o f p l a y e r s

 

public ComputerGame ( )

n Players = 1 ;// D e f a u l t : 1 p l a y e r ga m e

player = new Player [ 1 ] ;

}p ublic ComputerGame ( in t n ) n Players = n ;

player = new Player [ n ] ; // N P l a y e r ga m e

}p ublic void s e t P l a ye r ( in t s t a r t e r )

whoseTurn = s t a r t e r ;

}p ublic in t get Player ( )

return whoseTurn ;

}p ublic void addPlayer ( Player p) player [ addedPlayers ] = p ;

++addedPlayers ;

}p ublic void change Player ( )

whoseTurn = ( whoseTurn + 1 ) % n Players ;

}p ublic S t r i n g get Rules ( )

return ”The r ul e s of t h i s game are : ;

}p ublic S t r i n g l i s t P l a y e r s ( ) S t r i n g B u f fe r r e s u l t =

new S t r i n g B u f fe r ( nThe players are : n” ) ;

for ( in t k = 0 ; k < n Players ; k++)

r e s u l t . append ( Player + k + +

 

 

r e s u l t . append (


player [ k ] . t o S t r i n g ( ) + \n” ) ;

\n” ) ;

 

return r e s u l t . t o S t r i n g ( ) ;

}p ublic a b s t r a c t boolean gameOver ( ) ; // A b s t r a c t

public a b s t r a c t S t r i n g getWinner ( ) ; //m e t h o d s

// C o m p u t e r G a m e

\J

Figure 9.31: Implementation of the ComputerGame class.

 

 

 

 

 

 

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 9.34: Implementation of the Player class.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 9.35: The Sliding Tile Puz- zle.

 

 

 

 

,,

public c l a s s S l i di n g T i l e P uzzle extends ComputerGame

implements GUIPlayableGame

private char puzzle [ ] =’R , ’R , ’R , , ’L , ’L , ’L ;

private S t r i n g s o lut i o n = ”LLL RRR” ;

private in t blankAt = 3 ;

public S l i di n g T i l e P uzzle ( ) { super ( 1 ) ; }

public boolean gameOver ( )// T r u e i f p u z z l e s o l v e d

S t r i n g B u f fe r sb = new S t r i n g B u f fe r ( ) ; sb . append ( puzzle ) ;

return sb . t o S t r i n g ( ) . equals ( s o lut i o n ) ;

}p ublic S t r i n g getWinner ( )

i f ( gameOver ( ) )

return \nYou did i t ! Very Nice ! \ n” ;

e ls e return \nGood t r y . Try again ! \ n” ;

}p ublic S t r i n g report Game State ( )

S t r i n g B u f fe r sb = new S t r i n g B u f fe r ( ) ; sb . append ( puzzle ) ;

return sb . t o S t r i n g ( ) ;

}p ublic S t r i n g getGamePrompt ( )

return ”To move a t i l e , c l i c k on i t . ;

} // p r o m p t ( )

public S t r i n g submitUserMove ( S t r i n g usermove )

in t t i l e = I n t e ge r . pa r s e Int ( usermove ) ;

char ch = puzzle [ t i l e ] ;

i f ( ch== ’L && ( blankAt== t i l e 1blankAt== t i l e2 )) swap Tiles ( t i l e , blankAt ) ;

e ls e i f ( ch== ’R &&

( blankAt== t i l e +1blankAt== t i l e + 2 ) ) swap Tiles ( t i l e , blankAt ) ;

e ls e

return That s an i l l e g a l move . \ n” ;

return That move i s l e g a l . \ n” ;

}p r ivate void swap Tiles ( in t t i , in t bl )

char ch = puzzle [ t i ] ;

puzzle [ t i ] = puzzle [ bl ] ; puzzle [ bl ] = ch ;

blankAt = t i ;// R e s e t t h e b l a n k

}

// S l i d i n g T i l e P u z z l e

\J

Figure 9.38: Implementation of the SlidingTilePuzzle class.

 

 

 

 

 

,,

import j avax . swing . ;

import j ava . awt . ;

import j ava . awt . event . ;

public c l a s s SlidingGUI extends JFrame implements Action Listener

private JButton t i l e [ ] = new JButton [ 7 ] ;

private JButton r e s e t = new JButton ( Reset ) ;

private S l i di n g T i l e P uzzle s l i d i n g ;

private S t r i n g puzzle State ;

private Label label ;

private S t r i n g prompt = ” Goal : [ LLL RRR ] . ” + Click on the t i l e you want to move . ” +

I l l e g a l moves are ignored . ;

public SlidingGUI ( S t r i n g t i t l e )

s l i d i n g = new S l i di n g T i l e P uzzle ( ) ; buildGUI ( ) ;

s e t T i t l e ( t i t l e ) ; pack ( ) ;

s e t V i s i b l e ( t rue ) ;

// SlidingGUI ( )

private void buildGUI ( )

Container content Pane = get Content Pane ( ) ; content Pane . set Layout ( new BorderLayout ( ) ) ; JPanel buttons = new JPanel ( ) ;

puzzle State = s l i d i n g . report Game State ( ) ;

for ( in t k = 0 ; k < t i l e . length ; k++)

t i l e [ k ] = new JButton ( ””+puzzle State . charAt ( k ) ) ; t i l e [ k ] . add Action Listener ( t h i s ) ;

buttons . add ( t i l e [ k ] ) ;

}r e s e t . add Action Listener ( t h i s ) ;

label = new Label ( prompt ) ; buttons . add ( r e s e t ) ;

content Pane . add ( Center , buttons ) ; content Pane . add ( South” , label ) ;

// buildGUI ( )

private void la b e l B ut t ons ( S t r i n g s )

for ( in t k = 0 ; k < t i l e . length ; k++) t i l e [ k ] . s e t T e xt ( ””+ s . charAt ( k ) ) ;

// la b e l B ut t o ns ( )

public void action Performed ( ActionEvent e ) S t r i n g r e s u l t = ”” ;

i f ( e . get Source ( ) == r e s e t )// Reset c l i c k e d ? s l i d i n g = new S l i di n g T i l e P uzzle ( ) ;

label . s e t T e xt ( prompt ) ;

}f or ( in t k = 0 ; k < t i l e . length ; k++) // T i l e c l i c k e d ?

i f ( e . get Source ( ) == t i l e [ k ] )

r e s u l t = ( ( GUIPlayableGame ) s l i d i n g ) . submitUserMove ( ””+ k ) ;

i f ( r e s u l t . indexOf ( i l l e g a l ) ! =1)

j ava . awt . T o olkit . ge t De fa ult T o o lki t ( ) . beep ( ) ; puzzle State = s l i d i n g . report Game State ( ) ;

la b e l B ut t ons ( puzzle State ) ;

i f ( s l i d i n g . gameOver ( ) )

label . s e t T e xt ( ”You did i t ! Very nice ! ) ;

// action Performed ( )

public s t a t i c void main ( S t r i n g args [ ] )

new SlidingGUI ( S l i di n g T i l e Puzzle ) ;

} // main ( )

\} // SlidingGUI J

Figure 9.40: Implementation of the SlidingGUI class.

 

 

 

 

 

 

 

 

 

 

 

Chapter 10