School Java Project Chess (2)

Deploying 32 initial pieces

拇指 muzhi.com
Analytics Vidhya
Published in
8 min readJan 9, 2020

--

Last time we printed out the empty chess board. Today we’ll populate the board with initial 32 pieces. The board will look like the following when we finish.

Open Chess.java and create an enum Type to represent chess piece type at the end of the file.

Edit/Compile/Run Chess.java.

Now we can design a new class Piece to represent a piece. Add the following code at the end of file Chess.java.

There are two vim commands we can use to speed up editing a little bit. “L” moves cursor to the bottom. “o” enters INSERT mode and inserts a new line below cursor. BTW, “H” moves cursor to the top and “M” to the middle. “O” enters INSERT mode and inserts a new line above cursor.

Edit/Compile/Run Chess.java to make sure everything is fine.

In order to use data type Set as the container of all the pieces on board, we need to add two lines of code at the top of Chess.java.

We’ll create an instance variable with type Set<Piece> and insert a white queen into it in the constructor Board().

Make sure it still works by compiling and running the updated Chess.java.

To print out pieces on board we can create the following helper method Piece pieceAt(int c, int r) to return an Piece object at a specific location.

Now we need to modify toString() method of class Board to show pieces.

Edit/Compile/Run Chess.java to see the single piece Queen on board.

Time to add the rest 31 pieces in the constructor of class Board.

Edit/Compile/Run Chess.java to see all 32 pieces.

Here is the complete code so far.

And we are done.

--

--