Java easy understanding code


  • 0
    T

    public class SnakeGame {
    /** Initialize your data structure here.
    @param width - screen width
    @param height - screen height
    @param food - A list of food positions
    E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */

    LinkedList<Integer> queue;
    int[][] f;
    int len;
    int currP;
    int fIndex;
    int w;
    int h;
    private int PToNum(int x, int y) {
        return x * h + y;
    }
    
    private int[] NumToP(int num) {
        return new int[]{num/h, num%h};
    }
    
    public SnakeGame(int width, int height, int[][] food) {
        len = 1;
        queue = new LinkedList<Integer>();
        currP = 0;
        fIndex = 0;
        h = width;
        w = height;
        f = food;
    }
    
    /** Moves the snake.
        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
        @return The game's score after the move. Return -1 if game over. 
        Game over when snake crosses the screen boundary or bites its body. */
    public int move(String direction) {
        int[] pos = NumToP(currP);
        if (direction.equals("U")) {
            pos[0]--;
        }
        else if (direction.equals("D")) {
            pos[0]++;
        }
        else if (direction.equals("R")) {
            pos[1]++;
        }
        else if (direction.equals("L")) {
            pos[1]--;
        }
        if (pos[0] < 0 || pos[0] >= w || pos[1] < 0 || pos[1] >= h) {
            return -1;
        }
        int newP = PToNum(pos[0], pos[1]);
        if (fIndex < f.length && pos[0] == f[fIndex][0] && pos[1] == f[fIndex][1]) {
            fIndex++;
            len++;
        }
        else {
            queue.poll();
            if (queue.contains(newP))
                return -1;
        }
        queue.offer(newP);
        currP = newP;
        return len-1;
    }
    

    }
    /**

    • Your SnakeGame object will be instantiated and called as such:
    • SnakeGame obj = new SnakeGame(width, height, food);
    • int param_1 = obj.move(direction);
      */

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.