Advertisement
dmesticg

Untitled

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