SlideShare a Scribd company logo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("Checkers");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("",JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new CheckersData();
doNewGame();
}
/**
* Respond to user's click on one of the two buttons.
*/
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == newGameButton)
doNewGame();
else if (src == resignButton)
doResign();
}
/**
* Start a new game
*/
void doNewGame() {
if (gameInProgress == true) {
// This should not be possible, but it doesn't hurt to check.
message.setText("Finish the current game first!");
return;
}
board.setUpGame(); // Set up the pieces.
currentPlayer = CheckersData.RED; // RED moves first.
legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves.
selectedRow = -1; // RED has not yet selected a piece to move.
message.setText("Red: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
repaint();
}
/**
* Current player resigns. Game ends. Opponent wins.
*/
void doResign() {
if (gameInProgress == false) { // Should be impossible.
message.setText("There is no game in progress!");
return;
}
if (currentPlayer == CheckersData.RED)
gameOver("RED resigns. BLACK wins.");
else
gameOver("BLACK resigns. RED wins.");
}
void gameOver(String str) {
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
}
void doClickSquare(int row, int col) {
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) {
selectedRow = row;
selectedCol = col;
if (currentPlayer == CheckersData.RED)
message.setText("RED: Make your move.");
else
message.setText("BLACK: Make your move.");
repaint();
return;
}
/* If no piece has been selected to be moved, the user must first
select a piece. Show an error message and return. */
if (selectedRow < 0) {
message.setText("Click the piece you want to move.");
return;
}
/* If the user clicked on a square where the selected piece can be
legally moved, then make the move and return. */
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol
&& legalMoves[i].toRow == row && legalMoves[i].toCol == col) {
doMakeMove(legalMoves[i]);
return;
}
message.setText("Click the square you want to move to.");
} // end doClickSquare()
void doMakeMove(CheckersMove move) {
board.makeMove(move);
if (move.isJump()) {
legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol);
if (legalMoves != null) {
if (currentPlayer == CheckersData.RED)
message.setText("RED: You must continue jumping.");
else
message.setText("BLACK: You must continue jumping.");
selectedRow = move.toRow; // Since only one piece can be moved, select it.
selectedCol = move.toCol;
repaint();
return;
}
}
if (currentPlayer == CheckersData.RED) {
currentPlayer = CheckersData.BLACK;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("BLACK has no moves. RED wins.");
else if (legalMoves[0].isJump())
message.setText("BLACK: Make your move. You must jump.");
else
message.setText("BLACK: Make your move.");
}
else {
currentPlayer = CheckersData.RED;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("RED has no moves. BLACK wins.");
else if (legalMoves[0].isJump())
message.setText("RED: Make your move. You must jump.");
else
message.setText("RED: Make your move.");
}
selectedRow = -1;
if (legalMoves != null) {
boolean sameStartSquare = true;
for (int i = 1; i < legalMoves.length; i++)
if (legalMoves[i].fromRow != legalMoves[0].fromRow
|| legalMoves[i].fromCol != legalMoves[0].fromCol) {
sameStartSquare = false;
break;
}
if (sameStartSquare) {
selectedRow = legalMoves[0].fromRow;
selectedCol = legalMoves[0].fromCol;
}
}
/* Make sure the board is redrawn in its new state. */
repaint();
} // end doMakeMove();
public void paintComponent(Graphics g) {
/* Draw a two-pixel black border around the edges of the canvas. */
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
/* Draw the squares of the checkerboard and the checkers. */
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 )
g.setColor(Color.LIGHT_GRAY);
else
g.setColor(Color.GRAY);
g.fillRect(2 + col*20, 2 + row*20, 20, 20);
switch (board.pieceAt(row,col)) {
case CheckersData.RED:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.BLACK:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.RED_KING:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
case CheckersData.BLACK_KING:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
}
}
}
g.setColor(Color.cyan);
for (int i = 0; i < legalMoves.length; i++) {
g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17);
}
/* If a piece is selected for moving (i.e. if selectedRow >= 0), then
draw a 2-pixel white border around that piece and draw green borders
around each square that that piece can be moved to. */
if (selectedRow >= 0) {
g.setColor(Color.white);
g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19);
g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17);
g.setColor(Color.green);
for (int i = 0; i < legalMoves.length; i++) {
if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow ==
selectedRow) {
g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17);
}
}
}
}
} // end paintComponent()
public void mousePressed(MouseEvent evt) {
if (gameInProgress == false)
message.setText("Click "New Game" to start a new game.");
else {
int col = (evt.getX() - 2) / 20;
int row = (evt.getY() - 2) / 20;
if (col >= 0 && col < 8 && row >= 0 && row < 8)
doClickSquare(row,col);
}
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end class Board
private static class CheckersData {
/* The following constants represent the possible contents of a square
on the board. The constants RED and BLACK also represent players
in the game. */
static final int
EMPTY = 0,
RED = 1,
RED_KING = 2,
BLACK = 3,
BLACK_KING = 4;
int[][] board; // board[r][c] is the contents of row r, column c.
/**
* Constructor. Create the board and set it up for a new game.
*/
CheckersData() {
board = new int[8][8];
setUpGame();
}
void setUpGame() {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 ) {
if (row < 3)
board[row][col] = BLACK;
else if (row > 4)
board[row][col] = RED;
else
board[row][col] = EMPTY;
}
else {
board[row][col] = EMPTY;
}
}
}
} // end setUpGame()
int pieceAt(int row, int col) {
return board[row][col];
}
void makeMove(CheckersMove move) {
makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol);
}
void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
board[toRow][toCol] = board[fromRow][fromCol];
board[fromRow][fromCol] = EMPTY;
if (fromRow - toRow == 2 || fromRow - toRow == -2) {
// The move is a jump. Remove the jumped piece from the board.
int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece.
int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece.
board[jumpRow][jumpCol] = EMPTY;
}
if (toRow == 0 && board[toRow][toCol] == RED)
board[toRow][toCol] = RED_KING;
if (toRow == 7 && board[toRow][toCol] == BLACK)
board[toRow][toCol] = BLACK_KING;
}
CheckersMove[] getLegalMoves(int player) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // Moves will be stored in this list.
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
}
}
if (moves.size() == 0) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canMove(player,row,col,row+1,col+1))
moves.add(new CheckersMove(row,col,row+1,col+1));
if (canMove(player,row,col,row-1,col+1))
moves.add(new CheckersMove(row,col,row-1,col+1));
if (canMove(player,row,col,row+1,col-1))
moves.add(new CheckersMove(row,col,row+1,col-1));
if (canMove(player,row,col,row-1,col-1))
moves.add(new CheckersMove(row,col,row-1,col-1));
}
}
}
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMoves
CheckersMove[] getLegalJumpsFrom(int player, int row, int col) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list.
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMovesFrom()
private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) {
if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8)
return false; // (r3,c3) is off the board.
if (board[r3][c3] != EMPTY)
return false; // (r3,c3) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r3 > r1)
return false; // Regular red piece can only move up.
if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING)
return false; // There is no black piece to jump.
return true; // The jump is legal.
}
else {
if (board[r1][c1] == BLACK && r3 < r1)
return false; // Regular black piece can only move downn.
if (board[r2][c2] != RED && board[r2][c2] != RED_KING)
return false; // There is no red piece to jump.
return true; // The jump is legal.
}
} // end canJump()
private boolean canMove(int player, int r1, int c1, int r2, int c2) {
if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8)
return false; // (r2,c2) is off the board.
if (board[r2][c2] != EMPTY)
return false; // (r2,c2) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r2 > r1)
return false; // Regular red piece can only move down.
return true; // The move is legal.
}
else {
if (board[r1][c1] == BLACK && r2 < r1)
return false; // Regular black piece can only move up.
return true; // The move is legal.
}
} // end canMove()
} // end class CheckersData
} // end class Checkers
Solution
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame("Checkers");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("",JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new CheckersData();
doNewGame();
}
/**
* Respond to user's click on one of the two buttons.
*/
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == newGameButton)
doNewGame();
else if (src == resignButton)
doResign();
}
/**
* Start a new game
*/
void doNewGame() {
if (gameInProgress == true) {
// This should not be possible, but it doesn't hurt to check.
message.setText("Finish the current game first!");
return;
}
board.setUpGame(); // Set up the pieces.
currentPlayer = CheckersData.RED; // RED moves first.
legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves.
selectedRow = -1; // RED has not yet selected a piece to move.
message.setText("Red: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
repaint();
}
/**
* Current player resigns. Game ends. Opponent wins.
*/
void doResign() {
if (gameInProgress == false) { // Should be impossible.
message.setText("There is no game in progress!");
return;
}
if (currentPlayer == CheckersData.RED)
gameOver("RED resigns. BLACK wins.");
else
gameOver("BLACK resigns. RED wins.");
}
void gameOver(String str) {
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
}
void doClickSquare(int row, int col) {
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) {
selectedRow = row;
selectedCol = col;
if (currentPlayer == CheckersData.RED)
message.setText("RED: Make your move.");
else
message.setText("BLACK: Make your move.");
repaint();
return;
}
/* If no piece has been selected to be moved, the user must first
select a piece. Show an error message and return. */
if (selectedRow < 0) {
message.setText("Click the piece you want to move.");
return;
}
/* If the user clicked on a square where the selected piece can be
legally moved, then make the move and return. */
for (int i = 0; i < legalMoves.length; i++)
if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol
&& legalMoves[i].toRow == row && legalMoves[i].toCol == col) {
doMakeMove(legalMoves[i]);
return;
}
message.setText("Click the square you want to move to.");
} // end doClickSquare()
void doMakeMove(CheckersMove move) {
board.makeMove(move);
if (move.isJump()) {
legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol);
if (legalMoves != null) {
if (currentPlayer == CheckersData.RED)
message.setText("RED: You must continue jumping.");
else
message.setText("BLACK: You must continue jumping.");
selectedRow = move.toRow; // Since only one piece can be moved, select it.
selectedCol = move.toCol;
repaint();
return;
}
}
if (currentPlayer == CheckersData.RED) {
currentPlayer = CheckersData.BLACK;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("BLACK has no moves. RED wins.");
else if (legalMoves[0].isJump())
message.setText("BLACK: Make your move. You must jump.");
else
message.setText("BLACK: Make your move.");
}
else {
currentPlayer = CheckersData.RED;
legalMoves = board.getLegalMoves(currentPlayer);
if (legalMoves == null)
gameOver("RED has no moves. BLACK wins.");
else if (legalMoves[0].isJump())
message.setText("RED: Make your move. You must jump.");
else
message.setText("RED: Make your move.");
}
selectedRow = -1;
if (legalMoves != null) {
boolean sameStartSquare = true;
for (int i = 1; i < legalMoves.length; i++)
if (legalMoves[i].fromRow != legalMoves[0].fromRow
|| legalMoves[i].fromCol != legalMoves[0].fromCol) {
sameStartSquare = false;
break;
}
if (sameStartSquare) {
selectedRow = legalMoves[0].fromRow;
selectedCol = legalMoves[0].fromCol;
}
}
/* Make sure the board is redrawn in its new state. */
repaint();
} // end doMakeMove();
public void paintComponent(Graphics g) {
/* Draw a two-pixel black border around the edges of the canvas. */
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
/* Draw the squares of the checkerboard and the checkers. */
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 )
g.setColor(Color.LIGHT_GRAY);
else
g.setColor(Color.GRAY);
g.fillRect(2 + col*20, 2 + row*20, 20, 20);
switch (board.pieceAt(row,col)) {
case CheckersData.RED:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.BLACK:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
break;
case CheckersData.RED_KING:
g.setColor(Color.RED);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
case CheckersData.BLACK_KING:
g.setColor(Color.BLACK);
g.fillOval(4 + col*20, 4 + row*20, 15, 15);
g.setColor(Color.WHITE);
g.drawString("K", 7 + col*20, 16 + row*20);
break;
}
}
}
g.setColor(Color.cyan);
for (int i = 0; i < legalMoves.length; i++) {
g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17);
}
/* If a piece is selected for moving (i.e. if selectedRow >= 0), then
draw a 2-pixel white border around that piece and draw green borders
around each square that that piece can be moved to. */
if (selectedRow >= 0) {
g.setColor(Color.white);
g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19);
g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17);
g.setColor(Color.green);
for (int i = 0; i < legalMoves.length; i++) {
if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow ==
selectedRow) {
g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19);
g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17);
}
}
}
}
} // end paintComponent()
public void mousePressed(MouseEvent evt) {
if (gameInProgress == false)
message.setText("Click "New Game" to start a new game.");
else {
int col = (evt.getX() - 2) / 20;
int row = (evt.getY() - 2) / 20;
if (col >= 0 && col < 8 && row >= 0 && row < 8)
doClickSquare(row,col);
}
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end class Board
private static class CheckersData {
/* The following constants represent the possible contents of a square
on the board. The constants RED and BLACK also represent players
in the game. */
static final int
EMPTY = 0,
RED = 1,
RED_KING = 2,
BLACK = 3,
BLACK_KING = 4;
int[][] board; // board[r][c] is the contents of row r, column c.
/**
* Constructor. Create the board and set it up for a new game.
*/
CheckersData() {
board = new int[8][8];
setUpGame();
}
void setUpGame() {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if ( row % 2 == col % 2 ) {
if (row < 3)
board[row][col] = BLACK;
else if (row > 4)
board[row][col] = RED;
else
board[row][col] = EMPTY;
}
else {
board[row][col] = EMPTY;
}
}
}
} // end setUpGame()
int pieceAt(int row, int col) {
return board[row][col];
}
void makeMove(CheckersMove move) {
makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol);
}
void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
board[toRow][toCol] = board[fromRow][fromCol];
board[fromRow][fromCol] = EMPTY;
if (fromRow - toRow == 2 || fromRow - toRow == -2) {
// The move is a jump. Remove the jumped piece from the board.
int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece.
int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece.
board[jumpRow][jumpCol] = EMPTY;
}
if (toRow == 0 && board[toRow][toCol] == RED)
board[toRow][toCol] = RED_KING;
if (toRow == 7 && board[toRow][toCol] == BLACK)
board[toRow][toCol] = BLACK_KING;
}
CheckersMove[] getLegalMoves(int player) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // Moves will be stored in this list.
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
}
}
if (moves.size() == 0) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canMove(player,row,col,row+1,col+1))
moves.add(new CheckersMove(row,col,row+1,col+1));
if (canMove(player,row,col,row-1,col+1))
moves.add(new CheckersMove(row,col,row-1,col+1));
if (canMove(player,row,col,row+1,col-1))
moves.add(new CheckersMove(row,col,row+1,col-1));
if (canMove(player,row,col,row-1,col-1))
moves.add(new CheckersMove(row,col,row-1,col-1));
}
}
}
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMoves
CheckersMove[] getLegalJumpsFrom(int player, int row, int col) {
if (player != RED && player != BLACK)
return null;
int playerKing; // The constant representing a King belonging to player.
if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;
ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list.
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = moves.get(i);
return moveArray;
}
} // end getLegalMovesFrom()
private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) {
if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8)
return false; // (r3,c3) is off the board.
if (board[r3][c3] != EMPTY)
return false; // (r3,c3) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r3 > r1)
return false; // Regular red piece can only move up.
if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING)
return false; // There is no black piece to jump.
return true; // The jump is legal.
}
else {
if (board[r1][c1] == BLACK && r3 < r1)
return false; // Regular black piece can only move downn.
if (board[r2][c2] != RED && board[r2][c2] != RED_KING)
return false; // There is no red piece to jump.
return true; // The jump is legal.
}
} // end canJump()
private boolean canMove(int player, int r1, int c1, int r2, int c2) {
if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8)
return false; // (r2,c2) is off the board.
if (board[r2][c2] != EMPTY)
return false; // (r2,c2) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r2 > r1)
return false; // Regular red piece can only move down.
return true; // The move is legal.
}
else {
if (board[r1][c1] == BLACK && r2 < r1)
return false; // Regular black piece can only move up.
return true; // The move is legal.
}
} // end canMove()
} // end class CheckersData
} // end class Checkers

More Related Content

Similar to import java.awt.;import java.awt.event.;import javax.swing.;.pdf

Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
udit652068
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
archanaemporium
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
anithareadymade
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
petercoiffeur18
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
Sam Cartwright
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docx
Komlin1
 
GameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdfGameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdf
aravlitraders2012
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdf
atulkapoor33
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
Christoffer Noring
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
fonecomp
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
kavithaarp
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
infomalad
 
Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision Detection
Jenchoke Tachagomain
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2ME
Jenchoke Tachagomain
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mccormicknadine86
 

Similar to import java.awt.;import java.awt.event.;import javax.swing.;.pdf (18)

Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 
i need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdfi need a taking turn method for a player vs computer battleship game.pdf
i need a taking turn method for a player vs computer battleship game.pdf
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 TilePUzzle class Anderson, Franceschi public class TilePu.docx TilePUzzle class Anderson, Franceschi public class TilePu.docx
TilePUzzle class Anderson, Franceschi public class TilePu.docx
 
GameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdfGameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdf
 
Java ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdfJava ProgrammingImplement an auction application with the followin.pdf
Java ProgrammingImplement an auction application with the followin.pdf
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
tetris
tetristetris
tetris
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdfTic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
 
Mobile Game and Application with J2ME - Collision Detection
Mobile Gameand Application withJ2ME  - Collision DetectionMobile Gameand Application withJ2ME  - Collision Detection
Mobile Game and Application with J2ME - Collision Detection
 
Mobile Game and Application with J2ME
Mobile Gameand Application with J2MEMobile Gameand Application with J2ME
Mobile Game and Application with J2ME
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 

More from aoneonlinestore1

1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
aoneonlinestore1
 
1. B) - Two independent properties serve to specify the state.2. B.pdf
1. B) - Two independent properties serve to specify the state.2. B.pdf1. B) - Two independent properties serve to specify the state.2. B.pdf
1. B) - Two independent properties serve to specify the state.2. B.pdf
aoneonlinestore1
 
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
aoneonlinestore1
 
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
 I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
aoneonlinestore1
 
C program that prompts user to enter two floating point t.pdf
  C program that prompts user to enter two floating point t.pdf  C program that prompts user to enter two floating point t.pdf
C program that prompts user to enter two floating point t.pdf
aoneonlinestore1
 
The carbonyl functional group in glucose is an al.pdf
                     The carbonyl functional group in glucose is an al.pdf                     The carbonyl functional group in glucose is an al.pdf
The carbonyl functional group in glucose is an al.pdf
aoneonlinestore1
 
Well to find the pH at the equivalance point. Acc.pdf
                     Well to find the pH at the equivalance point. Acc.pdf                     Well to find the pH at the equivalance point. Acc.pdf
Well to find the pH at the equivalance point. Acc.pdf
aoneonlinestore1
 
The weakest base in the reaction is A the enolat.pdf
                     The weakest base in the reaction is A the enolat.pdf                     The weakest base in the reaction is A the enolat.pdf
The weakest base in the reaction is A the enolat.pdf
aoneonlinestore1
 
so take an aliquot of the upper layer and add a f.pdf
                     so take an aliquot of the upper layer and add a f.pdf                     so take an aliquot of the upper layer and add a f.pdf
so take an aliquot of the upper layer and add a f.pdf
aoneonlinestore1
 
moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
                     moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf                     moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
aoneonlinestore1
 
Latency is a measure of time delay experienced in.pdf
                     Latency is a measure of time delay experienced in.pdf                     Latency is a measure of time delay experienced in.pdf
Latency is a measure of time delay experienced in.pdf
aoneonlinestore1
 
Entropy is the measure of disorder. Therefore, th.pdf
                     Entropy is the measure of disorder. Therefore, th.pdf                     Entropy is the measure of disorder. Therefore, th.pdf
Entropy is the measure of disorder. Therefore, th.pdf
aoneonlinestore1
 
dydx = 1x dy = dxx y = ln x + c .pdf
                     dydx = 1x dy = dxx y = ln x + c               .pdf                     dydx = 1x dy = dxx y = ln x + c               .pdf
dydx = 1x dy = dxx y = ln x + c .pdf
aoneonlinestore1
 
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdf
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdfØ Napoleonic era brought some relief to the faltering ottoman empire.pdf
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdf
aoneonlinestore1
 
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdfYES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
aoneonlinestore1
 
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdfTWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
aoneonlinestore1
 
upSolutionup.pdf
upSolutionup.pdfupSolutionup.pdf
upSolutionup.pdf
aoneonlinestore1
 
To identify the identity of Variable Interest Entity , first of all .pdf
To identify the identity of Variable Interest Entity , first of all .pdfTo identify the identity of Variable Interest Entity , first of all .pdf
To identify the identity of Variable Interest Entity , first of all .pdf
aoneonlinestore1
 
technology is the application of scientific knowledge. technology is.pdf
technology is the application of scientific knowledge. technology is.pdftechnology is the application of scientific knowledge. technology is.pdf
technology is the application of scientific knowledge. technology is.pdf
aoneonlinestore1
 
b)The cations on the left side act as oxidants. C.pdf
                     b)The cations on the left side act as oxidants. C.pdf                     b)The cations on the left side act as oxidants. C.pdf
b)The cations on the left side act as oxidants. C.pdf
aoneonlinestore1
 

More from aoneonlinestore1 (20)

1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
1. VacuolesThe vacuole is an organelle in plant cells which stores.pdf
 
1. B) - Two independent properties serve to specify the state.2. B.pdf
1. B) - Two independent properties serve to specify the state.2. B.pdf1. B) - Two independent properties serve to specify the state.2. B.pdf
1. B) - Two independent properties serve to specify the state.2. B.pdf
 
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
(NH4)2SO4 is a soluble salt and is fully ionized in solution(NH4).pdf
 
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
 I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
I have inserted spaces. Consider f(x) belonging to f(X) thi.pdf
 
C program that prompts user to enter two floating point t.pdf
  C program that prompts user to enter two floating point t.pdf  C program that prompts user to enter two floating point t.pdf
C program that prompts user to enter two floating point t.pdf
 
The carbonyl functional group in glucose is an al.pdf
                     The carbonyl functional group in glucose is an al.pdf                     The carbonyl functional group in glucose is an al.pdf
The carbonyl functional group in glucose is an al.pdf
 
Well to find the pH at the equivalance point. Acc.pdf
                     Well to find the pH at the equivalance point. Acc.pdf                     Well to find the pH at the equivalance point. Acc.pdf
Well to find the pH at the equivalance point. Acc.pdf
 
The weakest base in the reaction is A the enolat.pdf
                     The weakest base in the reaction is A the enolat.pdf                     The weakest base in the reaction is A the enolat.pdf
The weakest base in the reaction is A the enolat.pdf
 
so take an aliquot of the upper layer and add a f.pdf
                     so take an aliquot of the upper layer and add a f.pdf                     so take an aliquot of the upper layer and add a f.pdf
so take an aliquot of the upper layer and add a f.pdf
 
moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
                     moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf                     moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
moles of NH4Cl formed = 20.050 = 0.1 moles so we.pdf
 
Latency is a measure of time delay experienced in.pdf
                     Latency is a measure of time delay experienced in.pdf                     Latency is a measure of time delay experienced in.pdf
Latency is a measure of time delay experienced in.pdf
 
Entropy is the measure of disorder. Therefore, th.pdf
                     Entropy is the measure of disorder. Therefore, th.pdf                     Entropy is the measure of disorder. Therefore, th.pdf
Entropy is the measure of disorder. Therefore, th.pdf
 
dydx = 1x dy = dxx y = ln x + c .pdf
                     dydx = 1x dy = dxx y = ln x + c               .pdf                     dydx = 1x dy = dxx y = ln x + c               .pdf
dydx = 1x dy = dxx y = ln x + c .pdf
 
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdf
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdfØ Napoleonic era brought some relief to the faltering ottoman empire.pdf
Ø Napoleonic era brought some relief to the faltering ottoman empire.pdf
 
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdfYES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
YES=Cathode rays have mass. .yes=Matter contains positive and nega.pdf
 
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdfTWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
TWEEN ENGINE1.Tween engine is universal.2.Reusability of tween .pdf
 
upSolutionup.pdf
upSolutionup.pdfupSolutionup.pdf
upSolutionup.pdf
 
To identify the identity of Variable Interest Entity , first of all .pdf
To identify the identity of Variable Interest Entity , first of all .pdfTo identify the identity of Variable Interest Entity , first of all .pdf
To identify the identity of Variable Interest Entity , first of all .pdf
 
technology is the application of scientific knowledge. technology is.pdf
technology is the application of scientific knowledge. technology is.pdftechnology is the application of scientific knowledge. technology is.pdf
technology is the application of scientific knowledge. technology is.pdf
 
b)The cations on the left side act as oxidants. C.pdf
                     b)The cations on the left side act as oxidants. C.pdf                     b)The cations on the left side act as oxidants. C.pdf
b)The cations on the left side act as oxidants. C.pdf
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 

import java.awt.;import java.awt.event.;import javax.swing.;.pdf

  • 1. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.ArrayList; public class Checkers extends JPanel { public static void main(String[] args) { JFrame window = new JFrame("Checkers"); Checkers content = new Checkers(); window.setContentPane(content); window.pack(); Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation( (screensize.width - window.getWidth())/2, (screensize.height - window.getHeight())/2 ); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); window.setResizable(false); window.setVisible(true); } private JButton newGameButton; // Button for starting a new game. private JButton resignButton; // Button that a player can use to end // the game by resigning. private JLabel message; // Label for displaying messages to the user. public Checkers() { setLayout(null); // I will do the layout myself. setPreferredSize( new Dimension(350,250) ); setBackground(new Color(0,150,0)); // Dark green background. /* Create the components and add them to the applet. */
  • 2. Board board = new Board(); // Note: The constructor for the // board also creates the buttons // and label. add(board); add(newGameButton); add(resignButton); add(message); /* Set the position and size of each component by calling its setBounds() method. */ board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 ! newGameButton.setBounds(210, 60, 120, 30); resignButton.setBounds(210, 120, 120, 30); message.setBounds(0, 200, 350, 30); } // end constructor private static class CheckersMove { int fromRow, fromCol; // Position of piece to be moved. int toRow, toCol; // Square it is to move to. CheckersMove(int r1, int c1, int r2, int c2) { // Constructor. Just set the values of the instance variables. fromRow = r1; fromCol = c1; toRow = r2; toCol = c2; } boolean isJump() { // Test whether this move is a jump. It is assumed that // the move is legal. In a jump, the piece moves two // rows. (In a regular move, it only moves one row.) return (fromRow - toRow == 2 || fromRow - toRow == -2); } } // end class CheckersMove.
  • 3. private class Board extends JPanel implements ActionListener, MouseListener { CheckersData board; // The data for the checkers board is kept here. // This board is also responsible for generating // lists of legal moves. boolean gameInProgress; // Is a game currently in progress? /* The next three variables are valid only when the game is in progress. */ int currentPlayer; // Whose turn is it now? The possible values // are CheckersData.RED and CheckersData.BLACK. int selectedRow, selectedCol; // If the current player has selected a piece to // move, these give the row and column // containing that piece. If no piece is // yet selected, then selectedRow is -1. CheckersMove[] legalMoves; // An array containing the legal moves for the // current player. Board() { setBackground(Color.BLACK); addMouseListener(this); resignButton = new JButton("Resign"); resignButton.addActionListener(this); newGameButton = new JButton("New Game"); newGameButton.addActionListener(this); message = new JLabel("",JLabel.CENTER); message.setFont(new Font("Serif", Font.BOLD, 14)); message.setForeground(Color.green); board = new CheckersData(); doNewGame(); }
  • 4. /** * Respond to user's click on one of the two buttons. */ public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); if (src == newGameButton) doNewGame(); else if (src == resignButton) doResign(); } /** * Start a new game */ void doNewGame() { if (gameInProgress == true) { // This should not be possible, but it doesn't hurt to check. message.setText("Finish the current game first!"); return; } board.setUpGame(); // Set up the pieces. currentPlayer = CheckersData.RED; // RED moves first. legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves. selectedRow = -1; // RED has not yet selected a piece to move. message.setText("Red: Make your move."); gameInProgress = true; newGameButton.setEnabled(false); resignButton.setEnabled(true); repaint(); } /** * Current player resigns. Game ends. Opponent wins.
  • 5. */ void doResign() { if (gameInProgress == false) { // Should be impossible. message.setText("There is no game in progress!"); return; } if (currentPlayer == CheckersData.RED) gameOver("RED resigns. BLACK wins."); else gameOver("BLACK resigns. RED wins."); } void gameOver(String str) { message.setText(str); newGameButton.setEnabled(true); resignButton.setEnabled(false); gameInProgress = false; } void doClickSquare(int row, int col) { for (int i = 0; i < legalMoves.length; i++) if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) { selectedRow = row; selectedCol = col; if (currentPlayer == CheckersData.RED) message.setText("RED: Make your move."); else message.setText("BLACK: Make your move."); repaint(); return; }
  • 6. /* If no piece has been selected to be moved, the user must first select a piece. Show an error message and return. */ if (selectedRow < 0) { message.setText("Click the piece you want to move."); return; } /* If the user clicked on a square where the selected piece can be legally moved, then make the move and return. */ for (int i = 0; i < legalMoves.length; i++) if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol && legalMoves[i].toRow == row && legalMoves[i].toCol == col) { doMakeMove(legalMoves[i]); return; } message.setText("Click the square you want to move to."); } // end doClickSquare() void doMakeMove(CheckersMove move) { board.makeMove(move); if (move.isJump()) { legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol); if (legalMoves != null) { if (currentPlayer == CheckersData.RED) message.setText("RED: You must continue jumping."); else
  • 7. message.setText("BLACK: You must continue jumping."); selectedRow = move.toRow; // Since only one piece can be moved, select it. selectedCol = move.toCol; repaint(); return; } } if (currentPlayer == CheckersData.RED) { currentPlayer = CheckersData.BLACK; legalMoves = board.getLegalMoves(currentPlayer); if (legalMoves == null) gameOver("BLACK has no moves. RED wins."); else if (legalMoves[0].isJump()) message.setText("BLACK: Make your move. You must jump."); else message.setText("BLACK: Make your move."); } else { currentPlayer = CheckersData.RED; legalMoves = board.getLegalMoves(currentPlayer); if (legalMoves == null) gameOver("RED has no moves. BLACK wins."); else if (legalMoves[0].isJump()) message.setText("RED: Make your move. You must jump."); else message.setText("RED: Make your move."); } selectedRow = -1; if (legalMoves != null) { boolean sameStartSquare = true;
  • 8. for (int i = 1; i < legalMoves.length; i++) if (legalMoves[i].fromRow != legalMoves[0].fromRow || legalMoves[i].fromCol != legalMoves[0].fromCol) { sameStartSquare = false; break; } if (sameStartSquare) { selectedRow = legalMoves[0].fromRow; selectedCol = legalMoves[0].fromCol; } } /* Make sure the board is redrawn in its new state. */ repaint(); } // end doMakeMove(); public void paintComponent(Graphics g) { /* Draw a two-pixel black border around the edges of the canvas. */ g.setColor(Color.black); g.drawRect(0,0,getSize().width-1,getSize().height-1); g.drawRect(1,1,getSize().width-3,getSize().height-3); /* Draw the squares of the checkerboard and the checkers. */ for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if ( row % 2 == col % 2 ) g.setColor(Color.LIGHT_GRAY); else g.setColor(Color.GRAY); g.fillRect(2 + col*20, 2 + row*20, 20, 20); switch (board.pieceAt(row,col)) {
  • 9. case CheckersData.RED: g.setColor(Color.RED); g.fillOval(4 + col*20, 4 + row*20, 15, 15); break; case CheckersData.BLACK: g.setColor(Color.BLACK); g.fillOval(4 + col*20, 4 + row*20, 15, 15); break; case CheckersData.RED_KING: g.setColor(Color.RED); g.fillOval(4 + col*20, 4 + row*20, 15, 15); g.setColor(Color.WHITE); g.drawString("K", 7 + col*20, 16 + row*20); break; case CheckersData.BLACK_KING: g.setColor(Color.BLACK); g.fillOval(4 + col*20, 4 + row*20, 15, 15); g.setColor(Color.WHITE); g.drawString("K", 7 + col*20, 16 + row*20); break; } } } g.setColor(Color.cyan); for (int i = 0; i < legalMoves.length; i++) { g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19); g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17); } /* If a piece is selected for moving (i.e. if selectedRow >= 0), then draw a 2-pixel white border around that piece and draw green borders around each square that that piece can be moved to. */ if (selectedRow >= 0) { g.setColor(Color.white); g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19); g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17); g.setColor(Color.green);
  • 10. for (int i = 0; i < legalMoves.length; i++) { if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow == selectedRow) { g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19); g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17); } } } } } // end paintComponent() public void mousePressed(MouseEvent evt) { if (gameInProgress == false) message.setText("Click "New Game" to start a new game."); else { int col = (evt.getX() - 2) / 20; int row = (evt.getY() - 2) / 20; if (col >= 0 && col < 8 && row >= 0 && row < 8) doClickSquare(row,col); } } public void mouseReleased(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } } // end class Board private static class CheckersData { /* The following constants represent the possible contents of a square
  • 11. on the board. The constants RED and BLACK also represent players in the game. */ static final int EMPTY = 0, RED = 1, RED_KING = 2, BLACK = 3, BLACK_KING = 4; int[][] board; // board[r][c] is the contents of row r, column c. /** * Constructor. Create the board and set it up for a new game. */ CheckersData() { board = new int[8][8]; setUpGame(); } void setUpGame() { for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if ( row % 2 == col % 2 ) { if (row < 3) board[row][col] = BLACK; else if (row > 4) board[row][col] = RED; else board[row][col] = EMPTY; } else { board[row][col] = EMPTY; } }
  • 12. } } // end setUpGame() int pieceAt(int row, int col) { return board[row][col]; } void makeMove(CheckersMove move) { makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol); } void makeMove(int fromRow, int fromCol, int toRow, int toCol) { board[toRow][toCol] = board[fromRow][fromCol]; board[fromRow][fromCol] = EMPTY; if (fromRow - toRow == 2 || fromRow - toRow == -2) { // The move is a jump. Remove the jumped piece from the board. int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece. int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece. board[jumpRow][jumpCol] = EMPTY; } if (toRow == 0 && board[toRow][toCol] == RED) board[toRow][toCol] = RED_KING; if (toRow == 7 && board[toRow][toCol] == BLACK) board[toRow][toCol] = BLACK_KING; } CheckersMove[] getLegalMoves(int player) { if (player != RED && player != BLACK) return null; int playerKing; // The constant representing a King belonging to player. if (player == RED)
  • 13. playerKing = RED_KING; else playerKing = BLACK_KING; ArrayList moves = new ArrayList(); // Moves will be stored in this list. for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (board[row][col] == player || board[row][col] == playerKing) { if (canJump(player, row, col, row+1, col+1, row+2, col+2)) moves.add(new CheckersMove(row, col, row+2, col+2)); if (canJump(player, row, col, row-1, col+1, row-2, col+2)) moves.add(new CheckersMove(row, col, row-2, col+2)); if (canJump(player, row, col, row+1, col-1, row+2, col-2)) moves.add(new CheckersMove(row, col, row+2, col-2)); if (canJump(player, row, col, row-1, col-1, row-2, col-2)) moves.add(new CheckersMove(row, col, row-2, col-2)); } } } if (moves.size() == 0) { for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (board[row][col] == player || board[row][col] == playerKing) { if (canMove(player,row,col,row+1,col+1)) moves.add(new CheckersMove(row,col,row+1,col+1)); if (canMove(player,row,col,row-1,col+1)) moves.add(new CheckersMove(row,col,row-1,col+1)); if (canMove(player,row,col,row+1,col-1)) moves.add(new CheckersMove(row,col,row+1,col-1)); if (canMove(player,row,col,row-1,col-1)) moves.add(new CheckersMove(row,col,row-1,col-1)); }
  • 14. } } } if (moves.size() == 0) return null; else { CheckersMove[] moveArray = new CheckersMove[moves.size()]; for (int i = 0; i < moves.size(); i++) moveArray[i] = moves.get(i); return moveArray; } } // end getLegalMoves CheckersMove[] getLegalJumpsFrom(int player, int row, int col) { if (player != RED && player != BLACK) return null; int playerKing; // The constant representing a King belonging to player. if (player == RED) playerKing = RED_KING; else playerKing = BLACK_KING; ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list. if (board[row][col] == player || board[row][col] == playerKing) { if (canJump(player, row, col, row+1, col+1, row+2, col+2)) moves.add(new CheckersMove(row, col, row+2, col+2)); if (canJump(player, row, col, row-1, col+1, row-2, col+2)) moves.add(new CheckersMove(row, col, row-2, col+2)); if (canJump(player, row, col, row+1, col-1, row+2, col-2)) moves.add(new CheckersMove(row, col, row+2, col-2)); if (canJump(player, row, col, row-1, col-1, row-2, col-2)) moves.add(new CheckersMove(row, col, row-2, col-2)); }
  • 15. if (moves.size() == 0) return null; else { CheckersMove[] moveArray = new CheckersMove[moves.size()]; for (int i = 0; i < moves.size(); i++) moveArray[i] = moves.get(i); return moveArray; } } // end getLegalMovesFrom() private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) { if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8) return false; // (r3,c3) is off the board. if (board[r3][c3] != EMPTY) return false; // (r3,c3) already contains a piece. if (player == RED) { if (board[r1][c1] == RED && r3 > r1) return false; // Regular red piece can only move up. if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING) return false; // There is no black piece to jump. return true; // The jump is legal. } else { if (board[r1][c1] == BLACK && r3 < r1) return false; // Regular black piece can only move downn. if (board[r2][c2] != RED && board[r2][c2] != RED_KING) return false; // There is no red piece to jump. return true; // The jump is legal. } } // end canJump()
  • 16. private boolean canMove(int player, int r1, int c1, int r2, int c2) { if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8) return false; // (r2,c2) is off the board. if (board[r2][c2] != EMPTY) return false; // (r2,c2) already contains a piece. if (player == RED) { if (board[r1][c1] == RED && r2 > r1) return false; // Regular red piece can only move down. return true; // The move is legal. } else { if (board[r1][c1] == BLACK && r2 < r1) return false; // Regular black piece can only move up. return true; // The move is legal. } } // end canMove() } // end class CheckersData } // end class Checkers Solution import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.ArrayList; public class Checkers extends JPanel {
  • 17. public static void main(String[] args) { JFrame window = new JFrame("Checkers"); Checkers content = new Checkers(); window.setContentPane(content); window.pack(); Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize(); window.setLocation( (screensize.width - window.getWidth())/2, (screensize.height - window.getHeight())/2 ); window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); window.setResizable(false); window.setVisible(true); } private JButton newGameButton; // Button for starting a new game. private JButton resignButton; // Button that a player can use to end // the game by resigning. private JLabel message; // Label for displaying messages to the user. public Checkers() { setLayout(null); // I will do the layout myself. setPreferredSize( new Dimension(350,250) ); setBackground(new Color(0,150,0)); // Dark green background. /* Create the components and add them to the applet. */ Board board = new Board(); // Note: The constructor for the // board also creates the buttons // and label. add(board); add(newGameButton); add(resignButton); add(message);
  • 18. /* Set the position and size of each component by calling its setBounds() method. */ board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 ! newGameButton.setBounds(210, 60, 120, 30); resignButton.setBounds(210, 120, 120, 30); message.setBounds(0, 200, 350, 30); } // end constructor private static class CheckersMove { int fromRow, fromCol; // Position of piece to be moved. int toRow, toCol; // Square it is to move to. CheckersMove(int r1, int c1, int r2, int c2) { // Constructor. Just set the values of the instance variables. fromRow = r1; fromCol = c1; toRow = r2; toCol = c2; } boolean isJump() { // Test whether this move is a jump. It is assumed that // the move is legal. In a jump, the piece moves two // rows. (In a regular move, it only moves one row.) return (fromRow - toRow == 2 || fromRow - toRow == -2); } } // end class CheckersMove. private class Board extends JPanel implements ActionListener, MouseListener { CheckersData board; // The data for the checkers board is kept here. // This board is also responsible for generating // lists of legal moves.
  • 19. boolean gameInProgress; // Is a game currently in progress? /* The next three variables are valid only when the game is in progress. */ int currentPlayer; // Whose turn is it now? The possible values // are CheckersData.RED and CheckersData.BLACK. int selectedRow, selectedCol; // If the current player has selected a piece to // move, these give the row and column // containing that piece. If no piece is // yet selected, then selectedRow is -1. CheckersMove[] legalMoves; // An array containing the legal moves for the // current player. Board() { setBackground(Color.BLACK); addMouseListener(this); resignButton = new JButton("Resign"); resignButton.addActionListener(this); newGameButton = new JButton("New Game"); newGameButton.addActionListener(this); message = new JLabel("",JLabel.CENTER); message.setFont(new Font("Serif", Font.BOLD, 14)); message.setForeground(Color.green); board = new CheckersData(); doNewGame(); } /** * Respond to user's click on one of the two buttons. */ public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); if (src == newGameButton)
  • 20. doNewGame(); else if (src == resignButton) doResign(); } /** * Start a new game */ void doNewGame() { if (gameInProgress == true) { // This should not be possible, but it doesn't hurt to check. message.setText("Finish the current game first!"); return; } board.setUpGame(); // Set up the pieces. currentPlayer = CheckersData.RED; // RED moves first. legalMoves = board.getLegalMoves(CheckersData.RED); // Get RED's legal moves. selectedRow = -1; // RED has not yet selected a piece to move. message.setText("Red: Make your move."); gameInProgress = true; newGameButton.setEnabled(false); resignButton.setEnabled(true); repaint(); } /** * Current player resigns. Game ends. Opponent wins. */ void doResign() { if (gameInProgress == false) { // Should be impossible. message.setText("There is no game in progress!"); return; } if (currentPlayer == CheckersData.RED)
  • 21. gameOver("RED resigns. BLACK wins."); else gameOver("BLACK resigns. RED wins."); } void gameOver(String str) { message.setText(str); newGameButton.setEnabled(true); resignButton.setEnabled(false); gameInProgress = false; } void doClickSquare(int row, int col) { for (int i = 0; i < legalMoves.length; i++) if (legalMoves[i].fromRow == row && legalMoves[i].fromCol == col) { selectedRow = row; selectedCol = col; if (currentPlayer == CheckersData.RED) message.setText("RED: Make your move."); else message.setText("BLACK: Make your move."); repaint(); return; } /* If no piece has been selected to be moved, the user must first select a piece. Show an error message and return. */ if (selectedRow < 0) { message.setText("Click the piece you want to move."); return;
  • 22. } /* If the user clicked on a square where the selected piece can be legally moved, then make the move and return. */ for (int i = 0; i < legalMoves.length; i++) if (legalMoves[i].fromRow == selectedRow && legalMoves[i].fromCol == selectedCol && legalMoves[i].toRow == row && legalMoves[i].toCol == col) { doMakeMove(legalMoves[i]); return; } message.setText("Click the square you want to move to."); } // end doClickSquare() void doMakeMove(CheckersMove move) { board.makeMove(move); if (move.isJump()) { legalMoves = board.getLegalJumpsFrom(currentPlayer,move.toRow,move.toCol); if (legalMoves != null) { if (currentPlayer == CheckersData.RED) message.setText("RED: You must continue jumping."); else message.setText("BLACK: You must continue jumping."); selectedRow = move.toRow; // Since only one piece can be moved, select it. selectedCol = move.toCol; repaint(); return; } }
  • 23. if (currentPlayer == CheckersData.RED) { currentPlayer = CheckersData.BLACK; legalMoves = board.getLegalMoves(currentPlayer); if (legalMoves == null) gameOver("BLACK has no moves. RED wins."); else if (legalMoves[0].isJump()) message.setText("BLACK: Make your move. You must jump."); else message.setText("BLACK: Make your move."); } else { currentPlayer = CheckersData.RED; legalMoves = board.getLegalMoves(currentPlayer); if (legalMoves == null) gameOver("RED has no moves. BLACK wins."); else if (legalMoves[0].isJump()) message.setText("RED: Make your move. You must jump."); else message.setText("RED: Make your move."); } selectedRow = -1; if (legalMoves != null) { boolean sameStartSquare = true; for (int i = 1; i < legalMoves.length; i++) if (legalMoves[i].fromRow != legalMoves[0].fromRow || legalMoves[i].fromCol != legalMoves[0].fromCol) { sameStartSquare = false; break; } if (sameStartSquare) {
  • 24. selectedRow = legalMoves[0].fromRow; selectedCol = legalMoves[0].fromCol; } } /* Make sure the board is redrawn in its new state. */ repaint(); } // end doMakeMove(); public void paintComponent(Graphics g) { /* Draw a two-pixel black border around the edges of the canvas. */ g.setColor(Color.black); g.drawRect(0,0,getSize().width-1,getSize().height-1); g.drawRect(1,1,getSize().width-3,getSize().height-3); /* Draw the squares of the checkerboard and the checkers. */ for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if ( row % 2 == col % 2 ) g.setColor(Color.LIGHT_GRAY); else g.setColor(Color.GRAY); g.fillRect(2 + col*20, 2 + row*20, 20, 20); switch (board.pieceAt(row,col)) { case CheckersData.RED: g.setColor(Color.RED); g.fillOval(4 + col*20, 4 + row*20, 15, 15); break; case CheckersData.BLACK: g.setColor(Color.BLACK); g.fillOval(4 + col*20, 4 + row*20, 15, 15);
  • 25. break; case CheckersData.RED_KING: g.setColor(Color.RED); g.fillOval(4 + col*20, 4 + row*20, 15, 15); g.setColor(Color.WHITE); g.drawString("K", 7 + col*20, 16 + row*20); break; case CheckersData.BLACK_KING: g.setColor(Color.BLACK); g.fillOval(4 + col*20, 4 + row*20, 15, 15); g.setColor(Color.WHITE); g.drawString("K", 7 + col*20, 16 + row*20); break; } } } g.setColor(Color.cyan); for (int i = 0; i < legalMoves.length; i++) { g.drawRect(2 + legalMoves[i].fromCol*20, 2 + legalMoves[i].fromRow*20, 19, 19); g.drawRect(3 + legalMoves[i].fromCol*20, 3 + legalMoves[i].fromRow*20, 17, 17); } /* If a piece is selected for moving (i.e. if selectedRow >= 0), then draw a 2-pixel white border around that piece and draw green borders around each square that that piece can be moved to. */ if (selectedRow >= 0) { g.setColor(Color.white); g.drawRect(2 + selectedCol*20, 2 + selectedRow*20, 19, 19); g.drawRect(3 + selectedCol*20, 3 + selectedRow*20, 17, 17); g.setColor(Color.green); for (int i = 0; i < legalMoves.length; i++) { if (legalMoves[i].fromCol == selectedCol && legalMoves[i].fromRow == selectedRow) { g.drawRect(2 + legalMoves[i].toCol*20, 2 + legalMoves[i].toRow*20, 19, 19); g.drawRect(3 + legalMoves[i].toCol*20, 3 + legalMoves[i].toRow*20, 17, 17); } }
  • 26. } } } // end paintComponent() public void mousePressed(MouseEvent evt) { if (gameInProgress == false) message.setText("Click "New Game" to start a new game."); else { int col = (evt.getX() - 2) / 20; int row = (evt.getY() - 2) / 20; if (col >= 0 && col < 8 && row >= 0 && row < 8) doClickSquare(row,col); } } public void mouseReleased(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } } // end class Board private static class CheckersData { /* The following constants represent the possible contents of a square on the board. The constants RED and BLACK also represent players in the game. */ static final int EMPTY = 0, RED = 1, RED_KING = 2, BLACK = 3,
  • 27. BLACK_KING = 4; int[][] board; // board[r][c] is the contents of row r, column c. /** * Constructor. Create the board and set it up for a new game. */ CheckersData() { board = new int[8][8]; setUpGame(); } void setUpGame() { for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if ( row % 2 == col % 2 ) { if (row < 3) board[row][col] = BLACK; else if (row > 4) board[row][col] = RED; else board[row][col] = EMPTY; } else { board[row][col] = EMPTY; } } } } // end setUpGame() int pieceAt(int row, int col) { return board[row][col];
  • 28. } void makeMove(CheckersMove move) { makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol); } void makeMove(int fromRow, int fromCol, int toRow, int toCol) { board[toRow][toCol] = board[fromRow][fromCol]; board[fromRow][fromCol] = EMPTY; if (fromRow - toRow == 2 || fromRow - toRow == -2) { // The move is a jump. Remove the jumped piece from the board. int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece. int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece. board[jumpRow][jumpCol] = EMPTY; } if (toRow == 0 && board[toRow][toCol] == RED) board[toRow][toCol] = RED_KING; if (toRow == 7 && board[toRow][toCol] == BLACK) board[toRow][toCol] = BLACK_KING; } CheckersMove[] getLegalMoves(int player) { if (player != RED && player != BLACK) return null; int playerKing; // The constant representing a King belonging to player. if (player == RED) playerKing = RED_KING; else playerKing = BLACK_KING; ArrayList moves = new ArrayList(); // Moves will be stored in this list.
  • 29. for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (board[row][col] == player || board[row][col] == playerKing) { if (canJump(player, row, col, row+1, col+1, row+2, col+2)) moves.add(new CheckersMove(row, col, row+2, col+2)); if (canJump(player, row, col, row-1, col+1, row-2, col+2)) moves.add(new CheckersMove(row, col, row-2, col+2)); if (canJump(player, row, col, row+1, col-1, row+2, col-2)) moves.add(new CheckersMove(row, col, row+2, col-2)); if (canJump(player, row, col, row-1, col-1, row-2, col-2)) moves.add(new CheckersMove(row, col, row-2, col-2)); } } } if (moves.size() == 0) { for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { if (board[row][col] == player || board[row][col] == playerKing) { if (canMove(player,row,col,row+1,col+1)) moves.add(new CheckersMove(row,col,row+1,col+1)); if (canMove(player,row,col,row-1,col+1)) moves.add(new CheckersMove(row,col,row-1,col+1)); if (canMove(player,row,col,row+1,col-1)) moves.add(new CheckersMove(row,col,row+1,col-1)); if (canMove(player,row,col,row-1,col-1)) moves.add(new CheckersMove(row,col,row-1,col-1)); } } } } if (moves.size() == 0) return null;
  • 30. else { CheckersMove[] moveArray = new CheckersMove[moves.size()]; for (int i = 0; i < moves.size(); i++) moveArray[i] = moves.get(i); return moveArray; } } // end getLegalMoves CheckersMove[] getLegalJumpsFrom(int player, int row, int col) { if (player != RED && player != BLACK) return null; int playerKing; // The constant representing a King belonging to player. if (player == RED) playerKing = RED_KING; else playerKing = BLACK_KING; ArrayList moves = new ArrayList(); // The legal jumps will be stored in this list. if (board[row][col] == player || board[row][col] == playerKing) { if (canJump(player, row, col, row+1, col+1, row+2, col+2)) moves.add(new CheckersMove(row, col, row+2, col+2)); if (canJump(player, row, col, row-1, col+1, row-2, col+2)) moves.add(new CheckersMove(row, col, row-2, col+2)); if (canJump(player, row, col, row+1, col-1, row+2, col-2)) moves.add(new CheckersMove(row, col, row+2, col-2)); if (canJump(player, row, col, row-1, col-1, row-2, col-2)) moves.add(new CheckersMove(row, col, row-2, col-2)); } if (moves.size() == 0) return null; else { CheckersMove[] moveArray = new CheckersMove[moves.size()]; for (int i = 0; i < moves.size(); i++) moveArray[i] = moves.get(i); return moveArray;
  • 31. } } // end getLegalMovesFrom() private boolean canJump(int player, int r1, int c1, int r2, int c2, int r3, int c3) { if (r3 < 0 || r3 >= 8 || c3 < 0 || c3 >= 8) return false; // (r3,c3) is off the board. if (board[r3][c3] != EMPTY) return false; // (r3,c3) already contains a piece. if (player == RED) { if (board[r1][c1] == RED && r3 > r1) return false; // Regular red piece can only move up. if (board[r2][c2] != BLACK && board[r2][c2] != BLACK_KING) return false; // There is no black piece to jump. return true; // The jump is legal. } else { if (board[r1][c1] == BLACK && r3 < r1) return false; // Regular black piece can only move downn. if (board[r2][c2] != RED && board[r2][c2] != RED_KING) return false; // There is no red piece to jump. return true; // The jump is legal. } } // end canJump() private boolean canMove(int player, int r1, int c1, int r2, int c2) { if (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8) return false; // (r2,c2) is off the board. if (board[r2][c2] != EMPTY)
  • 32. return false; // (r2,c2) already contains a piece. if (player == RED) { if (board[r1][c1] == RED && r2 > r1) return false; // Regular red piece can only move down. return true; // The move is legal. } else { if (board[r1][c1] == BLACK && r2 < r1) return false; // Regular black piece can only move up. return true; // The move is legal. } } // end canMove() } // end class CheckersData } // end class Checkers