Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. public class Spider extends Animal {
  2.  
  3. // spider algo
  4. public Position move(Board board, Direction direction, Animal ... animals)
  5. {
  6. // get the current position
  7. Position position = getPositionOnBoard();
  8.  
  9. while (true)
  10. {
  11. // get a ref sur our target position
  12. Position targetPosition = position.next(direction);
  13. Square square = null;
  14.  
  15. // try getting the square at that position
  16. try
  17. {
  18. square = board.getSquareAtPosition(targetPosition);
  19. }
  20. catch (IllegalArgumentException ex)
  21. {
  22. return null;
  23. }
  24. // oob, we are out of the board
  25. catch (ArrayIndexOutOfBoundsException ex)
  26. {
  27. return null;
  28. }
  29.  
  30. // square is null (= vide), we die
  31. if (square == null)
  32. {
  33. setPositionOnBoard(null);
  34.  
  35. return null;
  36. }
  37. // square is star, we die and replace the star by a grass
  38. else if (square.getType() == SquareType.STAR)
  39. {
  40. setPositionOnBoard(targetPosition);
  41. square.setType(SquareType.GRASS);
  42. setOnStar();
  43. setPositionOnBoard(null);
  44.  
  45. return targetPosition;
  46. }
  47. // check if the square is occupied by another animal
  48. else
  49. {
  50. for(Animal animal : animals)
  51. {
  52. // if so, stay where we are
  53. if(animal.getPositionOnBoard().equals(targetPosition))
  54. {
  55. return position;
  56. }
  57. }
  58.  
  59. // update our pos to the target position and we loop again
  60. position = targetPosition;
  61. setPositionOnBoard(position);
  62. }
  63. }
  64. }
  65.  
  66. public Spider(Position position) {
  67. super(position);
  68.  
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement