Creating a new instance for class with a boolean array - java

I'm writing a code which changes the colour of an array cell to either black or white depending on what the original colour is. If the cell is white, it changes to black and vice versa. I'm working with the below code:
public class Grid {
boolean[][] grid;
private int Height;
private int Width;
public White;
public Black;
public Grid(int height, int width) {
Height = height;
Width = width;
}
public int getHeight() {
return Height;
}
public int getWidth() {
return Width;
}
public boolean isWhite(int i, int j) {
boolean [][] Grid = new boolean [Height][Width];
for ( i = 0; i<Height ; i++);{
for (j = 0; j<Width ; j++){
if (Grid[i][j] ?? //iswhite) {
??//setBlack
}
else (??)//setWhite
}
}
}}
protected void setWhite(int i, int j) {
??
}
protected void setBlack(int i, int j) {
??
}
}
I believe I'm supposed to create an instance for Grid[i][j] depending on the boolean value however I'm not sure how to actually relate 'public boolean isWhite' to 'setWhite' and 'setBlack'. How should I go about it?

You have already defined boolean grid[][] as a class variable. You'll need to set it up in your constructor with something along the lines of grid = new boolean[height][width]; I would recommend initializing all the values, just for sanity's sake. (i.e. set them all to true or false or some predefined pattern.)
Once you've done that, you can check grid[i][j] for its value, which will either be true or false. (Whichever of those you wish to represent black and white.)
For instance, your isWhite function is as simple as this (assuming white == true)
public boolean isWhite(int i, int j) {
return grid[i][j];
}
Similarly, the set functions are also relatively minimal:
void setWhite(int i, int j) {
grid[i][j] = true;
}
void setBlack(int i, int j) {
grid[i][j] = false;
}
Additional:
You would probably want to create some code that does the appropriate thing when flipping colors rather than placing it inside the isWhite function. (It should be testing for color, not changing the values, right?)
void changeColorAtYX(int y, int x){
if(isWhite(y, x)){
setBlack(y, x);
} else {
setWhite(y,x);
}
}

1) You should probably initialize your array in your constructor. Since it is an array of primitives it will default to false in every position. If this is not what you want, set to true as needed.
2) isWhite, judging from the name, should probably just return the value at the given indices.
3) For the set methods, assuming that false == black, just set the value at the appropriate position to true or false depending on whether you want it white or black.

Related

Othello - Algorithm for finding the available options to play

I'm trying to develop the game Othello using Java and I'm struggling with the implementation of finding the available moves the player has(not computer).
For example I'm player 1, and I'm playing with the white pieces,
Check if the button is empty or not. (I'm using buttons as tiles)
Check if there're any neighbors of the opposite color.
If there is, continue checking every direction there's an opposite color until
If we reach a boundary - return false.
If we reach our color - turn all the pieces to my color.
I'm struggling implementing 3. and 5.
How can I Iterate through all the directions ( maximum of 8 directions if I'm in the inner part of the board ), and how can I can advance on checking the colors in each direction?
I thought about implementing all the 8 directions for the inner board, and then implementing all the possibilities in the outer board and checking edge options which is VERY not efficient and I don't want to code like that.
You don't have to look on the code, I'm trying to figure out how to approach it (thinking about 2 for loops), but here's the function and the whole code below: (every button has an icon - black/white piece)
private void checkLegalPlay(int row, int col) {
if(playerNum == 0){ //Black player
if(row > 0 && row < 7 && col > 0 && col < 7){ //Inner board -
//not good, i want from any point of the board
for(int i = col-1; i != 0; i--)
if(squares[row][i].getIcon() != null){
if(squares[row][i].getIcon() == blackPiece){
//Advance until boundary - return false
//Advance if there're black pieces
//If we get to white piece, turn all to
// white pieces
}
}
}
}
}
It's already almost 300 lines of code, so I prefer to give a link if you really want to see what I've done so far: -deleted-
Software development is an art of abstraction. You should try to develop a skill to see similarities between pieces of logic and to abstract them away. For example, to check if the move is legal you have to iterate from the cell in different directions applying the same check logic. Moreover, check of a move and applying move (flipping pieces) share the same iteration logic. So let's abstract it away, i.e. let's separate iteration from logic we do inside iteration:
private static final int SIZE = 8;
static boolean isValidPos(int pos) {
return pos >= 0 && pos < SIZE;
}
static class Point {
public final int row;
public final int col;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
}
private static final Point[] ALL_DIRECTIONS = new Point[]{
new Point(1, 0),
new Point(1, 1),
new Point(0, 1),
new Point(-1, 1),
new Point(-1, 0),
new Point(-1, -1),
new Point(0, -1),
new Point(1, -1),
};
interface CellHandler {
boolean handleCell(int row, int col, Icon icon);
}
void iterateCells(Point start, Point step, CellHandler handler) {
for (int row = start.row + step.row, col = start.col + step.col;
isValidPos(row) && isValidPos(col);
row += step.row, col += step.col) {
Icon icon = squares[row][col].getIcon();
// empty cell
if (icon == null)
break;
// handler can stop iteration
if (!handler.handleCell(row, col, icon))
break;
}
}
static class CheckCellHandler implements CellHandler {
private final Icon otherIcon;
private boolean hasOtherPieces = false;
private boolean endsWithMine = false;
public CheckCellHandler(Icon otherIcon) {
this.otherIcon = otherIcon;
}
#Override
public boolean handleCell(int row, int column, Icon icon) {
if (icon == otherIcon) {
hasOtherPieces = true;
return true;
} else {
endsWithMine = true;
return false;
}
}
public boolean isGoodMove() {
return hasOtherPieces && endsWithMine;
}
}
class FlipCellHandler implements CellHandler {
private final Icon myIcon;
private final Icon otherIcon;
private final List<Point> currentFlipList = new ArrayList<Point>();
public FlipCellHandler(Icon myIcon, Icon otherIcon) {
this.myIcon = myIcon;
this.otherIcon = otherIcon;
}
#Override
public boolean handleCell(int row, int column, Icon icon) {
if (icon == myIcon) {
// flip all cells
for (Point p : currentFlipList) {
squares[p.row][p.col].setIcon(myIcon);
}
return false;
} else {
currentFlipList.add(new Point(row, column));
return true;
}
}
}
private boolean checkLegalPlay(int row, int col) {
ImageIcon otherIcon = (playerNum == 0) ? whitePiece : blackPiece;
Point start = new Point(row, col);
for (Point step : ALL_DIRECTIONS) {
// handler is stateful so create new for each direction
CheckCellHandler checkCellHandler = new CheckCellHandler(otherIcon);
iterateCells(start, step, checkCellHandler);
if (checkCellHandler.isGoodMove())
return true;
}
return false;
}
ALL_DIRECTIONS represents all 8 directions you can navigate. iterateCells method accepts some direction and navigates through it till it hits either empty cell or a border. For each non-empty cell handleCell of the passed CellHandler is called. So now your checkLegalPlay becomes simple: implement CheckCellHandler and iterate through all possible directions to see if we can flip in that direction. Implementing actual flip logic is actually very similar: just implement FlipCellHandler and use it similarly. Note that you can also abstract "current player" away by explicitly passing myIcon and otherIcon to handlers.

how do i call an accsessor method from a different class for an object of that class?

I am trying to produce a proceduraly generated 2D map, but i am stuck on creating the accsessor method to just return what type a specific location is.
I created a custom square class that has the variable type and special..
here is the square class
public class Square{//custom object for map class
private int type = 0;
private boolean special = false;
public int getType(){//returns type of square
return type;
}
public boolean isSpecial(){//returns boolean for whether square is special or not
return special;
}
public void setType(int a){//sets type for square if input is between 1 and 5
if(a>=1&&a<=5){
type = a;
}
}
public void setSpecial(){//sets special status to true
special = true;
}
}
I've tested the square class to make sure it works, I am getting trouble in my Map class when i try to create a method that returns the type of square at a given coordinates
here is the applicable code from that class
public class Map{
private int mapWidth;
private int mapHeight;
Square newMap[][] = new Square[0][0];
public Map(int width, int height){//constructor sets map height and width and instantiates a 2d array with the arguments
if(width <= 0){//if user inputs numbers less than 1 will set according attribute to 1
width = 1;
}
if (height <= 0){
height = 1;
}
mapWidth = width;
mapHeight = height;
Square newMap[][] = new Square[mapWidth][mapHeight];
}
public void create(){
}
public int getWidth(){//accssesor methods
return mapWidth;
}
public int getHeight(){
return mapHeight;
}
public int getType(int x, int y){
return newMap[y][x].getType();
}
}
I know that i am probably doing something horribly wrong but any help will be greatly appreciated.

Assign states various values in Processing

I am working on a tile based game, where various tiles have different states.
I am now looking to add a player object, this object will continually check the states of the tiles in order to move.
My Tile class:
class Tile {
int x, y;
boolean empty = true;
boolean baseCell = true;
boolean active = false;
public static final int EMPTY = 0;
public static final int BASE = 1;
public static final int ACTIVE = 2;
Tile(int x_, int y_, boolean baseCell_) {
x=x_;
y=y_;
baseCell=baseCell_;
}
void display() {
if (baseCell) {
fill(0, 0, 255);
} else {
if (empty) {
fill (255);
} else if (active) {
fill(255, 100, 50);
}
}
stroke(0);
rect(x, y, 50, 50);
}
}
When the game starts, 4 baseCells are drawn and cannot be changed. The user is able to click on other cells to change their values from empty to active or active to empty.
Currently I am unsure how to assign booleans the static values I have set - or perhaps this is not the best approach.
Any help or guidance would be much appreciated.
First of all, given that you want to assign to boolean values, the values of the static variables, I would say that it would be impossible since ACTIVE = 2. This value cannot be used as a boolean since it is not 0 nor 1.So if you want to use boolean variables all static final variable values should be 0 or 1.
Secondly, you should consider gathering all the constants (static final variables) in an interface which will be implemented by each class that needs one of those constants. It is a better programming practice and this will help you organize your project better.
Finally, if you want to change the value of the variables empty,active,baseCell, you should either include them in the constructor like so:
Tile(int x_, int y_, boolean baseCell_, boolean active_, boolean empty_)
{
x=x_;
y=y_;
baseCell=baseCell_;
active = active_;
empty = empty_;
}
and/or you should implement getters and setters for each one of them like so:
//setter
protected void setEmpty(boolean empty_)
{
empty = empty_;
}
//getter
public boolean getEmpty()
{
return empty;
}
And the way to change the respective values is by simply calling either the constructor, when the object is first constructed, and the setters after that like so:
(..) new Tile( x, y, BASE, ACTIVE, EMPTY); //constructor
tile1.setEmpty(EMPTY); //tile1 is an instance of the Tile class
Final notes:
Regarding the visibility of the setter you should be careful, because if you make it public, anyone can access it and change its' value, and this affects the security of your application. The way to tackle this is through the hierarchy.
I suggest you read this: http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html (basic info on getters/setters)
and this: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
(required knowledge to tackle the setter problem)
As I was mentioning in the commend, rather than using a boolean for each state, you can use a single integer to keep track of the cell state.
This will also allow you to use a switch statement. There's nothing wrong with if/else, you can achieve the same thing, but it may help things tidy.
Here's a basic proof of the above concept based mostly on your existing code:
//a few test tiles
int numTiles = 3;
//prepare an array to store each tile
Tile[] tiles = new Tile[numTiles];
void setup(){
size(150,150);
//initialize each tile
for(int i = 0 ; i < numTiles; i++)
tiles[i] = new Tile(50*i,50,random(1) > .5);//50% pseudo-random change of getting a BASE cell
}
void draw(){
background(255);
//render tiles (they'll handle their own states internally)
for(int i = 0 ; i < numTiles; i++){
tiles[i].display();
}
}
void mouseReleased(){
//update each tile on click
for(int i = 0 ; i < numTiles; i++)
tiles[i].click(mouseX,mouseY);
}
class Tile {
int x, y;
int size = 50;
int state = 0;
public static final int EMPTY = 0;
public static final int BASE = 1;
public static final int ACTIVE = 2;
Tile(int x_, int y_, boolean baseCell_) {
x=x_;
y=y_;
if(baseCell_) state = BASE;
else state = EMPTY;
}
void click(int mx,int my){
//check if the mouse coordinates are within the tile's rectangle
boolean isOver = (mx >= x && mx <= x + size) && (my >= y && my <= y + size);
if(isOver){//if so, update states
switch(state){
case EMPTY:
state = ACTIVE;
break;
case ACTIVE:
state = EMPTY;
break;
case BASE:
println("BASE cell clicked, change what happens here");
break;
}
}
}
void display() {
switch(state){
case EMPTY:
fill(255);
break;
case ACTIVE:
fill(255, 100, 50);
break;
case BASE:
fill(0,0,255);
break;
}
stroke(0);
rect(x, y, size, size);
}
}
Later on you may choose to call functions from within the switch statements to keep the code easier to manage (especially if you might use many states)

Rectangle Project Error Fixing

I am currently working on a project called Rectangle project in which I am supposed to do the following on Java:
Make the following methods:
setOrigin
area
move
Also make a method that determines if two rectangles intersect and returns a new intersection Rectangle. Test all your methods in the ObjectDemo program for the following rectangles:
A: Origin 0,0: width 10: height 20
B: Origin 5,5: width 15, height 15
C: Origin 20,12: width 10: height 20
What is the area of each? Test if each of them intersect with the other two and what is the intersection area. Move A by 5,5; B by -5,-5: and C by -20, 0. Now give the intersection area of each.
I need to finish this by Monday but I keep getting a ton of errors like unrecognized variables, etc., and I'm not sure how to fix them. Please let me know!
I have three files: Point, RectangleTest, and Rectangle.
Here are their codes:
Point code:
public class Point
{
//Class variables
private int xCoord; //Private (instead of Public) because we are going to use this class in the other file
//We don't want people changing the values unless we let them
private int yCoord; //Variables are not in a function so will maintain their value
//Constructor
Point()
{
xCoord = 0;
yCoord = 0;
}
//Constructor
Point(int startX, int startY)
{
xCoord = startX;
yCoord = startY;
}
public int getX()
{
return xCoord;
}
public int getY()
{
return yCoord;
}
public void setX(int newX)
{
xCoord = newX;
}
public void setY(int newY)
{
yCoord = newY;
}
public void move(int moveX, int moveY)
{
xCoord+=moveX;
yCoord+=moveY;
}
Point(Point p)
{
xCoord = p.getX();
yCoord = p.getY();
}
}
RectangleTest Code:
public class RectangleTest
{
public static void main(String [] args)
{
Rectangle A = new Rectangle(0,0,10,20);
Rectangle B = new Rectangle(5,5,15,15);
Rectangle C = new Rectangle(20,12,10,20);
//Move rectangles
A.moveby(5,10);
B.moveby(-5,-5);
C.moveby(-20,0);
int areaA = A.getarea;
System.out.println("The area of rectangle A is " +areaA);
int areaB = B.getarea;
System.out.println("The area of rectangle B is " +areaB);
int areaC = C.getarea;
System.out.println("The area of rectangle C is " +areaC);
Rectanlge iAB = A.intersect(B);
Rectangle iAC = A.intersect(C);
Rectangle iBC = B.intersect(C);
if(iab != null)
{
System.out.println("The area of intersection rectangle iab = " +iAB.area());
}
if(iac != null)
{
System.out.println("The area of intersection rectangle iac = " +iAC.area());
}
if (ibc != null)
{
System.out.println("The area of intersection area ibc = " +iBC.area());
}
}
}
Rectangle Code:
public class Rectangle
{
Point origin;
int height;
int width;
//Constructor for rectangle object
Public Rectangle(int startX, int startY, int startW, int startH)
{
origin = new Point (startX, startY);
width = startW;
height = startH;
}
//Set origin point for NEW rectangle origins
//FIX
public void setOrigin(int newX, int newY)
{
origin.setX(newX);
origin.setY(newY);
}
public int moveBy(int moveX, int moveY)
{
origin.move(moveX, moveY);
}
public int getArea()
{
int recArea = height*width;
return recArea;
}
public Rectangle intersect(Rectangle testR)
{
int meTRX = origin.getX() + width;
int meTRY = origin.getY() + height;
int testTRX = testR.origin.getX() + width;
int testTRY = testR.origin.getY() + height;
//Boolean to get iTRX
if(meTRX>testTRX)
{
int iTRX = testTRX;
}
else
{
int iTRX = meTRX;
}
//Boolean to get iTRY
if(meTRY>testTRY)
{
int iTRY = testTRY;
}
else
{
int iTRY = meTRY;
}
//Boolean to get iBLX
if(testBLX>meBLX)
{
int iBLX = testBLX;
}
else
{
int iBLX = meBLX;
}
//Boolean to get iBLY
if(testBLY>meBLY)
{
int iBLY = testBLY;
}
else
{
int iBLY = meBLY;
}
//Testing for whether or not there is an intersection rectangle
if(iTRX-iBLX<0 || iTRY-iBLY<0)
{
return null;
}
int iH = iTRY - iBLY;
int iW = iTRX - iBLX;
int intersectArea = iH * iW;
}
}
Please point out any problems! I'm rather new to programming, so I usually make a lot of simple mistakes. Also, I would appreciate if there are no newly introduced commands or anything because my teacher is pretty strict about doing it this way.
Thanks!
P.S. I would appreciate any extra knowledge or info on code improvement (just in general). Thanks!
Couple of Issues:
Java is case sensitive so Public is not same as public in your rectangle class.
When your method doesnt return anything you should use void as return type. So in your method public int moveBy(int moveX, int moveY), you should change it to public void moveBy(int moveX, int moveY)
You need to define variables before using them. So variables like testBLX, meBLX, testBLY, meBLY, iTRX, iTRY, iBLX, iBLY are undefined. I am not sure from where the values will get populated. But you could avoid the compilation error by defining them as int testBLX = 0; and similarly the others.
In your Rectangle class:
In the constructor your wrote Public Rectangle(int startX, int startY, int startW, int startH), but you actually want public Rectangle(int startX, int startY, int startW, int startH). In Java keywords start always with a lower case.
Your method for changing the origin of a rectangle public int moveBy(int moveX, int moveY) has int as a return type, so the compiler wants you to return an integer value. I suppose you did not want to return anything at all so you can change the return type to void.
In your intersect method public Rectangle intersect(Rectangle testR) you declare your variables (iTRX, iTRY, iBLX, iBLY) such as int iTRX = testTRX; only in the scope of your if/else statements which means that after every if/else statement these variables are not available anymore. To learn more about the different scopes of variables: Variable scopes
In your RectangleTest class:
You forgot a part of your task: What is the area of each? Test if each of them intersect with the other two and what is the intersection area.
Some general leads:
The use of more descriptive variable names improves the readability. For example the variable name meTRX does not have any meaning for me as person who did not work on your code or maybe for you if you review your code two months later.
Before you start coding, you could check if Java has built-in classes which you can use. In your case Java provides a Point class in the package java.awt.Point. You do not have to reinvent the wheel.
I would also recommend to read the Java Code Conventions Code Conventions which can bring you and others who read your code on a common denominator in the future.

Position and orientation of robot in a grid

I want to make a 10x10 grid and put the robot in position (10,1) (bottom left). I want this robot to be able to move forward, turn left/right and to pick up/put objects in a grid. When put in any position, there should be number in a grid which shows how many objects is put in this position, just like this:
..........
...1......
..2.......
....3.....
..........
..........
......9...
.....4....
.........1
..........
We will not see the robot in a grid. I have two classes. Class Robot:
public class Robot {
private Area area;
private Robot rob;
public Robot(Area area){
this.area = area;
rob = new Robot(area);
}
public void Right(){
}
public void Left(){
}
public void Forward(){
}
public void Put(){
}
public void PickUp(){
}
public (?) getPosition(){ // should return robot's position
}
}
Class Area:
private int numberOfObjects;
private Robot robot;
private static final int X = 10;
private static final int Y = 10;
private Object [][] area; // grid
public Area(){ // defines a grid and robot
area = new Area[X][Y];
for(int a=0;a<X;a++){
for(int b=0;b<Y;b++)
area[a][b]=".";
}
numberOfObjects = 0; // grid is initially empty
Area ar = new Area();
robot = new Robot(ar);
}
public void Put(int x,int y){ // put the object to position (x,y)
area[x][y]=numberOfObjects++;
}
public void PickUp(int x,int y){ // pick up the object in position (x,y)
if(area[x][y]!=null){
area[x][y]=numberOfObjects--;
}
}
public void PrintAGrid(){
for(int r=0;r<X;r++){
for(int c=0;c<Y;c++)
System.out.print(area[r][c]+" ");
System.out.println();
}
System.out.println();
}
}
How can I put the robot in position (10,1)? How can I declare and set its orientation (i.e. on the right)? I guess it will be easy to write other methods, so I do not focus on it.
There are several issues with your code.
Why do you have an instance of Robot inside the class Robot? You have not used that instance at all!
private Object [][] area; should be int[][] area. You always save int in this, right?
If I understand your requirements correctly, Your implementation of pick and put is not correct.
Here is a help how you can solve the problems. I had to think several times if Robot should be in Grid or it should be the other way. I ended up with Grid in Robot.
May be Grid could be a singleton.
Here is our Grid
public class Grid {
private int[][] numberOfObjects = new int[10][10];
public void put(int x, int y) {
numberOfObjects[y][x]++;
}
public void pick(int x, int y) {
numberOfObjects[y][x]--;
}
}
You can replace parameters int x, int y with a Point.
And here is the robot
public class Robot {
private static final int NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3;
private int direction;
private int x, y;
private Grid grid;
public Robot(Grid grid) {
this.x = 0;
this.y = 0;
this.grid = grid;
direction = NORTH;
}
public void right() {
direction++;
if (direction == 4) {
direction = 0;
}
}
public void left() {
direction--;
if (direction == -1) {
direction = 3;
}
}
public void forward() {
if (direction == NORTH) {
y--;
} else if (direction == SOUTH) {
y++;
} else if (direction == EAST) {
x++;
} else if (direction == WEST) {
x--;
}
}
public void put() {
grid.put(x, y);
}
public void pick() {
grid.pick(x, y);
}
}
You need to represent the curent location with a variable and initialize it to the 10 1 postion, though your array goes 0-9 and 0-9 so this may be 9,0. to store this position maybe try a Point object that contains a Point x,y.
If someone is interested in a JavaScript version, you can have a look at this repo right here. In general:
The robot must have a facing direction (left, up, right, down).
The are three possible commands: left, right, move.
With that being said, the algorithm is quite straightforward:
totalScore = 0
Foreach i in input
computeCurrentDirection()
if input != MOVE: continue
totalScore += i
return totalScore
There are several sweet-tricks that someone might do to optimize the functions. Take a look at switchDirection.
const directionArray = [Directions.RIGHT, Directions.DOWN, Directions.LEFT, Directions.UP];
const switchDirection = (currDirection, command) => {
if (command === Commands.MOVE) {
return currDirection
}
const currDirectionIndex = directionArray.indexOf(currDirection);
if (command === Commands.RIGHT) {
return directionArray[(currDirectionIndex + 1) % 4];
}
return directionArray[((currDirectionIndex - 1) + 4) % 4];
}
Instead of an exhaustive approach, someone might use an array to help compute the upcoming direction of the robot. This significantly reduces the amount of needed code.
Note this implementation can be easily expanded to accommodate any new requirements needed for project expansion. When faced with such questions, try to architect your codebase in a testable and expandable way, because it's usually the case where reviewers are interested in your coding organizational skills, rather than whether you are able to solve the problem or not.

Categories