Download Java Programming: Enums, Classes, and Exercises and more Lecture notes Object Oriented Programming in PDF only on Docsity!
ASSIGNMENT 3
Object Oriented Programming
COMP-202B, Winter 2011, All Sections
Due: Friday, February 18th, 2011 (13:00)
You MUST do this assignment individually and, unless otherwise specified, you MUST follow all the general instructions and regulations for assignments. Graders have the discretion to deduct up to 10% of the value of this assignment for deviations from the general instructions and regulations.
Please read this entire document before starting. Important information may be contained in the warm-up questions.
Part 1: 0 points Part 2, Question 1: 30 points Part 2, Question 2: 70 points 100 points total
Part 0: Information
We will talk extensively about the following concepts in class. However, we present here a brief summary which, combined with reading documentation, should be enough to get you started.
Defining an enum
An enum is a user-defined type. The values that the enum can take come from a pre-defined set of constants. An example of an application for an enum could be to store a day of the week.
To define an enum type, first decide on the name of your new type, and create a .java file with that name. (Much as you do with a class name). Then inside that file, you will just have one statement:
public enum ENUMNAME { list of values }
For example, to define an enum for the days of the week, you would create a file Day.java and inside that file have the following statement.
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
To use the new type you have created, you can now declare a variable of this new type, or access its values by the following
ENUMNAME.ENUMVALUE
For example, after defining the prior enum Day you could have in another class
Day happyDay = Day.FRIDAY; Day[] danLectures = { Day.MONDAY, Day.WEDNESDAY, Day.FRIDAY} Day[] majaLectures = { Day.TUESDAY, Day.THURDAY }
You will then need to compile the file Day.java at the same time (i.e. by writing javac Day.java Your- Class.java) or beforehand (i.e javac Day.java and then subsequently javac YourClass.java) as your class that will use it.
Note that enums are like primitive types as they are constants. They are not references.
Creating objects
Remember that an object in Java is a class that normally has both attributes and bahviours. To define an object, you will create a class in its own file as you normally do.
To define attributes of an object, you add variables inside the class that are not part of any method. To define behaviours of an object, you add methods inside the class. For example if I create a file Chef.java with the following contents:
public class Chef private String[] recipes;
public int numberKnownRecipes;
public Chef() {
}
public void cookRecipe(String dishName) { //......some actions }
private void heatPan() { // ....some actions } }
I would be defining the type Chef as an object that has 2 properties–a list of recipes (stored as an array of String) and an integer which stores the number of recipes the chef knows. An object of type Chef knows how to do two actions—cookRecipe and heatPan.
Once I have defined a type of object, I can create instances of that type elsewhere in my program or class. In other words, once I define what a Chef is, I can create as many actual Chefs as I want elsewhere in my program. Objects are always reference types. To declare a variable that can store the address of a Chef we could write Chef ratatouille
To actually, create a Chef (allocate it in computer memory), or any object, we must use the new keyword. This is very similar to how we allocate an array.
Chef someChef = new Chef()
Once we have created a Chef we have access to some of its properties and methods. We can do this by writing the name of our variable, followed by a. followed by the name of the attribute or behaviour we wish to use. For example:
int x = someChef.numberKnownRecipes;
will assign to x the value of numberKnownRecipes inside of someChef.
Any property or method that we write public before, is accessible outside the method this way. Any property or method that we do not write public before, or write private before, is not accessible. For example, we can not write:
- Call a method called shuffle() that you will write and will take as input an array and returns void. It should, however, modify the values inside the array. Your shuffle method should pick 2 random integers between 0 and 51 (inclusive). It should then swap the cards that are at those locations in the array. This should be in a for loop so that the method repeats NUMTIMES (a final declared at the top)
- Print the entire deck after shuffling To choose a random integer, you will need to use a random number generator. In Java, to do this, you first have to import the class java.util.Random Then make a variable of type Random. You should make this an instance variable. Recall that to do this, you declare the variable outside of any other method in the class. In your main method, create a new instance of the Random class and call a method shuffle Now inside your shuffle method, you can write random.nextInt(52) to get a random integer between 0 (inclusive) and 52 (not inclusive). (Assuming of course that you have named your variable random.) Note that to compile your program, you will have to include all files on the same line. i.e. javac Value.java Suit.java Card.java CardShuffler.java
Warm-up Question 2 (0 points) Practice using loops and enums Inside the ConnectFour.java class, write a method printBoard that prints a 2d array of type Piece[][] that it takes as input. Every RED piece should be displayed as an ‘O’ Every BLACK piece should be displayed as an ‘X’ Every EMPTY square should be displayed as an ‘ ’ Because it will be hard to read otherwise, you should add a space between every column and a new line between every row.
Warm-up Question 3 (0 points) Practice with classes In this exercise, we will design a class to keep track of the moves of a connect- game and will give you practice with writing a class. The task is to design a class GameLogger which can keep track of a sequence of moves in a Connect Four game. Your class will have 1 attribute, an array of ints representing “move numbers”. Your class should have the following methods:
- public GameLogger() This constructor method should initialize an array instance variable moveList of size 2. It should also set a instance variable size to be equal to 2.
- public void addMove(int newMove) This method should add the value of newMove to the end of the array stored as a instance variable. If the array is full, it should a)create a new temporary array of size size b)copy all values from moveList to this temporary variable, c)create space to store size*2 values using the new keyword and store this array in moveList d)copy all values from the temporary array to moveList e)set size to be equal to size * 2. Then finally add the value of newMove to the array.
- public void printGameFromList()
This method should print reconstruct the game from the list of moves and print the list by writing the player and then the move and then a new line. You method may assume that the first player to go is “X” and the 2nd player to go is ”Y” For example, if the move list is 1,2,3,4 your program should print X 1
Y 2
X 3
Y 4
Part 2
The questions in this part of the assignment will be graded.
Question 1: Vector Class (30 points) This question will give you practice with classes. It will also provide practice with loops. The methods you write will be inside of a class. Create a class called Vector. The class Vector must contain 3 instance variables. Each instance variable must be declared as private. private double x; private double y; private double z; You class should have the following public methods:
- public Vector(double xcoord, double ycoord, double zcoord) This is the constructor of your vector class. It should initialize 3 private instance variables, called x, y, z with the values of the input variables, xcoord, ycoord, and zcoord respectively. Note that because the constructor has 3 input variables, you will only be able to create a Vector by providing 3 numbers. For example: Vector origin = new Vector(0,0,0); Vector equal = new Vector(1,1,1);
- public double getX() This method should return the value of the instance variable x
- public double getY() This method should return the value of the instance variable y
- public double getZ() This method should return the value of the instance variable z
- public Vector add(Vector v) This method should return a new Vector which is calculated by adding this vector–i.e. the vector which is doing the behaviour–to the vector passed to it as a parameter.
- public double dotProduct(Vector v)
Question 2: Connect Four (70 points) In this exercise, you will work with a skeleton program to produce a large part of the game Connect Four. See http://en.wikipedia.org/wiki/Connect_Four In this, you will write much of the board logic to determine things like who has won the game. You will also design part of the Artificial Intelligence for the computer player. This will provide practice in using 2-dimensional arrays, classes, and nested loops. Inside the code directory there are several files:
- Player.java
- HumanPlayer.java
- Board.java
- ComputerPlayer.java
- ConnectFour.java
- Piece.java You will add methods to the files HumanPlayer.java , Board.java , and ComputerPlayer.java Any changes you make to the other files will not be graded. You may change the file ConnectFour.java to do the warm-up exercises, but you must not change any other files. Throughout this program, we will represent the connect four board as a 2-dimensional array of type Piece which is an enum defined to be either EMPTY, RED, or BLACK. We will use the first index of the 2d array to represent the row number and the second number to represent the column number. We will call row 0 the bottom row, and column 0 the left most row. So for example, if the board is stored in a 2d array called theboard, then theboard[0][2] refers to the square located in the bottom most row and 3rd column from the left. We will use a connect four board which has 6 rows and 8 columns. (a) (5 points) HumanPlayer class You must fill in the following method to HumanPlayer.java
- public int chooseMove(Board b) This method should read an int from the user. This is a number from 0-7 that represents the column, going from left to right, of the move to be made. It should then return the number that the user entered. Note that you do not need to do any sort of checking here to make sure the number is between 0 and 7, but you must return an int. (b) (40 points) Board class The Board class must contain the following private instance variables:
- A 2-d array of type Piece called theBoard representing the piece on each square. The type Piece is defined using an enum in the file Piece.java and can take 1 of 3 values: RED, BLACK, EMPTY The first index of this array will be used to store the row and the second index will store the column. For example theBoard[2][3] will store whether the 3rd row and 4th column (since we count starting from
- contains a red piece, black piece, or is empty. Note that row 0 is on the bottom and column 0 is on the left. For this example, we will use 6 total rows and 8 total columns.
- A final int NUMROWS which will be set to 6
- A final int NUMCOLS which will be set to 8
Throughout the board class, you should never refer to the value 6 or 8 directly. You must always refer to the final described above.
In addition to these variables, you must write the following methods:
- public Board(Piece[][] oldBoard) This constructor will create a board from an array of Pieces. It must copy values one at a time from the original array oldBoard to the new one. There must be two distinct 2-d arrays after this is created. That is, it is not sufficient to write theBoard = oldBoard; The constuctor should also set the boolean isRedTurn to be true.
- public Piece getPiece(int row, int col) This method should return the piece that is located at the specified row and column. Note that the row and column indices both start from zero. So to access the element in the bottom-left most spot, one could write Piece lowerleft = getPiece(0,0);
- public Piece[][] getPieceArray() This method should return the entire 2dimensional array of pieces. Note that you should just return the 2d array. You do not and must not make a copy of the array.
- public int findFirstFreeRow(int column) This method should return the first empty space in the specified column. For example, if the first three rows of a column are filled, it should return 3. Remember that the first row is labeled row 0. If there are no free spaces in the column, you function should return -
- public boolean isLegal(int nextMove) This method should return a boolean representing whether the current move is a legal move or not. A move is legal provided that - nextMove is between 0 and NUMCOLS (inclusive of 0 but not of NUMCOLS) - There is an open space in the row
- public boolean existLegalMoves() This method should check if there exist any legal moves on the board. Do not worry whether one side has already connected 4 in a row
- public Piece getWinner() This method should check if either player has already connected four. It should return Piece.Black if black has won, Piece.Red if red has won, or Piece.Empty if there is no winner. This method must work any time that there are four pieces in a row/column/diagonal of the same colour, regardless of whether it is a “legal” sequence of connect four moves. You can not rely on whose turn it is, for example.
- void updateBoard(int moveChoice, Piece move) This method should take as input a specific column and update the board by putting the piece whose turn it is in the first free row of the specified column. You may assume that the move is legal. Remember to update the boolean isRedTurn to correspond with the new board state.
- public static Board GenerateEmptyBoard() This static method should create a new Board and fill it in with empty pieces. It should
Hint: It will be useful to write helper methods such as boolean imminentWin(Board b, Piece p). Remember that you may also use the method updateBoard from the Board class, but you should make sure to create a new Board before doing so. Hint 2:A very useful helper method to write is int getTotalTriples(Board b, Piece p, boolean requiredOpening) which returns the total number of times that player p has connected 3 in a row (not counting cases where the 4th in a row would be off the board). If requiredOpening is true, then it will verify that the 4th space is open. Otherwise it will not check.
What we have provided to you
We have provided to you several files.
- Piece.java This file defines the enum Piece which can take values EMPTY, BLACK, or RED
- ConnectFour.java This file controls the logic for a simple game of connect four.
- ComputerPlayer.java This file defines what a ComputerPlayer is. We have provided some methods for you, but you will modify the heuristic() method
- Player.java This file defines what a Player is. You should make no changes to this file
- HumanPlayer.java This file defines what a HumanPlayer is. You will write the method chooseMove
In addition, we have provided test cases for your classes. It is important to note that the test cases are not necessarily exhaustive and you will probably find it useful to write you own additional test cases in a main method (or if you feel ambitious by adding them to the test case files themselves). These additional test cases that you write will not be looked at by TAs.
- BoardTest.java This file can be used to test your Board class
- ComputerPlayerTest.java This file can be used to test your ComputerPlayer class
- VectorTest.java This file can be used to test your Vector class
To run these test cases, you can do something identical to what you did in assignment 2.
- First put all files related to the question in the same directory.
- Then compile YOUR code. You can do this by writing javac Board.java ComputerPlayer.java ConnectFour.java HumanPlayer.java Piece.java Player.java or alternatively, if you separate each question into a separate folder: javac *.java (You would do something identical for the vector class except with different file names)
- You then compile the test case via the following command: Windows javac -cp junit.jar;junit.jar;. BoardTest.java Mac OsX javac -cp junit.jar:. BoardTest.java
- To run the program, you run the connect four class, i.e. java ConnectFour
Table 1: An example of an imminent win. If it is red’s turn, then he has an imminent win because he can connect four immediately. There could also be vertical and diagonal imminent wins
B B B - - - - - R R R - - - - -
Table 2: An example of a fork. Even though it is red’s turn, there is nothing he can do to avoid losing because black has 2 possible ways to win.
- B - - - - R R - B - - - R R R - B B B - R
Table 3: An example of a fork that is also an imminent win. In this case, the heuristic should output the return of an imminent win since it does not matter that red is forked (since he can immediately win anyway)
R - - B - - - - R R - B - - - - R R - B B B - R
Table 4: An example of a fork possibility. If it is BLACK’s turn, he can put a piece into the 3rd column from the leftto set up a fork
Table 5: Here BLACK has 2 triplets of three in a row. (Without any red pieces on the board, he would have 2 different squares on the board that could be filled at some point to connect 4. Red has 2 triplets: the horizontal one on the bottom row, and the vertical one on the furthest right rows. The diagonal does not count because there is no square to get a connect 4 from. (Since there are only 8 columns)