0% found this document useful (0 votes)
153 views36 pages

LBYCPEI Final Report 6

This document provides a summary of Module 6 of the Object-Oriented Programming Laboratory course at LBYCPEI. The module covers abstraction, inheritance, and polymorphism. It includes 3 individual exercises - modifying a previous Hangman game to use an interface, creating a Pokémon card collection program using abstract classes, and developing a chess game using polymorphism. The document outlines the objectives, materials, procedures, results including screenshots, and conclusion for the module.

Uploaded by

Milo Perez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views36 pages

LBYCPEI Final Report 6

This document provides a summary of Module 6 of the Object-Oriented Programming Laboratory course at LBYCPEI. The module covers abstraction, inheritance, and polymorphism. It includes 3 individual exercises - modifying a previous Hangman game to use an interface, creating a Pokémon card collection program using abstract classes, and developing a chess game using polymorphism. The document outlines the objectives, materials, procedures, results including screenshots, and conclusion for the module.

Uploaded by

Milo Perez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

LBYCPEI

Object-Oriented Programming Laboratory

Laboratory Module 6
Abstraction, Inheritance, and Polymorphism
By
Luis Miguel IV G. Perez, LBYCPEI-EQ6

1
INTRODUCTION
Abstraction and polymorphism are two important concepts in object-oriented programming
(OOP). Abstraction refers to the act of representing essential features without including background
details or explanations. Polymorphism, on the other hand, is the ability of a single entity to take on
multiple forms. These concepts are often used together in OOP to create more flexible and reusable code.
In this article, we will explore the differences between abstract classes and interfaces, as well as the
differences between static and dynamic polymorphism. We will also learn how to create custom abstract
classes and use them in derived classes, and how to use dynamic polymorphism in OOP applications or
game programs.

Objectives
1. To understand and apply the concepts of abstraction and polymorphism.
2. To differentiate abstract classes and interfaces.
3. To compare static polymorphism and dynamic polymorphism.
4. To be able to write custom abstract classes and utilize it for multiple derived classes that have similar
behaviors.
5. To be able to use dynamic polymorphism and utilize it in an OOP application or game program.

Materials:
1. IntelliJ IDEA (Java IDE)
2. Java SE
3. cpei.jar (spl.jar)
4. ACM graphics documentation

2
PROCEDURES (Individual) / EXPERIMENTAL PLAN

I. Hangman Revisited

The goal of the first exercise is to create an interface in the IDE for the hangman activity from
previous modules. To do this, we need to add the methods from the hangman project to the interface. If
everything is done correctly, the methods in the interface should be able to reference the ones in the
hangman project.

II. Pokemon Card Collection

The second exercise asked us to create a program that keeps track of a Pokémon card collection.
The starter code provided help for us to get started. The program uses an abstract class as its foundation,
which contains methods for getting information about the individual Pokémon in the collection. Our task
is to write the relevant information for each Pokémon by creating individual classes for each Pokémon,
with their corresponding stats. The starter code contains the necessary methods to make the program
work, so we need to fill in the missing code to make the methods function correctly. The program also
uses a canvas, similar to the one used in the hangman project in previous modules, to display the images
of the Pokémon.

III. Chess Program

The final exercise asked us to create a chess game using the acm graphics program. The provided
starter code included a Chess class that extends the GraphicsProgram class and creates a ChessDisplay
object and a ChessBoard object. The Chess class also implements a mousePressed method that is called
whenever a mouse button is pressed on the game board. This method checks which player's turn it is,
whether a piece is currently selected and whether the selected piece can move to the location that was
clicked on the board. If all of these conditions are met, the selected piece is moved to the clicked location,
the game board is updated, and it becomes the other player's turn. The code also makes use of different
classes for each of the individual chess pieces in the game.

3
RESULTS AND DISCUSSION

1. Hangman Revisited

4
Explanation:

This screenshot shows the successful implementation of the past hangman code to an interface class in
java. The interface allows the user to see the methods used in the hangman class and their corresponding
functions. This makes it easy to view all the methods that are used to make the program work.

2. Pokemon Card Collection

i. Remove a Pokemon function

Explanation:

This screenshot shows the removal of a pokemon with the user’s inputted number, particularly Bulbasaur,
and the bottom of the program shows that it cannot be found.

ii. View one Pokemon

5
Explanation:

This screenshot shows the viewing of 1 random pokemon. In this screenshot, we also see an example of a
pokemon with two types, the first type being its main type and the second having its own color.

iii. Show a slideshow of pokemon

6
Explanation:

This screenshot shows the running of a slideshow of the different pokemon cards. 2 of 20 pokemon cards
is shown in the screenshots.

iv. Search a Pokemon

7
Explanation:

This screenshot shows the successful run of the search for a pokemon function. In this example, Pikachu
is searched in the ConsoleProgram then its corresponding card is shown in the GraphicsProgram on the
right.

8
3. Chess Program

i. Starting Chess Board

ii. Moving Chess Pieces

9
Explanation:

The screenshots above show the various functions of the chess program. The first screenshot shows the
start of the game while the second shows that the chess pieces are movable. The program uses
polymorphism to create a chess program using the provided starter code. It includes multiple classes for
handling the game board, the main game, and the individual chess pieces. These classes manage the
movement and actions of the chess pieces.

10
CONCLUSION:
Did you achieve your objectives for this module? Describe your achievement in this module
one-by-one, objective by objective.

1. To understand and apply the concepts of abstraction and polymorphism.


- I was able to understand these with the help of the Pokemon and Chess program.
2. To differentiate abstract classes and interfaces.
- I was able to understand these by doing the Hangman Revisited program and the two other
programs.
3. To compare static polymorphism and dynamic polymorphism.
- Studying the terms and applying the concepts to the projects helped me easily compare static
polymorphism and dynamic polymorphism.
4. To be able to write custom abstract classes and utilize it for multiple derived classes that have similar
behaviors.
- The chess program and pokemon program have multiple abstract classes and apply similar
behaviors.
5. To be able to use dynamic polymorphism and utilize it in an OOP application or game program.
- All the deliverables from this module can be applied for future use since the logic learned from
this module can be applied to other gaming programs.

What have you learned? Both technically (focused on OOP), and in general (soft skills,
attitude-related, etc.)

Understanding the concept of polymorphism in OOP, and writing more efficient code with
polymorphism. I learned that these can be used to make the code more organized and easier to understand
which can be applied in real life when I can use different methods to solve different problems.

What are the common pitfalls, mistakes, and confusion that you have encountered? How did
you overcome them?

Common mistakes I had is relating the classes to each other and making sure that they were called
or are being used for the right logic. I overcame them by checking the errors given by the IDE and
double-checking the logic that I inputted into my code.

What are your recommendations for those who will try the activity for the first time and
what can you suggest to improve this module?

11
I recommend for those who will try this activity really understand how objects work and how they
can be modified to improve the program. This module can be improved if there were less time consumed
on adjusting the graphics.

APPENDIX (Copy all source codes here per problem category)

1. Hangman Revisited(Interface Class)


public interface HangmanInterface{
void intro();
int playOneGame(String secretWord);
void displayHangman(int guessCount);
String createHint(String secretWord, String guessedLetters);
char readGuess(String guessedLetters);
String getRandomWord(String filename);
void stats(int gamesCount, int gamesWon, int best);

2.1 Pokemon Card Collection(PokemonCardCollection)


// PokemonCardCollection.java
import acm.program.ConsoleProgram;
import acm.util.RandomGenerator;

public class PokemonCardCollection extends ConsoleProgram {


private PokemonCanvas canvas; // Draws the cards similar to Hangman
private PokemonCards pokemonDeck; // Card collection object
private RandomGenerator rgen = RandomGenerator.getInstance();

public void run() {


pokemonDeck = new PokemonCards(); // loads the stats
pokemonDeck.loadStats();
int choice;
do {
println("Choose an Option:");
println("1-Remove a Pokemon");
println("2-View One Pokemon");
println("3-View slideshow of Pokemon");
println("4-Search a Pokemon");
println("5-Quit");

12
choice = readInt("Choice: ");
switch (choice) {

case 1:
int num;

for (int x = 0; x < pokemonDeck.getSize(); x++) {


num = x + 1;
print("[" + num + "]");
println(pokemonDeck.getPokemon(x).getName());
}
pokemonDeck.remove((readInt("Choose to Remove a Pokemon: ")
- 1));
break;
case 2:
int random = rgen.nextInt(0, pokemonDeck.getSize() - 1);
canvas.showPokemon(pokemonDeck.getPokemon(random));
break;
case 3:
for (int x = 0; x < pokemonDeck.getSize(); x++) {
canvas.removeAll();
canvas.showPokemon(pokemonDeck.getPokemon(x));
pause(1000);
canvas.removeAll();
}
break;
case 4:
String name = readLine("Enter the pokemon name to search:
");
int index = pokemonDeck.searchPokemon(name);
if (index != -1){
println("Pokemon "+ name + " is found!");
canvas.showPokemon(pokemonDeck.getPokemon(index));
}
else {
println("Sorry: " + name + " is not found in the
database!");
}

break;
case 5:

13
println("Thank you for using the Program");
break;
default:
println("Invalid Input");
break;
}

} while (choice != 5);


}

public void init() {


canvas = new PokemonCanvas(); // Responsible for displaying the cards
add(canvas);
setTitle("Pokemon Card Collection");
setSize(1280, 720);
}

public static void main(String[] args)


{
(new PokemonCardCollection()).start(args);
}
}

2.2 PokemonCards

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class PokemonCards extends Pokemon{

//private PokemonCanvas canvas;


private final ArrayList<Pokemon>pokedex = new ArrayList<>();

public void loadStats(){


String filename = "assets/Pokemon.txt";
try {
// Scanner Object reads the line from the file
FileReader file = new FileReader(filename);

14
// System.in reads from console while this reads from file

Scanner text = new Scanner(file);


String[] pokemonStats;
String[] stats = new String[6];
// Read and display the lines
while (text.hasNextLine()) {
String line = text.nextLine();
System.out.println(line); // working!

// Splits this string around matches of the given regular


expression.
pokemonStats = line.split(",");

for(int i = 0; i < 6; i++){


Arrays.toString(stats);
stats[i] = pokemonStats[i+1];
System.out.println(Arrays.toString(stats));
}
System.out.print(stats);

Class newPokemon = Class.forName(pokemonStats[0]);


Constructor ctor = newPokemon.getConstructor(String[].class);
Object object = ctor.newInstance(new Object[] {stats});

if (object instanceof Pokemon) {


pokedex.add((Pokemon) object); // forcing a variable to be
variable data type (Pokemon); variable type casting
}
// Doc:
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
System.out.println(Arrays.toString(pokemonStats));
// Access of parameters:
System.out.println(Arrays.toString(pokemonStats));
System.out.println(pokemonStats[0]); // Names
System.out.println(pokemonStats[1]); // Weights
System.out.println(pokemonStats[2]); // Heights
System.out.println(Double.parseDouble(pokemonStats[3]));//Attack
System.out.println(Double.parseDouble(pokemonStats[4]));//
Defense
System.out.println(Double.parseDouble(pokemonStats[5]));//
Stamina
System.out.println(pokemonStats[6]); // Types

}
//Arrays.toString(pokemonStats);

} catch (FileNotFoundException e) {

15
System.out.println("File does not Exist");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}

public int getSize(){


return pokedex.size();
}

public Pokemon getPokemon(int index){


return pokedex.get(index);
}

public void remove(int readNum){


pokedex.remove(readNum);
}

public int searchPokemon(String pokemonName){


String names = "";
int pokemonNum = 0;

for (int i = 0; i < pokedex.size(); i++){


names = pokedex.get(i).getName();
pokemonNum = i;

if (pokemonName.equalsIgnoreCase(names)){
return pokemonNum;
}
}
return -1;
}

public static void main(String[] args){


PokemonCards pokemonCards = new PokemonCards();
pokemonCards.loadStats();
System.out.println(pokemonCards.getSize());
System.out.println(pokemonCards.getPokemon(0));
}

2.3 PokemonCanvas
import acm.graphics.GCanvas;
import acm.graphics.*;

16
import java.awt.*;

public class PokemonCanvas extends GCanvas {


private final double MAX_BAR = 620;

public void showPokemon(Pokemon pokemon) {


if (pokemon.getType().contains("/")) {
showMultiBackgroundAndSprite(pokemon);
showMultiTypeStats(pokemon);
} else {
showSingleBackgroundAndSprite(pokemon);
showOneTypeStats(pokemon);
}

System.out.println(pokemon.getName());
GImage pokemonPic = new GImage("assets/" + pokemon.getName() + ".png");
pokemonPic.sendToFront();
pokemonPic.setSize(200, 200);
add(pokemonPic, 200, 100);

names(pokemon);

private void names(Pokemon pokemon) {

GLabel pokemonName = new GLabel(pokemon.getName().toUpperCase());


pokemonName.setColor(Color.WHITE);
pokemonName.setFont("Cambria-Bold-60");
double x = (getWidth() - pokemonName.getWidth()) / 2;

add(pokemonName, x, 350);
}

private void showOneTypeStats(Pokemon pokemon) {


// Your CODE here
GRect rectOne = new GRect(640, 300);

rectOne.sendBackward();

if (pokemon.getType() == "Grass") {
rectOne.setColor(Color.GREEN);
rectOne.setFilled(true);
} else if (pokemon.getType() == "Fire") {
rectOne.setColor(Color.orange);
rectOne.setFilled(true);
} else if (pokemon.getType() == "Electric") {
rectOne.setColor(Color.yellow);
rectOne.setFilled(true);
} else if (pokemon.getType() == "Water") {
rectOne.setColor(Color.blue);
rectOne.setFilled(true);
}
else if (pokemon.getType() == "Psychic") {
rectOne.setColor(Color.MAGENTA);
rectOne.setFilled(true);
}

17
else if (pokemon.getType() == "Poison") {
rectOne.setColor(Color.getColor("Purple"));
rectOne.setFilled(true);
}
add(rectOne, 0, 430);

GRect rectTwo = new GRect(610, 200);


rectTwo.setFilled(true);
rectTwo.setFillColor(Color.black);
add(rectTwo, 15, 500);

GLabel type = new GLabel(pokemon.getType().toUpperCase());


type.setFont("Cambria-Bold-60");
type.setColor(Color.WHITE);
double x = (getWidth() - type.getWidth()) / 2;
add(type, x, 480);

Font fontWH = new Font("Helvetica-Bold-60", Font.BOLD, 30);

GLabel weight = new GLabel("WEIGHT:" + pokemon.getWeight());


weight.setFont(fontWH);
weight.setColor(Color.WHITE);
add(weight, 200, 380);

GLabel height = new GLabel("HEIGHT:" + pokemon.getHeight());


height.setFont(fontWH);
height.setColor(Color.WHITE);
add(height, 200, 410);

GRect atkRect = new GRect(400, 20);


GRect atkVal = new GRect(pokemon.getAtk(), 20);
atkVal.setFilled(true);
atkRect.setFilled(true);
atkVal.setFillColor(Color.orange);
atkRect.setFillColor(Color.white);
add(atkRect, 200, 555);
add(atkVal, 200, 555);

GRect defRect = new GRect(400, 20);


GRect defVal = new GRect(pokemon.getDef(), 20);
defVal.setFilled(true);
defRect.setFilled(true);
defVal.setFillColor(Color.orange);
defRect.setFillColor(Color.white);
add(defRect, 200, 605);
add(defVal, 200, 605);

GRect stamRect = new GRect(400, 20);


GRect stamVal = new GRect(pokemon.getStamina(), 20);
stamVal.setFilled(true);
stamRect.setFilled(true);
stamVal.setFillColor(Color.orange);
stamRect.setFillColor(Color.white);
add(stamRect, 200, 655);
add(stamVal, 200, 655);

GLabel atkTxt = new GLabel("ATTACK:");

18
atkTxt.setFont("Times New Roman-Bold-30");
atkTxt.setColor(Color.WHITE);
add(atkTxt, 50, 575);

GLabel defTxt = new GLabel("DEFENSE:");


defTxt.setFont("Times New Roman-Bold-30");
defTxt.setColor(Color.WHITE);
add(defTxt, 30, 625);

GLabel stamTxt = new GLabel("STAMINA:");


stamTxt.setFont("Times New Roman-Bold-30");
stamTxt.setColor(Color.WHITE);
add(stamTxt, 35, 675);

private void showSingleBackgroundAndSprite(Pokemon pokemon) {


// Your CODE here
GImage pokemonBg = new GImage("assets/" + pokemon.getType() + ".png");
pokemonBg.setSize(640, 800);
pokemonBg.sendToBack();
add(pokemonBg);
}

private void showMultiBackgroundAndSprite(Pokemon pokemon) {


// Your CODE here
String type = pokemon.getType();
String[] typeTwo = type.split("/");
String firstType = typeTwo[0];
String secType = typeTwo[1];

GImage imgOne = new GImage("assets/" + firstType + ".png");


imgOne.setSize(640, 720);
add(imgOne);

GImage imgTwo = new GImage("assets/" + secType + ".png");


imgTwo.setSize(640, 720);
add(imgTwo);
imgTwo.sendToBack();

GRect rectOne = new GRect(640, 300);


GRect rectTwo = new GRect(320, 70);

if (firstType == "Grass" && secType == "Psychic") {


rectOne.setColor(Color.green);
rectOne.setFilled(true);

rectTwo.setColor(Color.MAGENTA);
rectTwo.setFilled(true);
} else if (firstType == "Grass" && secType == "Poison") {
rectOne.setColor(Color.GREEN);
rectOne.setFilled(true);

rectTwo.setColor(Color.MAGENTA);
rectTwo.setFilled(true);
} else if (firstType == "Water" && secType == "Psychic") {

19
rectOne.setColor(Color.blue);
rectOne.setFilled(true);

rectTwo.setColor(Color.MAGENTA);
rectTwo.setFilled(true);
}
else {
rectOne.setColor(Color.blue);
rectOne.setFilled(true);

rectTwo.setColor(Color.pink);
rectTwo.setFilled(true);
}

add(rectOne, 0, 430);
rectOne.sendForward();
rectOne.sendToFront();
add(rectTwo, 321, 430);
}
private void showMultiTypeStats(Pokemon pokemon) {
// Your CODE here

//rectOne.setColor(Color.green);

//add(rectOne,0, y + 170);

String types = pokemon.getType();


String[] typeTwo = types.split("/");
String firstType = typeTwo[0];
String secType = typeTwo[1];

GRect rectTwo = new GRect(610, 200);


rectTwo.setFilled(true);
rectTwo.setFillColor(Color.black);
add(rectTwo,10,500);

GLabel typesOne = new GLabel(firstType.toUpperCase());


typesOne.setFont("Cambria-Bold-60");
typesOne.setColor(Color.WHITE);
typesOne.sendForward();
add(typesOne, 30, 480);

GLabel typesTwo = new GLabel(secType.toUpperCase());


typesTwo.setFont("Cambria-Bold-60");
typesTwo.setColor(Color.WHITE);
typesTwo.sendForward();
add(typesTwo, 345, 480);

Font fontWH = new Font("ARIAL", Font.BOLD | Font.ITALIC, 30);

GLabel weight = new GLabel("WEIGHT:"+ pokemon.getWeight());


weight.setFont(fontWH);
weight.setColor(Color.WHITE);
add(weight,200,380);

20
GLabel height = new GLabel("HEIGHT:"+ pokemon.getHeight());
height.setFont(fontWH);
height.setColor(Color.WHITE);
add(height,200,410);

GRect atkRect = new GRect(400, 20);


GRect atkVal = new GRect(pokemon.getAtk(), 20);
atkVal.setFilled(true);
atkRect.setFilled(true);
atkVal.setFillColor(Color.orange);
atkRect.setFillColor(Color.white);
add(atkRect,200,555);
add(atkVal,200,555);

GRect defRect = new GRect(400, 20);


GRect defVal = new GRect(pokemon.getDef(), 20);
defVal.setFilled(true);
defRect.setFilled(true);
defVal.setFillColor(Color.orange);
defRect.setFillColor(Color.white);
add(defRect,200,605);
add(defVal,200,605);

GRect stamRect = new GRect(400, 20);


stamRect.setFilled(true);
stamRect.setFillColor(Color.white);
add(stamRect,200,655);

GRect stamVal = new GRect(pokemon.getStamina(), 20);


stamVal.setFilled(true);
stamVal.setFillColor(Color.orange);
add(stamVal,200,655);

GLabel atkTxt = new GLabel("ATTACK:");


atkTxt.setFont("Times New Roman-Bold-30");
atkTxt.setColor(Color.WHITE);
add(atkTxt,50,575);

GLabel defTxt = new GLabel("DEFENSE:");


defTxt.setFont("Times New Roman-Bold-30");
defTxt.setColor(Color.WHITE);
add(defTxt,30,625);

GLabel stamTxt = new GLabel("STAMINA:");


stamTxt.setFont("Times New Roman-Bold-30");
stamTxt.setColor(Color.WHITE);
add(stamTxt,35,675);
}
}

2.4 Pokemon (Abstract Class)


public abstract class Pokemon {

21
protected String name;
protected String weight;
protected String height;
protected int atk;
protected int def;
protected int stamina;
protected String type;

public String getName() {


return name;
}
public void setName(String name){
this.name = name;
}

public String getWeight(){


return weight;
}

public void setWeight(String weight){


this.weight = weight;
}

public String getHeight(){


return height;
}

public void setHeight(String height){


this.height = height;
}

public int getAtk(){


return atk;
}

public void setAtk(int atk){


this.atk = atk;
}

public int getDef(){


return def;
}

public void setDef(int def){


this.def = def;
}

public int getStamina(){


return stamina;
}

public void setStamina(int stamina){


this.stamina = stamina;
}

22
public String getType(){
return type;
}

public void setType(String type){


this.type = type;
}

2.5 Pikachu Class (Example of a Pokemon class)


public class Pikachu extends Pokemon{

public Pikachu(String[] stats){

name = "Pikachu";

type = "Electric";

this.weight = stats[0];

this.height = stats[1];

this.atk = Integer.parseInt(stats[2].trim());

this.def = Integer.parseInt(stats[3].trim());

this.stamina = Integer.parseInt(stats[4].trim());

3.1 Chess.java

import java.awt.Color;
import java.awt.event.*;

/** The main class responsible for managing the chess game */
public class Chess extends GraphicsProgram {

/**
* Object responsible for handling the graphical display on the screen
*/
ChessDisplay display;

/**
* Object that keeps track of the locations of all pieces

23
*/
ChessBoard board;

ChessFrame frame;

ChessPiece lastPieceClicked;

boolean isWhiteTurn;
boolean isBlackTurn;
boolean isPieceClicked;

/**
* Method called before run responsible for initializing the ChessDisplay
and
* ChessBoard objects
*/
public void init() {
frame = new ChessFrame(this);
frame.init();
display = ChessDisplay.getInstance(this); // This line is required,
don't change it
board = new ChessBoard();
mouseListenerAdded();

display.useRealChessLabels(false); // Use this method to change how


the board is labeled
// on the screen. Passing in true will label the board
// like an official chessboard; passing in false will
// label the board like it is indexed in an array and
// in ChessDisplay.
lastPieceClicked = null;
initBooleans();
}

/**
* The main method that runs the program
*/
public void run() {
// You fill this in.
display.draw(board);
}

//@Override
//public synchronized void addMouseListener(MouseListener l) {
//super.addMouseListener(l);
//}

public boolean mouseListenerAdded(){


addMouseListeners();
return true;
}

public void initBooleans(){

24
isWhiteTurn = true;
isBlackTurn = false;
isPieceClicked = false;
}

public void mousePressed(MouseEvent e){


int[] place = display.getLocation(e.getX(),e.getY());

if(isWhiteTurn){
if (!isPieceClicked){
if (board.pieceAt(place[0],place[1]).getColor() ==
ChessPiece.WHITE){
display.selectSquare(place[0],place[1], Color.blue);
lastPieceClicked = board.pieceAt(place[0],place[1]);
display.draw((board));
isPieceClicked = true;
} else {
println("not your piece");
}
} else {
if (lastPieceClicked.canMoveTo(place[0],place[1], board)){
board.removePiece(lastPieceClicked.getRow(),
lastPieceClicked.getCol());
lastPieceClicked.moveTo(place[0], place[1]);
board.addPiece(lastPieceClicked);
display.unselectAll();
display.draw(board);
isWhiteTurn = false;
isBlackTurn = true;
lastPieceClicked = null;
isPieceClicked = false;
System.out.println("Black's turn");
}
}
} else if (isBlackTurn){
if (!isPieceClicked){
if (board.pieceAt(place[0],place[1]).getColor() ==
ChessPiece.BLACK){
display.selectSquare(place[0],place[1], Color.blue);
lastPieceClicked = board.pieceAt(place[0],place[1]);
display.draw((board));
isPieceClicked = true;
} else {
println("not your piece");
}
} else {
if (lastPieceClicked.canMoveTo(place[0],place[1], board)){
board.removePiece(lastPieceClicked.getRow(),
lastPieceClicked.getCol());
lastPieceClicked.moveTo(place[0], place[1]);
board.addPiece(lastPieceClicked);
display.unselectAll();
display.draw(board);
isWhiteTurn = true;
isBlackTurn = false;
lastPieceClicked = null;
isPieceClicked = false;

25
System.out.println("White's turn");
}
}
}
}

@Override
public ChessFrame getChessFrame() {
return frame;
}

public static void main(String[] args){(new Chess()).start(args);}

3.2 ChessBoard
/*
* Name:
* Section Leader:
* File: ChessBoard.java
* ------------------
* This class represents the ChessBoard. Its job is to keep track of where
all
* of the pieces are. Since we just learned about two-dimensional arrays,
it
* might be a good idea to use one here (just a hint). Currently, it
doesn't do
* anything, but it does have four methods for you to fill in. These are
the only
* required methods in this class. As long as these work, feel free to do
whatever
* else you want to get this class working.
*/

public class ChessBoard extends DrawableObject{


/** Constant that sets the size of the chess board */
public static final int BOARD_SIZE = 8;
public ChessPiece[][] board;

// The constructor will need to initialize whatever data structure you’re


going
// to use to store the ChessPieces and their locations.
// The job of the constructor would be to initialize this Array to all nulls,
// as initially, there aren't any pieces on the board.

/** Constructor for the ChessBoard class (do whatever you want with this) */
public ChessBoard() {
// You fill this in.
// Note: In Java, each class variable, instance variable, or array
component is
//initialized with a default value when it is created
//For all reference types, the default value is null.
board = new ChessPiece[BOARD_SIZE][BOARD_SIZE];

26
for (int i = 0; i < 8; i++) {
addPiece(new Pawn(1,i,ChessPiece.BLACK));
addPiece(new Pawn(6,i,ChessPiece.WHITE));
}
//ROOK
addPiece(new Rook(0,0,ChessPiece.BLACK));
addPiece(new Rook(0,7,ChessPiece.BLACK));
addPiece(new Rook(7,0,ChessPiece.WHITE));
addPiece(new Rook(7,7,ChessPiece.WHITE));
//KNIGHT
addPiece(new Knight(0,1,ChessPiece.BLACK));
addPiece(new Knight(0,6,ChessPiece.BLACK));
addPiece(new Knight(7,1,ChessPiece.WHITE));
addPiece(new Knight(7,6,ChessPiece.WHITE));
//BISHOP
addPiece(new Bishop(0,2,ChessPiece.BLACK));
addPiece(new Bishop(0,5,ChessPiece.BLACK));
addPiece(new Bishop(7,2,ChessPiece.WHITE));
addPiece(new Bishop(7,5,ChessPiece.WHITE));

//QUEEN,KING
addPiece(new Queen(0,3,ChessPiece.BLACK));
addPiece(new King(0,4,ChessPiece.BLACK));
addPiece(new Queen(7,3,ChessPiece.WHITE));
addPiece(new King(7,4,ChessPiece.WHITE));

}
/** Returns the ChessPiece currently residing at the specified row and
* column. If no piece exists at the specified location, should return
* null.
*/
public ChessPiece pieceAt(int row, int col)
{
return board[row][col];
}

/** Adds the specified ChessPiece to the ChessBoard (hint: ChessPieces know
their
* own rows and columns. You can use this to figure out where to place the
piece)
*/
public void addPiece(ChessPiece piece)
{
// If the user attempts to add a piece to a location where one already
exists,
// addPiece should overwrite the old piece with the new one.
board[piece.getRow()][piece.getCol()] = piece;
}

/** Removes the piece at the specified location from the board.
*/
public void removePiece(int row, int col)
{
board[row][col] = null;
}

27
}

3.3 Bishop
/*
* Name:
* Section Leader:
* File: Bishop.java
* ------------------
* This class represents the Bishop type of chess piece. This piece can move and
capture
* pieces along diagonals. For more information visit:
http://en.wikipedia.org/wiki/Bishop_(chess)
*/

public class Bishop extends ChessPiece{

/** Constructor for the Bishop class */


public Bishop(int initialRow, int initialCol, int pieceColor)
{
this.row = initialRow;
this.col = initialCol;
this.color = pieceColor;
}

/** Method that returns a boolean indicating whether or not the bishop can
legally move
* to the specified location (you need to fill this one in).
*/
public boolean canMoveTo(int nextRow, int nextCol, ChessBoard board)
{
// Fill this in with your own code.
boolean canMoveBoolean = false;
int dx = Math.abs(this.row - nextRow);
int dy = Math.abs(this.col - nextCol);
int x = nextRow - this.row;
int y = nextCol - this.col;
int xDir = 0;
int yDir = 0;

if (dx != 0){
xDir = dx/x;
}
if (dy != 0){
yDir = dy/y;
}

if (this.color == WHITE){
if ((nextCol - this.col == nextRow - this.row) || (this.col - nextCol
== nextRow - this.row)) {
for (int i = 1; i <= Math.max(dx, dy); i++) {
if (board.pieceAt(this.row + xDir * i, this.col + yDir * i) !=
null) {
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.BLACK) {

28
canMoveBoolean = true;
} else {
canMoveBoolean = false;
break;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
}
}
} else {
if ((nextCol - this.col == nextRow - this.row) || (this.col - nextCol
== nextRow - this.row)) {
for (int i = 1; i <= Math.max(dx, dy); i++) {
if (board.pieceAt(this.row + xDir * i, this.col + yDir * i) !=
null) {
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.WHITE) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
break;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
}
}
}
return canMoveBoolean; // Eventually this line should not be here
}

/** Implementation of getType() method for the Bishop class. Provides a way
to identify
* the Bishop-type chess piece as such (you don't need to change anything
here)
*/
public PieceType getType()
{
return PieceType.BISHOP;
}
}

3.4 Rook
/*
* Name:
* Section Leader:
* File: Rook.java
* ------------------
* This class represents the Rook type of chess piece. This piece can move and
capture
* pieces along rows and columns. It is also known as a castle. For more
information visit:
* http://en.wikipedia.org/wiki/Rook_(chess)

29
*/

public class Rook extends ChessPiece{

/** Constructor for the Rook class */


public Rook(int initialRow, int initialCol, int pieceColor)
{
this.row = initialRow;
this.col = initialCol;
this.color = pieceColor;
}

/** Method that returns a boolean indicating whether or not the bishop can
legally move
* to the specified location (you need to fill this one in).
*/
public boolean canMoveTo(int nextRow, int nextCol, ChessBoard board)
{
// Fill this in with your own code.
boolean canMoveBoolean = false;
int dx = Math.abs(this.row - nextRow);
int dy = Math.abs(this.col - nextCol);
int x = nextRow - this.row;
int y = nextCol - this.col;
int xDir = 0;
int yDir = 0;

if (dx != 0){
xDir = dx/x;
}
if (dy != 0){
yDir = dy/y;
}

if (this.color == WHITE){
if (this.col == nextCol || this.row == nextRow) {
for (int i = 1; i <= Math.max(dx, dy); i++) {
if (board.pieceAt(this.row + xDir * i, this.col + yDir * i) !=
null) {
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.BLACK) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
break;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
}
}
} else {
if (this.col == nextCol || this.row == nextRow) {
for (int i = 1; i <= Math.max(dx, dy); i++) {
if (board.pieceAt(this.row + xDir * i, this.col + yDir * i) !=
null) {

30
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.WHITE) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
break;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
}
}
}
return canMoveBoolean; // Eventually this line should not be here
}

/** Implementation of getType() method for the Rook class. Provides a way to
identify
* the Rook-type chess piece as such (you don't need to change anything
here)
*/
public PieceType getType()
{
return PieceType.ROOK;
}

31
3.5 King

public class King extends ChessPiece{

/** Constructor for the King class */


public King(int initialRow, int initialCol, int pieceColor)
{
this.row = initialRow;
this.col = initialCol;
this.color = pieceColor;
}

/** Method that returns a boolean indicating whether or not the king can
legally move
* to the specified location (you need to fill this one in).
*/
public boolean canMoveTo(int nextRow, int nextCol, ChessBoard board)
{
// Fill this in with your own code.
boolean canMoveBoolean = false;
if (this.color == WHITE){
if ((this.col - nextCol)*(this.col - nextCol) + (this.row
-nextRow)*(this.row -nextRow) <= 2) {
if (board.pieceAt(nextRow, nextCol) != null){
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.BLACK) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol, board);
}
}
} else {
if ((this.col - nextCol)*(this.col - nextCol) + (this.row
-nextRow)*(this.row -nextRow) <= 2) {
if (board.pieceAt(nextRow, nextCol) != null){
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.WHITE) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
}
} else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol, board);
}
}
}
return canMoveBoolean; // Eventually this line should not be here
}

/** Implementation of getType() method for the King class. Provides a way to
identify
* the King-type chess piece as such (you don't need to change anything
here)

32
*/
public PieceType getType()
{
return PieceType.KING;
}

3.6 Knight
/*
* Name:
* Section Leader:
* File: Knight.java
* ------------------
* This class represents the Knight type of chess piece. This piece can move
only in
* L-shapes. That is it moves two spaces in one direction and one space in an
orthogonal
* direction. It is the only piece in chess that can jump over other pieces. For
* more information go here: http://en.wikipedia.org/wiki/Knight_(chess)
*/

public class Knight extends ChessPiece{

/** Constructor for the Knight class */


public Knight(int initialRow, int initialCol, int pieceColor)
{
this.row = initialRow;
this.col = initialCol;
this.color = pieceColor;
}

/** Method that returns a boolean indicating whether or not the king can
legally move
* to the specified location (you need to fill this one in).
*/
public boolean canMoveTo(int nextRow, int nextCol, ChessBoard board)
{
// Fill this in with your own code.
boolean canMoveBoolean = false;
int dx = Math.abs(this.row - nextRow);
int dy = Math.abs(this.col - nextCol);
System.out.println(dx);
System.out.println(dy);

if (this.color == WHITE){
if ((dx == 2 && dy == 1) || (dx == 1 && dy == 2 )){
if (board.pieceAt(nextRow, nextCol) != null){
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.BLACK) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
}

33
}
else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol, board);
}
}
} else {
if ((dx == 2 && dy == 1) || (dx == 1 && dy == 2 )){
if (board.pieceAt(nextRow, nextCol) != null){
if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.WHITE) {
canMoveBoolean = true;
} else {
canMoveBoolean = false;
}
}
else {
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol, board);
}
}
}
return canMoveBoolean; // Eventually this line should not be here
}

/** Implementation of getType() method for the Knight class. Provides a way
to identify
* the Knight-type chess piece as such (you don't need to change anything
here)
*/
public PieceType getType()
{
return PieceType.KNIGHT;
}

3.7 Pawn
/*
* Name:
* Section Leader:
* File: Pawn.java
* ------------------
* This class represents the Pawn type of chess piece. This piece can move only
straight
* forward (away from your side toward the other side). In can normally move
only one space
* at a time, except on the first move, when it has the option of moving two
spaces. The pawn,
* although it moves only forward, captures only diagonally forward. Turns out,
this makes it
* the most difficult to implement in code (fair warning). For more information
go
* here: http://en.wikipedia.org/wiki/Pawn_(chess)
*/

public class Pawn extends ChessPiece{

34
/** Constructor for the Pawn class */
public Pawn(int initialRow, int initialCol, int pieceColor)
{
this.row = initialRow;
this.col = initialCol;
this.color = pieceColor;
}

/** Method that returns a boolean indicating whether or not the pawn can
legally move
* to the specified location (you need to fill this one in).
*/
public boolean canMoveTo(int nextRow, int nextCol, ChessBoard board)
{
int dx = Math.abs(this.row - nextRow);
int dy = Math.abs(this.col - nextCol);
// Fill this in with your own code.
boolean canMoveBoolean = false;
if (this.color == WHITE){
if (board.pieceAt(nextRow, nextCol) == null){
if (this.row == 6){
if (dy == 0 && dx < 3){
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
} else if (dy == 0 && dx == 1){
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
} else if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.BLACK){
if (dy == 1 && dx == 1){
canMoveBoolean = true;
}
}
} else {
if (board.pieceAt(nextRow, nextCol) == null){
if (this.row == 1){
if (dy == 0 && dx < 3){
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol,
board);
}
} else if (dy == 0 && dx == 1){
canMoveBoolean = !moveWouldCauseCheck(nextRow, nextCol, board);
}
} else if (board.pieceAt(nextRow, nextCol).getColor() ==
ChessPiece.WHITE){
if (dy == 1 && dx == 1){
canMoveBoolean = true;
}
}
}
return canMoveBoolean; // Eventually this line should not be here
}

35
/** Implementation of getType() method for the Pawn class. Provides a way to
identify
* the Pawn-type chess piece as such (you don't need to change anything
here)
*/
public PieceType getType()
{
return PieceType.PAWN;
}

3.8 PieceType

public enum PieceType {


KING,
QUEEN,
ROOK,
KNIGHT,
BISHOP,
PAWN
}

36

You might also like