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

  1. public class Ship{
  2. public static final int X = 0;
  3. public static final int Y = 1;
  4. private boolean vertical;
  5. private int[] start;
  6. private int[] end;
  7. private int length;
  8. public Ship(int[] start,int[] end){
  9. boolean vertical = start[Y] == end[Y];
  10. this.vertical = vertical;
  11. int cord;
  12. if (vertical) {
  13. cord = X;
  14. }
  15. else {
  16. cord = Y;
  17. }
  18. if (start[cord] < end[cord]){
  19. this.start = start;
  20. this.end = end;
  21. }
  22. else {
  23. this.start = end;
  24. this.end = start;
  25. }
  26. this.length = this.end[cord] - this.start[cord]+1;
  27. }
  28. public void print() {
  29. System.out.println("Start: " + "(" + this.start[X] + ", " + this.start[Y] + ")");
  30. System.out.println("End: " + "(" + this.end[X] + ", " + this.end[Y] + ")");
  31. }
  32. public int getLength() {
  33. return this.length;
  34. }
  35. public boolean isVertical() {
  36. return this.vertical;
  37. }
  38. public int[] getStart() {
  39. return this.start;
  40. }
  41. public int[] getEnd() {
  42. return this.end;
  43. }
  44. public boolean intersects(Ship other){
  45. boolean cond1;
  46. boolean cond2;
  47. boolean cond3;
  48. int cord1;
  49. int cord2;
  50. // <necessary bit, ensures algorithm works both when other is oriented horizontally or vertically>
  51. if (other.isVertical()) {
  52. cord1 = X;
  53. cord2 = Y;
  54. }
  55. else {
  56. cord1 = Y;
  57. cord2 = X;
  58. }
  59. // </necessary bit>
  60. int t_s1 = this.start[cord1];
  61. int t_e1 = this.end[cord1];
  62. int o_s1 = other.start[cord1];
  63. int o_e1 = other.end[cord1];
  64. int t_s2 = t_s2;
  65. int t_e2 = this.end[cord2];
  66. int o_s2 = other.start[cord2];
  67. int o_e2 = other.end[cord2];
  68. // lines are parallel
  69. if (this.vertical == other.isVertical()) {
  70. // overlaps
  71. cond1 = t_s2 == o_s2;
  72. // intersects
  73. cond2 = o_e1 <= t_s1;
  74. cond3 = t_e1 <= o_s1;
  75. return cond1 && (cond2 || cond3);
  76. }
  77. // lines are perpendicular
  78. else{
  79. // other in range of this with respect to axis cord1
  80. cond1 = (t_s1 >= o_s1) && (t_e1 <= o_e1);
  81. // this in range of other with respect to axis cord2
  82. cond2 = (o_s2 >= t_s2) && (o_e2 <= t_e2);
  83. return cond1 && cond2;
  84. }
  85. }
  86. }