You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.3 KiB

public class Ship{
public static final int X = 0;
public static final int Y = 1;
private boolean vertical;
private int[] start;
private int[] end;
private int length;
public Ship(int[] start,int[] end){
boolean vertical = start[Y] == end[Y];
this.vertical = vertical;
int cord;
if (vertical) {
cord = X;
}
else {
cord = Y;
}
if (start[cord] < end[cord]){
this.start = start;
this.end = end;
}
else {
this.start = end;
this.end = start;
}
this.length = this.end[cord] - this.start[cord]+1;
}
public void print() {
System.out.println("Start: " + "(" + this.start[X] + ", " + this.start[Y] + ")");
System.out.println("End: " + "(" + this.end[X] + ", " + this.end[Y] + ")");
}
public int getLength() {
return this.length;
}
public boolean isVertical() {
return this.vertical;
}
public int[] getStart() {
return this.start;
}
public int[] getEnd() {
return this.end;
}
public boolean intersects(Ship other){
boolean cond1;
boolean cond2;
boolean cond3;
int cord1;
int cord2;
// <necessary bit, ensures algorithm works both when other is oriented horizontally or vertically>
if (other.vertical) {
cord1 = X;
cord2 = Y;
}
else {
cord1 = Y;
cord2 = X;
}
// </necessary bit>
int t_s1 = this.start[cord1];
int t_e1 = this.end[cord1];
int o_s1 = other.start[cord1];
int o_e1 = other.end[cord1];
int t_s2 = this.start[cord2];
int t_e2 = this.end[cord2];
int o_s2 = other.start[cord2];
int o_e2 = other.end[cord2];
// lines are parallel
if (this.vertical == other.vertical) {
// overlaps
cond1 = t_s2 == o_s2;
// intersects
cond2 = o_e1 >= t_s1;
cond3 = t_e1 >= o_s1;
return cond1 && (cond2 || cond3);
}
// lines are perpendicular
else{
// other in range of this with respect to axis cord1
cond1 = (t_s1 >= o_s1) && (t_e1 <= o_e1);
// this in range of other with respect to axis cord2
cond2 = (o_s2 >= t_s2) && (o_e2 <= t_e2);
return cond1 && cond2;
}
}
}