Advertisement
dmesticg

Untitled

Feb 10th, 2020
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. public class Snake {
  2.  
  3. private int snakeLength;
  4. private Position[] snakeBody;
  5.  
  6. public Snake(int row, int col) {
  7. snakeLength = 0;
  8. snakeLength = 1;
  9. snakeBody = new Position[5];
  10. Position initial = new Position(row, col);
  11. snakeBody[0] = initial;
  12. }
  13.  
  14. public int getLength() {
  15. return snakeLength;
  16. }
  17.  
  18. public Position getPosition(int index) {
  19. if(index < 0 || index >= snakeLength) {
  20. return null;
  21. }
  22. return snakeBody[index];
  23. }
  24.  
  25. public void shrink() {
  26. snakeLength = snakeLength - 1;
  27. }
  28.  
  29. public boolean snakePosition(Position pos) {
  30. for(int i = 0; i < snakeBody.length;i++) {
  31. boolean isEqual = pos.equals(snakeBody[i]);
  32. if (isEqual = true) {
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38.  
  39. public Position newHeadPosition(String direction) {
  40. Position pos = snakeBody[0];
  41. int currentCol = pos.getCol();
  42. int currentRow = pos.getRow();
  43. if(direction == "up") {
  44. pos = new Position(currentRow,currentCol-1);
  45. }
  46. if(direction == "down") {
  47. pos = new Position(currentRow,currentCol+1);
  48. }
  49. if(direction == "left") {
  50. pos = new Position(currentRow-1,currentCol);
  51. }
  52. if(direction == "right") {
  53. pos = new Position(currentRow+1,currentCol);
  54. }
  55. return pos;
  56. }
  57.  
  58. public void moveSnake(String direction) {
  59. for(int i = 1; i < snakeLength - 2; i++) {
  60. snakeBody[i] = snakeBody[i-1];
  61. }
  62. Position newHead = newHeadPosition(direction);
  63. snakeBody[0] = newHead;
  64. }
  65.  
  66. public void grow(String direction) {
  67. if(snakeLength != snakeBody.length) {
  68. for(int i = 1; i < snakeLength - 1; i++) {
  69. snakeBody[i] = snakeBody[i-1];
  70. }
  71. } else {
  72. increaseArraySize();
  73. grow(direction);
  74. }
  75. }
  76.  
  77. private void increaseArraySize() {
  78. Position[] newArray = new Position[snakeLength*2];
  79. for (int i = 0; i < snakeBody.length; i++) {
  80. newArray[i] = snakeBody[i];
  81. }
  82. snakeBody = newArray;
  83.  
  84. }
  85.  
  86. public static void main (String[] args) {
  87. int length = getLength();
  88. System.out.print(length);
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement