Advertisement
dmesticg

Snake

Apr 2nd, 2020
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 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 < snakeLength;i++) {
  30. if (snakeBody[i].equals(pos)) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36.  
  37. public Position newHeadPosition(String direction) {
  38. Position pos = snakeBody[0];
  39. int currentCol = pos.getCol();
  40. int currentRow = pos.getRow();
  41. if(direction == "up") {
  42. pos = new Position(currentRow-1,currentCol);
  43. }
  44. if(direction == "down") {
  45. pos = new Position(currentRow+1,currentCol);
  46. }
  47. if(direction == "left") {
  48. pos = new Position(currentRow,currentCol-1);
  49. }
  50. if(direction == "right") {
  51. pos = new Position(currentRow,currentCol+1);
  52. }
  53. return pos;
  54. }
  55.  
  56. public void moveSnake(String direction) {
  57. Position originHead = snakeBody[0];
  58. Position newHead = newHeadPosition(direction);
  59. snakeBody[0] = newHead;
  60. for(int i = 1; i <= snakeLength - 1; i++) {
  61. Position origin = originHead;
  62. originHead = snakeBody[i];
  63. snakeBody[i] = origin;
  64. }
  65. }
  66.  
  67.  
  68.  
  69. public void grow(String direction) {
  70.  
  71. if (snakeLength == snakeBody.length) {
  72. increaseArraySize();
  73. }
  74.  
  75. snakeLength = snakeLength + 1;
  76. Position originHead = snakeBody[0];
  77. snakeBody[0] = newHeadPosition(direction);
  78. for(int i = 1; i < snakeLength; i++) {
  79. Position origin = originHead;
  80. originHead = snakeBody[i];
  81. snakeBody[i] = origin;
  82. }
  83.  
  84. }
  85.  
  86. private void increaseArraySize() {
  87. Position[] newArray = new Position[snakeLength*2];
  88. for (int i = 0; i < snakeBody.length; i++) {
  89. newArray[i] = snakeBody[i];
  90. }
  91. snakeBody = newArray;
  92. }
  93.  
  94. public static void main (String[] args) {
  95. Snake theSnake = new Snake(2,1);
  96. theSnake.snakePosition(new Position(0,1));
  97.  
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement