How to create the correct relationship between classes - java

I have a feeling this question is going to be something really common sense that I am overcomplicating. I am working on a random maze generation program, so given a width, height, and maximum path length, it will randomly select a start point and generate a path until the max path length is reached or it dead ends/gets stuck, then it will pick a new start point for another path and repeat until the whole grid is filled. I am just creating it for the practice.
I have 3 classes, but I guess I do not really understand how they should interact, or how I should make them interact for the best performance and such. One thing in particular, I just know is terrible practice. Since my Path and Point classes have to operate on the grid of Points that is created in the Maze class, I pass the constructors for Path and Point that Array of Points. It "works"... but I just realized that in doing that, I get a seemingly infinite loop where I create a grid, and create all the points for that grid, and in those points I pass an Array of Points, and each of those Points gets passed an Array of Points, forever.
I thought about making Path and Point extend Maze, but I do not think that is the right relationship. I googled interfaces and abstract classes to see if maybe that is what I wanted, but those did not seem right either.
Maze constructor:
public class Maze
{
private int fileNum = 0;
private Random rand = new Random();
private Point[] grid;
private int width, height;
private int pathLength;
private int curLoc;
private boolean debug, toTxt, toPng, hasValidNewHead = true;
public int frameNum = 0;
public int lastPercent = 0;
public Maze(int iWidth, int iHeight, int iPathLength, boolean d, boolean txt, boolean png)
{
width = iWidth;
height = iHeight;
pathLength = iPathLength;
grid = new Point[width * height];
debug = d;
toTxt = txt;
toPng = png;
}
Path constructor:
public class Path
{
private Random rand = new Random();
private Maze maze;
private int length, maxLength, lastDir, height, width;
private int curLoc;
private boolean generating;
private Point[] grid;
private boolean debug, toTxt, toPng;
public Path(int head, int gridWidth, int gridHeight, int ml, Point[] iGrid, Maze m, boolean d, boolean txt, boolean png)
{
maze = m;
generating = true;
lastDir = -1;
length = 1;
grid = iGrid;
curLoc = head;
height = gridHeight;
width = gridWidth;
maxLength = ml;
debug = d;
toTxt = txt;
toPng = png;
}
Point constructor:
public class Point
{
private int x, y, width, height;
private Point[] grid;
private int type, curLoc;
public Point(int iX, int iY, int w, int h, Point[] iGrid)
{
x = iX;
y = iY;
width = w;
height = h;
grid = iGrid;
curLoc = Arrays.asList(grid).indexOf(this);
type = 0;
}

Mazes are annoying to model because they're either structured around rooms or walls, you need different ones at different times, and either way, you'll end up with tricky code or redundant data and awkward record keeping.
Thad said, Paths are sequences/Lists of moves (North, South, East West), a Maze is an array (or Map) from a coordinate to a Cell/Room, and Cells have boolean walls keyed on moves, so { East: true, North: false, South, false, West: true}.
Or you could just make it an undirected graph.

All I had to do was make the Path and Point classes inner-classes in my Maze Class. That way they have all of the instance data from Maze that they need without needing to pass it through their constructors.

Related

best way to recognize a Free segment, hyperbole or a Polygon from segments, no java.awt

im working on a project and basically i have this thing that draw segments every time, this class segment i have 2 objects PointOnTheArea which show me the two ends of the segment in the plane:
public class PointOnTheArea implements Point {
private final double pointX;
private final double pointY;
public PointOnTheArea(double x, double y){
this.pointY = y;
this.pointX = x;
}
public double getX(){
return pointX;
}
public double getY(){
return pointY;
}
}
public class Segment {
private PointOnTheArea startingPoint;
private PointOnTheArea endingPoint;
private final SegmentType segmentType; // It is just for straight or curve
private final int radius; // just for curve segments
private final Direction dir; // direction it was drawn, is only for the plane
private boolean isTaken = false; // it is already part of a polygon???
private final int size; // distance between points
private final Color myColor; // just the color of the line
public Segment(int x1, int y1, int x2, int y2, SegmentType type, Direction dir, int radius, Color myColor){
this.segmentType = type;
this.radius = radius;
this.dir = dir;
setSegment(x1, y1, x2, y2);
this.myColor = myColor;
this.size = (int) Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));
}
and im looking to find a way to store this segments and differentiate them in polygons, hyperbole or free segments:
Hyperbola is a sequence of segments that have a junction point in common (starting point of a segment = endingPoint of another 1)
Polygon is a loop that is created between segments everyone shares his endingPoint with the startingPoint of the next one, you cannot have 2 endingPoing or 2 starting Points in common (note that a polygon could be created starting from the fourth element of a List of segments up to the last one, therefore the first ones three would become a separate hyperbola)
Free segments, i.e. segments that have been created but are not attached to any other segment
when I started the project I had thought of a LinkedList but now I find it difficult to manage everything, as many borderline cases remain uncovered, do u have some ideas? i ll appreciate a lot <3
AND NO i cannot use java.awt

Thrust method for an asteroids duplicate Java

I have a project that is similar to the Asteroids game. The game contains a thrust method, which like the name suggests thrusts the spaceship. The method is not thrusting in the direction I am asking to. The spaceship will rotate with the left and right keys and will thrust with the space key.
private static final double THRUST_VALUE = 3;
private static final int MAX_SPEED = 4;
private int lives;
private int rotationSpeed;
public void thrust() {
double[] newVelocity = new double[2];
double[] oldVelocity = getVelocity();
newVelocity[0] = oldVelocity[0] - THRUST_VALUE * Math.sin(getRotation()*Math.PI/180);
newVelocity[1] = oldVelocity[1] - THRUST_VALUE * Math.cos(getRotation()*Math.PI/180);
System.out.println(newVelocity[0]);
System.out.println(newVelocity[1]);
if (newVelocity[0] >= MAX_SPEED || newVelocity[0] <= -MAX_SPEED){
newVelocity[0] = MAX_SPEED;
}
if (newVelocity[1] >= MAX_SPEED || newVelocity[1] <= -MAX_SPEED){
newVelocity[1] = MAX_SPEED;
}
setVelocity(newVelocity);
The properties for the velocity and the rotation are inherited from a Polygon class. Here are the properties being declared:
private Point[] shape; // An array of points.
private Point position; // The offset mentioned above.
private double rotation; // Zero degrees is due east.
The code runs fine, but the logic of the code is off and it is not listening to the position, but I don't know what the issue is. All input is appreciated.

tile disappearing from rubiks cube with rotation

I'm working on a 2x2 rubik cube, and was having trouble getting one side rotate with my program. The cube is a 2d array of squares. I'm just triying to do a 90 degree counter clockwise turn.
This is what happens
https://imgur.com/a/tlskNKY
I changed the colour so I could see the specific squares and how they changed. I tried changing the order, moving specific pieces at a time to see if the problem was just overlapping pieces (no such luck).
//square class
public class square implements Comparable {
int c;
private Rectangle r;
int xpos, ypos, width, height;
public square(int a, int x, int y) {
c = a;
xpos = x;
ypos = y;
r = new Rectangle(xpos, ypos, 50, 50);
}
//some unused methods
}
//inside the cube class
public class cube{
square[] temp = new square[4]
square[][] sq= new square[6][4]
//two for loops make squares and fills the sq 2d array
//the result is in the imgur link
public void turnVc(){
temp= sq[2];
sq[2][0]=temp[1];
sq[2][1]=temp[3];
sq[2][2]=temp[2];
sq[2][3]=temp[0];
}
}
I expect the output to be the original image turned counter clockwise.
tmp is a pointer that points to the same object that sq[2] pointers. That's why when you change sq[2] content, you change tmp's as well.
i think instead of assign "temp= sq[2];" you should do the following:
temp = new square[4];
for (int i = 0; i < 4; i++) {
temp[i] = sq[2][i];
}
Edit:
i think a little improvement you could do is that you don;t need to save all the sq[2] array, you could only save the fist item. i would do like this (tmp is now a square, not an array):
tmp = sq[2][0];
sq[2][0] = sq[2][1];
sq[2][1] = sq[2][3];
sq[2][3] = sq[2][2];
sq[2][2] = tmp;
If your square class implements Cloneable, you should use clone() method possible, it is also similar to answer of #Nguyen Tan Bao, but shorter
I guess you 're C++ dev, reference in Java is like pointer in C++, you can research more Have fun !

How to choose random move that takes highest value piece in chess?

So I have an array list of all the moves at the current board state in chess that take a piece.
ArrayList<Move> takePiece;
And all the pieces have a corresponding value:
public static final int PAWN = 1;
public static final int KNIGHT = 2;
public static final int BISHOP = 3;
public static final int ROOK = 4;
public static final int QUEEN = 5;
public static final int KING = 6;
I want to be able to select a random move from the array list that takes the highest value piece.
So if 3 different moves could take the king it would randomly choose one of the 3 moves (check and checkmate haven't been implemented).
How would i go about this?
public Move(Piece p , int x, int y, int dx, int dy, boolean t){
this.p = p;
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.t = t;
}
So this is what a move is so to check the piece value that was going to be taken i would check the piece at (dx,dy).
You have to check in your array the most valuable Piece and choose your move accordingly, to make this, you must iterate twice:
// get the max value of possible pieces that could be taken
ArrayList<Move> takePiece // here you must have all possible takes
int maxPieceValue = 0;
for (Move m : takePiece) {
if(PieceCode.charToInt(m.getChar()) > maxPieceValue)
maxPieceValue = m.getPiece.getType();
}
// get a list with best moves available
ArrayList<Move> bestMoves new ArrayList<Move>();
for (Move m : takePiece) {
if(PieceCode.charToInt(m.getChar()) > maxPieceValue)
bestMoves.add(m);
}
// choose randomly one of best moves
Random random = new Random();
Move choosenMove = bestMoves.get(random.nextInt(bestMoves.lenght));

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.

Categories