Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Snake {
- private int snakeLength;
- private Position[] snakeBody;
- public Snake(int row, int col) {
- snakeLength = 1;
- snakeBody = new Position[5];
- Position initial = new Position(row, col);
- snakeBody[0] = initial;
- }
- public int getLength() {
- return snakeLength;
- }
- public Position getPosition(int index) {
- if(index < 0 || index >= snakeLength) {
- return null;
- }
- return snakeBody[index];
- }
- public void shrink() {
- snakeLength = snakeLength - 1;
- }
- public boolean snakePosition(Position pos) {
- for(int i = 0; i <= snakeBody.length-1;i++) {
- if (snakeBody[0] != null) {
- boolean isEqual = pos.equals(snakeBody[0]);
- if (isEqual == true) {
- return true;
- }
- }
- }
- return false;
- }
- public Position newHeadPosition(String direction) {
- Position pos = snakeBody[0];
- int currentCol = pos.getCol();
- int currentRow = pos.getRow();
- if(direction == "up") {
- pos = new Position(currentRow-1,currentCol);
- }
- if(direction == "down") {
- pos = new Position(currentRow+1,currentCol);
- }
- if(direction == "left") {
- pos = new Position(currentRow,currentCol-1);
- }
- if(direction == "right") {
- pos = new Position(currentRow,currentCol+1);
- }
- return pos;
- }
- public void moveSnake(String direction) {
- for(int i = 1; i < snakeLength - 2; i++) {
- snakeBody[i] = snakeBody[i-1];
- }
- Position newHead = newHeadPosition(direction);
- snakeBody[0] = newHead;
- }
- public void grow(String direction) {
- if(snakeLength <= snakeBody.length) {
- snakeLength = snakeLength + 1;
- snakeBody[0] = newHeadPosition(direction);
- for(int i = 1; i < snakeLength; i++) {
- snakeBody[i] = snakeBody[i-1];
- }
- } else {
- increaseArraySize();
- grow(direction);
- }
- }
- private void increaseArraySize() {
- Position[] newArray = new Position[snakeLength*2];
- snakeLength = snakeLength * 2;
- for (int i = 0; i < snakeBody.length; i++) {
- newArray[i] = snakeBody[i];
- }
- snakeBody = newArray;
- }
- public static void main (String[] args) {
- Snake theSnake = new Snake(2,1);
- theSnake.snakePosition(new Position(0,1));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement