Assignment #5 Chess Due: 1:15pm On Friday, May 17th PDF

1m ago
2 Views
0 Downloads
807.74 KB
25 Pages
Transcription

Steve CooperCS 106AHandout #36May 10, 2013Assignment #5 – ChessDue: 1:15pm on Friday, May 17thYour Early Assignment Help (YEAH) hours: Monday 05/13 at 7PM in 200-303Handout by Thomas FuFor this assignment, your job is going to be to create the game of Chess. This game, whichoriginated in its current form in the late 15th century, is currently one of the world’s most popularand ubiquitous games. By the time you are done with this assignment, you will have your veryown version of this classic game, quite similar to the kind you might find already installed onyour computer1. Much like the earlier assignments, though, you'll likely want to decompose thisone into a series of smaller problems, and get started early. We’ll also outline an approach in thishandout that should help you get through the steps.Figure 1. Image of the Chess game you’re going to program.In this assignment, we first describe the starter classes. We then propose a series of steps youcan take to create the game. After suggesting some possible extensions, we include several usefulmethods you'll likely wish to use, as part of Appendix A. And, if you are not familiar with thegame of chess, Appendix B includes lots of details.1If you’re on a Mac, try looking for Chess in the Applications folder.

-2-The Java FilesTo get started, let’s take a look at the files that you’ll be getting for this assignment. When youopen up the Chess assignment in Eclipse you’ll see a list of Java files that looks something likethis:Figure 2. Listing of the files contained in the Chess Assignment.There are four groups of interesting classes, detailed below.1) The Chess PiecesThe different types of chess pieces are really what make chess such an interesting game (a boardof entirely pawns would make for a really boring game). There are six distinct types of pieces:Pawn, Knight, Bishop, Rook, Queen, and King. Each piece has its own unique rules governinghow it can move and capture other pieces. Details about how the pieces move are found inAppendix B. The bulk of what you’ll be writing for this assignment is the code that willdetermine whether a given piece can move to a specified spot on the board. Basically, you’ll beenforcing the rules of chess.Let’s take a look at the structure behind how we’re going to be representing the chess pieces. InJava-speak, we have six different classes (Pawn, Knight, Bishop, Rook, King and Queen) thatare all subclasses of a ChessPiece superclass. This is analogous to the ACM Graphics Library,where we have GRects, GOvals, GPolygons, GLabels, etc. all of which are subclasses of theGObject superclass. We have exactly the same thing here. In picture form the structure of ourpiece classes looks like this:ChessPiecePawnKnightBishopCastleKingFigure 3. Diagram of the ChessPiece class hierarchy.Queen

-3We’ve defined a general ChessPiece class that’s responsible for managing the things that arecommon across all different types of chess pieces. For instance, every ChessPiece, regardless ofits type, needs to know where it is and what color it is. Then, to get the individual functionalityof each individual type of chess piece, we expanded upon this abstract ChessPiece class andmade specific types of ChessPieces. If this is confusing, you can keep it straight by justremembering that every Knight is a ChessPiece, but not every ChessPiece is a Knight.So why did we do this? Since we know that Knights, Pawns, Bishops, etc. are going to have a lotof overlapping functionality, rather than implementing the same methods a bunch of times, wejust have to do it once in ChessPiece. Then anything that inherits from ChessPiece gets it for free.This is one of the big benefits of object-oriented programming; it just makes some things reallyconvenient.But wait, I get that all the classes like Pawn and Rook extend this ChessPiece superclass, butwhere is ChessPiece.java? Why can’t I see it in my Chess assignment? The short answer is, it’sjust like a GraphicsProgram. Remember how your Breakout program extended GraphicsProgrambut you couldn’t actually see GraphicsProgram.java? Well it’s the same deal here. Just likeGraphicsProgram.java lives in acm.jar, ChessPiece.java lives in ChessLib.jar and its interface isdescribed starting in Appendix A of the handout.2) The ChessBoardWe begin a discussion of the other classes and java files you’ll be dealing with in this assignment.Probably the most straightforward of these is the ChessBoard class. This is primary because thisclass does basically what you would expect – it allows you to store a bunch of ChessPieces atdifferent locations (that is what a real life chessboard does after all). Now, to start diving into thedetails of this class, let’s begin by looking at the code in ChessBoard.java (comments omitted inthe interest of saving space):public class ChessBoard{public static final int BOARD SIZE 8;public ChessBoard(){}public ChessPiece pieceAt(int row, int col){}public void addPiece(ChessPiece piece){}public void removePiece(int row, int col){}}

-4We’ve just got three methods and a constructor. Let’s talk about this constructor in more detail.The constructor will need to initialize whatever data structure you’re going to use to store theChessPieces and their locations. Strictly speaking, you’re free to choose whatever data structureyou like, provided the methods pieceAt, addPiece, and removePiece all work like they’resupposed to, but seeing as how we just learned about Arrays and ArrayLists (specifically twodimensional Arrays and ArrayLists), it seems like using one of these might be a good way toproceed. Let’s just say, for example, that you wanted to use a two-dimensional Array ofChessPieces to back the ChessBoard class. Thus the job of the constructor would be to initializethis Array to all nulls, as initially, there aren't any pieces on the board.Now let’s talk really briefly about the methods pieceAt, addPiece, and removePiece. Thesemethods should behave more or less how you’d expect, but for the sake of clarity we’ll go overtheir functionality. The first one, pieceAt, should, return the ChessPiece located at the specifiedrow and column, or null (if no piece exists at the current location). Next, addPiece should addthe given ChessPiece to your ChessBoard. Be advised that this method only takes one argument(a single ChessPiece) so to figure out where this piece is to go, you’ll have to take advantage ofthe fact that each ChessPiece knows its location (you will find the methods getRow() andgetCol() defined in the ChessPiece class to be helpful). If the user attempts to add a piece toa location where one already exists, addPiece should overwrite the old piece with the newone. Finally, the method removePiece should remove whatever ChessPiece is at the specifiedrow and column from your ChessBoard data structure, setting the ChessPiece at that row andcolumn to be null.In addition to these three required methods, you’re free to add any other methods to theChessBoard class in order to make your job easier. For instance, it might not be a bad idea to adda method that initializes the board by adding ChessPieces to produce the starting configurationfor a game of chess. One important note on these required methods though – you have toimplement them exactly as they are given to you. That means DO NOT change the headers forthese methods (i.e. addPiece must have return type void and must accept a ChessPiece as its oneargument).3) The ChessDisplayThis entire section is about a class that has already been written for you. In the Chess class, wehave created an object of the ChessDisplay type. You will invoke methods on this object todisplay the board as well as to determine what square was clicked by the user when the game isplayed (which is described below). There are a few caveats you must consider.Caveat One: Just because you don’t have to draw anything doesn’t mean you don’t have to dealwith mouse input. We’ll take care of the drawing; you take care of figuring out what to do whenthe user clicks the mouse (more on this below). However, we do provide a helper method int[]getLocation(int x, int y), which takes in a x and y coordinate and returns the correspondingrow and column on the ChessBoard as a array of length 2 – the first element is the row, thesecond the column.Caveat Two: Even though we’ll do all the drawing for you, you still need to tell us what to draw.Or rather, you need to tell ChessDisplay what to draw. This isn’t as hard as it sounds, though,

-5and you can do this through the conveniently named method void draw(ChessBoard board)defined in the ChessDisplay class. We’ll discuss more about when to call this method in the nextsection, but for now all you need to know is this. You pass in a ChessBoard (which here wecalled board) all loaded up with ChessPieces into the draw method, and ChessDisplay will thendraw that board to the screen. It will then stay on the screen until you call draw again. Anytimeyou want to update the screen, you just call draw.Caveat Three: To make the game look nicer, when the user selects a piece to move (again, moreon this in the next section), your job is to highlight the square that piece is sitting on to make itstand out. We’ve written three methods for you, void selectSquare(double row, double col,Color c), void unselectSquare(int row, int col), and void unselectAll(). The methodselectSquare highlights the square at the given row and column with the given color;unselectSquare changes the square at the given row and column to its original color; andunselectAll changes all squares drawn to the screen to their original colors.One more note about the ChessDisplay class. When you use the methods selectSquare,unselectSquare, unselectAll each of these methods addresses the chessboard using the sameconvention as a GraphicsProgram. That is, the square corresponding to row-column coordinatesof (0,0) is the top left square on the chessboard. (See Figure 4 below.) This is consistent with theidea of having the origin in the top left of the screen. Additionally, this is the default conventionfor how the chessboard is labeled when it is displayed to the screen, as shown in the Figurebelow. Again, all methods in ChessDisplay use the convention that (0,0) is the top leftsquare of the chessboard. Basically this means if you say:display.selectSquare(0, 0, Color.YELLOW);display.draw(board);then the square in the upper left-hand corner will be highlighted.Figure 4.Image of the default numbering scheme for the chessboard as it is displayed to the screen. Observe how the coordinate(0,0) corresponds to the upper left-hand corner of the chessboard.

-64) The Chess Class***If you are not familiar with the game of Chess, see Appendix B for a gamedescription****So far we’ve discussed the ChessPiece subclasses (these represent the individual chess pieces),the ChessBoard class (which represents the board that holds these pieces), and the ChessDisplayclass (which draws everything to the screen). Now we turn to the Chess class, which actually willbe managing the game. This file is responsible for reading mouse input from the screen andhandling the gameplay accordingly. This means that nearly all of the action in Chess will be theresult of MouseEvents, which work just like they did in earlier GraphicsPrograms.The games of chess works by alternating turns between a White player and a Black player, withthe White player always playing first. You will need to mirror this functionality in your program.Unlike in games like Breakout, all the action in Chess happens in response to a user action, sothe bulk of your code will be in mousePressed (see Part III under our “Suggested Approach”section for more details about mousePressed, including pseudocode). You will therefore need tokeep track of the turn across mousePressed calls.During a single turn the user will select one of their pieces by clicking on it, which will highlightit. We have provided a helper method int[] getLocation(int x, int y) in the ChessDisplayclass which translates x and y coordinates to a row and column on the ChessBoard (seeAppendix A for more details about this method). The user will then click a second time on thesquare that he or she would like to move the piece to. If the piece is unable to move to the square,or the user re-clicks the same square, the piece is un-highlighted and nothing happens – itcontinues to be that player’s turn, and the player can try the two-click process again, with thatpiece or another one.If they are able to move the piece to that square, the piece should be moved, capturing theopponent’s piece if appropriate. You should also print the line “color pieceType moved from(oldRow, oldCol) to (newRow, newCol)” with the italicized words replaced with their appropriatevalues. An example would be the following line: White queen moved from (0,1) to (2,3). Feelfree to use real Chess notation for this line as well!You will also need to print a message when one of the players is in check, which you candetermine by calling our helper method boolean isInCheck(ChessBoard board, int Player).You should print something like “Black is in check.”The games ends when one of players is in checkmate or stalemate, which you can figure out bycalling our helper methods boolean isInCheckMate(ChessBoard board, int Player) andboolean isInStalemate(ChessBoard board, int Player) on the Chess class. When this happens,print a message like “Black is in checkmate. Game over.” or “Stalemate. Game over.” and stopresponding to mouseclicks.See Part III under our “Suggested Approach” section for a more in-depth discussion of gameplaymechanics.

-7-The Pieces ReduxHaving discussed the ChessBoard class responsible for keeping track of the pieces and theirlocations, and the Chess class, responsible for the gameplay, it is now time to turn our attentionback to the chess pieces themselves. With an understanding of Chess and ChessBoard under ourbelts, we can now move into a more thorough understanding of the ChessPiece subclasses. Inparticular, we begin our discussion with some of the fields that each of these classes inheritsfrom ChessPiece.It is important to note the stuff that you get for free from the ChessPiece class. Because yourKnight, Rook, Queen, etc. classes all subclass from ChessPiece, you get access to the instancevariables that are defined in ChessPiece. In particular, you have access to the variables shown inthe code block below:public static final int BLACK 0;public static final int WHITE 1;protected int row, col;protected int color;What this means (don’t worry about what protected means, you can treat it like private) is thatyou can treat this code like it’s in each of your chess piece files (Pawn.java, King.java, etc.). Thismeans that in any of the ChessPiece subclasses (i.e. Pawn, Knight, Bishop, Rook, Queen, andKing) you can use row, col, color, BLACK, or WHITE as if it had been defined directly in the classyou are working in.For instance

int[] getLocation(int x, int y), which takes in a x and y coordinate and returns the corresponding row and column on the ChessBoard as a array of length 2 – the first element is the row, the second the column. Caveat Two: Even though we’ll do all the drawing for you, you still need to tell us what to draw.