accept( ) is the method called on the remote side in response to the server.accept )
call just mentioned, Just <IS the other player deleted hims,elf .or herself from the list of.available players, so must we call server.delete( ). We take the first turn by setting.

chat( )
The chat( ) method is called by the server whenever opponent types in his or her chat lVindow.ln this implementation, the method simply shows the chat message in the browser's status message. In the future, it might be nice to log these into a TextArea.

move( )
The move() method is called once for each tile your opponent plays. I~looks through.the letters saved in theirs to find the one 'used. If the square is already occupied , the retumed to the player's tray. Otherwise, the opponent's letter is moved onto the board permanently. Next, the tile is replaced in theirs by bag takeOut( ). If t he bag is empty, 'a status message apgears. The board is repainted to show the new tiles on it. ,Note that no seating is 'donabased on the placement, of these tiles. The applet waits until turn( ) is called to give the seore."

The tum() method is called after all of the opponent's tiles aremoved. The remote .
instance of Scrabblet computes the score and sends it to us, so'our copy doesn't have
to redo it. Then-the score is reported in the status line, and the setEnabled mefhod .
allows us to take a turn, othersTurn( ) tells the board about the score. The board will
reflect the new score at this point.

 nameEntered( )
The nameEntered( ) method is called from actionl'erformedt ) whenever ENTER is
pressed in the original prompt for the user's name. Any AWT components that might be in the way are removed, and then a new List object, idList, is created to store the names of the other players. The method also adds a button at the top named challenge, then notifies the server that we are here by calling setName().

weplck( ) and theyplck( )
The methods wepickt ) and theypic:k( ) are simply used to start of! the game by picking the seven tiles for each player. It is important that the caller do these in the 'right order on each side of !he challenge, depending on who goes first. The call to bag.takeOut( ) gets a single letter permanently-out of the shared bag. The call to
board addLetter( ) places the tile on our tray. For the, other side, theypick( ) simply saves the letters in theirs.

start_Game( ) 
In single-player mode, slarCGame() Pops up the splash screen in a Frame window. It : then creates 4 playing board, passing in no parameters to the constructor, which . indicates single-player mode.  , In head-tcFhead mode, we remove the selection list components and add the chat ,window to the applet, We then add the board and Done button to the applel Next, we create the bas. and if it lseurtum, wepick() is first, then theyPick(). In the case where we don't have-the first turn.we disable the board and the Done button, and they pick() '.is first. We then force the board to repaint, which initializes it.

our_turn( )
When the Done button is clicked, our_turn( ) is called: First, it checks to see if we've
.placed tiles in valid locations by calling board.findwords( ) and storing the result in
word. If word is null, then something is amiss with the tiles,' and the method shows
that in the status line. If word is I'll, then it knows that there were no tiles in play at the time. In single-player mode, this is igno~d. In competition mode, if we dick Done twice in a row without any tiles in play, we will pass our tum to our opponent.
If you have played tiles and they are in legal positions, you have finished your turn,'
. so ourtum( ) commits the letters to the board. Notice that commit( ) takes the server as . .a parameter. It will use this to tell the remote side about the position of each new letter . .Then the method replaces the letters you used; In multiplayer mode, Wedisable ," ourselves and call server.turnt ) to tell the other player it is his or her turn.

actionPerformed( ) 
The action Performed() method is used to grab input from the various components the , appJet uses. It handles the Challenge and Done buttons, as well as the name entry field and the ch~t entry field.
The IntroCanvas subclass of Canvas is very simple. It just overrides paint( ) to draw
the name of the applet and a brief copyright notice. It creates some custom colors and - fonts, The display strings are held in static variables simply for clarity.

d( ) .
The private method d( ) is a convenience method that paints centered text with an
optional isometric offset. This is used to give the main title a highlight/shadow effect by drawing a white string up and to the left by 1. a black string down and to the right by 1,and then drawing the string one last time in pink, not offset at all,

mousePressed{ ) ,
In the following code fragment, notice that MyMouseAdapter is an inner class that'.
.extends MouseAdapter. It overrides the mousePressed( ) method to cause this canvas' parent to hide( ) if it is clicked on. This is only .useful in single-player mode to dismiss " the pop-up frame.

The Board class encapsulates m~st; ot the game logic as well as th2100k and feel of the board. It is the biggest class in the game, weighing in at over 500 lines of code. There are several private variables that store the game state. The lSx15 array of Letters ' named board is used to store the tiles on each square of the boardtThe tray array holds. the Letters that are currently on our tray. Remember that the Scrablet applet class . holds the seven Letters from our opponent. The Point objects orig and here are used to . remember letter positions. The name and others_name variables re used simply to display names for the scoreboard. In single-player mode, both will be null. The two  players' scores are stored in totaLscore and others_score, while our last turn's result is .

import' java.awt.event.*;
class Board extends Canvas
private Letter board[] [] = new L~tter(15) [15);
,private Letter tray[) = new Letter(7);
private Point or Lq = new Point(O,O'):
private Point here = new Point(O,O);
private String ~ame:
private int total~score = 0:
private int turn_score =,0:
private,ine others_scor~ = 0;
private String others_name = null;

addLetter( )
The addLetter( ) method is used to place a letter on the tray. The letter is placed in the first slot that is empty. If the method. can'tfind an empty slot, it returns false.

The private method existingLetterAH ) is used to check a board position to see if it has' a letter in it that is not currently in play. This is used by find words of ) next to make sure 'that at least one letter in a turn is touching an already existing letter.

flndwords( )
findwords( ) is a very large method used to examine ~he state of the board for a legal tum. If the rules for letter placement arc broken, then null is returncd. If no tiles were  in play, the" is returned. If all of the tiles played in this turn are legal, then the list of words they formed is returned as a string containing the space-separated words. The instance variables turn_score and total C score are updated to reflect the value of the words that were just played. First find words( ) counts the tiles at play,  storing them in a separate array called at play. Next, it looks at the first two tiles (if more than one was played) to determine if they arc vertically or horizontally oriented. Then it inspects all of the other tiles at play, to make sure they are along the same line. If any of the tiles is out of that row or column, the method returns null.

Next, it looks at each tile to be sure that at least one of them is touching an existing.
tile on one of its four sides. As special case is made for the beginning of the game: if the center tile is cover.ed and more than one tile is played, it is loop iterates-over every letter in the main word, (i == -i), then comes back agatn tor each letter (i == O notice), which might also create a word orthogonal to the main direction, which is managed via horizontal.

The method then picks each tile and moves left or up from it to find the first tile in
each word. Once at the beginning of the word. it moves right or down from it,
inspecting every letter. It counts the letters in letters_seen. For each letter, it determines the point contribution based on the bonus multiplier beneath it. If the square is played for the first time, the multiplier value is applied; otherwise the tile is counted at face value. This score is accumulated in word_score.

One last error check is done .on the main word only: Since the loop ends whenever
it hits a blank square or the edge of the board.It should cover all of the freshly played tiles, as well as some previously played ones. If it sees fewer tiles, then there must have been a gap in them, which is  position, so it returns null, If that test' s passed, it checks to see if all seven tiles were .played, awarding a 50-point bonus if they were .. After inspecting the main word, Find words( ) inverts the sense of horizontal and looks for orthogonal words on the subsequent passes.

As find words( ) walks across the word, it needs to make sure that it only scores letters that form at least two-letter words. In this case, it adds the word_score to the turn_score and appends this word to the result string. Once all of the letters have been inspected, it totals the score and returns.

commit( ) and commitLetter( ),
The' commit( ) and commitLcttert ) methods commit the letters that were tentatively placed on the board. These letters are removed from the tray and painted in darker color on the board. As each letter is committed, commit( ) notifies the server of the position of each letter by calling move( ) so that the opponent's board can be updated .

update( ) and,.Paint( )
Many private values arc declared here to provide easy access to the dimensions of
the board. This code also declares two offscreen buffers, one to be used as the image of the board and all of the permanently set tiles and another to use as a double buffer for the display. The update( ) method simply calls paint( ) to avoid flicker. The paint( ) method makes a 'quick call to check sizel ) to make sure all of the buffers have been created, then checks to see if we are dragging a letter around by means of pick.If so, then paint( ) makes a copy of the off screen graphics context and clips it to the bounds of the letter it is , it clips the  graphics context to the same rectangle. This will minimize the number of pixels it will have to move for each move of the mouse. To paint, we copy the background image, offscreen, then call paint on each letter in the tray with the setting of NORMAL. We paint the letter we arc dra~ging around in the BRIGHT mode. Finally, we copy the double buffer image,  off screen2, to the screen.

LefterHit( )
LettcrHit( ) returns the letter that is under the point x,y and returns null if no letter
is there.

unplay( ) 
This simple method removes a "letter from play that was placed on the board but was :not yet committed.

moveToTray( )
The moveToTray( ) method is just a simple convenience to compute the screen position of a letter in a given tray slot.

dropOnTray( )
The dropOnTray( ) method is used whenever we drop a letter over the tray area or off the board anywhere. This allows us to shuffle the contents of the tray as well as simply return tiles from the board.

getLetter( )
getLetter() is a simple read-only wrapper on the board array.

moveLetter{ )
The move Letter( ) method handles the cases where we want to move tiles to board
positions or set them on the tray. U the x,y petition is out of range for the board, then the tray is used. When a letter is moved to the board, it must be a blank slot, otherwise ,the letter is sent back to the value stored in orig.

checksize( ) .
This method has a misleading name. check size ) does a lot more than verify the size of the applet, but it is convenient to do this kind of initialization once, when we confirm the size of the applet:This method contains the drawing code for the main board pattern. It paints all of the squares, including the colors and the bonus score text.

center{ )
center( ) is a convenience routine thaf checkslzet ) uses to center the "Double Letter
Score" text.

The paintScore( ) method paints the two players' scores or just the one score in single-player mode.

selectLetter( )
The selcctl.ettert ) method checks the mouse position to see if the cursor is over a letter. If so, it stores that in pick and computes how far the mouse was from the upper-left comer of the letter, which is stored in dx,dy. It also.remembers the original position of this letter in orig.

In dropLetter( ), the user has dropped the letter if he or she was carrying one. It determines which square on the board the letter was over when it was dropped. It then , calls moveLetter( ) to attempt to move the letter to that square.

dragLetter{ )
The dragLcttcr( ) method is handled differently than the other mouse-related events. This is mainly due to performance considerations. The goal is to have as smooth an interaction with the user as possible: dragLetter( ) goes to some length to compute the bounding box of where the tile was before.this drag plus where it is now. It then . directly calls paint(getGraphics( This is nonstandard Java applet programming, but it perfo. -ns much more reliably.

In the following code fragment, notice that My Mouse Chaptetr L\11 inner class that extends Mouse.Adapter. It overrides the mouse  ressedt) and mousekclcasedt )

mouseReleased( )
The mouselteleasedt ) method invokes the dropLetter() method to do the necessary
processing. The x and y coordinates of the current mouse position are obtained from
the argument supplied to the mouseRc1eased( ) method.

mouseDragged( )
'In the following code fragment. notice that MyMouseMotionAdapter is an inner class that extends Mouselvlotioria.daptcr, It overrides the mouscDragged( ) method.
The mouseDraggcd() method invokes the dragl.ettcrf ) method to do the necessary
processing. The x and y coordinates of the currentmouse position arc obtained from
the argument supplied to the mouseDragged() method.
TIle Bag class is very clean compared with Board. It is a simple abstraction for the bag of letters. When you create a Bag, you pass in a random seed, which allows you to create two bags that are random but the same by passing in the ~aIne random seed. The random number generator is stored in rand. There are two somewhat strange arrays of integers, named letteccounts and leller_points. Both arrays arc Fslots long. They.represent the blank tile in slot 0, and A through Z in 1 through 26. The letter ccounts array says how many of each letter arc in a full bag. For example, letter_counts is 9, which says there are nine A tiles in the bag. Similarly, the letter_points array maps, each letter to its point value. The A tiles are worth only 1 point, and the lone Z is worth 10. There arc 100 letters stored in the array called letters. The number of letters actually " left in the bag during game play is stored in .

Bag( )
The Bag constructor takes the seed and makes a Random object out of it. It then scans through the Ictter..counts array, making the right number of new Letter objects, being careful to replace the blank tile with-an asterisk. It then calls putDackO for each letter, to put them in the bag.

The next method is slightly clever and a little inefficient, but in a noncritical way. takeOut() picks a random number between 0 and then extracts the letter at that offset from the letters away It closes the hole over that slot in letters using System.arraycopy(). Then it decrements n and returns the letter.

Letter java
The Letter class is fairly dean in that it doesn't know anything about the game or the
board.It nearly encapsulates the position and visual rendering of a single letter. It uses several static-variables to hold information about fonts and sizes. This is done so that the applet doesn't end up with 100 fonts in memory at once. This has the side effect sultana browser page containment two instances of the Scrabble applet if the)' each have different sues. Rile second one to initialize will overwrite the values in these static variables.

The w and h variables hold the constant width and height of every letter. The-font
and smfont variables arc the AWT font objects for the big letter and the smaller point value. The ints yOand ysO store the offset of the baseline of the letter and the points, respectively. A few constants are provided to be passed back into paintt ) to describe which c0191'stateto paint in: NORMAL, DIM, and BRIGHT mode.

colors] 1, mix( ), gain{ ), and clamp( )
The colors array is initialized statically with nine color objects-three sets of three
colors. The mix ) method is used to take a set of RGIJ values like 250, 220, 100 and turn them into three colors, which can be used to provide 3-D-like highlights and Iow lights. The mix( ) method calls on gain( ) to boost or decimate the brightness of a given color and calls on clamp ) to-make sure it remains in the legal range.

Share This