标签:
1 public class SnakeGame { 2 private Deque<Integer> snake; 3 private int[][] food; 4 private int width; 5 private int height; 6 private boolean isGameOver; 7 private int index; 8 9 /** Initialize your data structure here. 10 @param width - screen width 11 @param height - screen height 12 @param food - A list of food positions 13 E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ 14 public SnakeGame(int width, int height, int[][] food) { 15 this.food = food; 16 this.width = width; 17 this.height = height; 18 snake = new LinkedList<>(); 19 snake.offer(0); 20 isGameOver = false; 21 index = 0; 22 } 23 24 /** Moves the snake. 25 @param direction - ‘U‘ = Up, ‘L‘ = Left, ‘R‘ = Right, ‘D‘ = Down 26 @return The game‘s score after the move. Return -1 if game over. 27 Game over when snake crosses the screen boundary or bites its body. */ 28 public int move(String direction) { 29 if (isGameOver) { 30 return -1; 31 } 32 int head = snake.getFirst(); 33 int tail = snake.pollLast(); 34 int x = head / width; 35 int y = head % width; 36 37 switch (direction) { 38 case "U": 39 x--; 40 break; 41 case "D": 42 x++; 43 break; 44 case "L": 45 y--; 46 break; 47 case "R": 48 y++; 49 break; 50 } 51 52 if (x < 0 || x >= height || y < 0 || y >= width || snake.contains(x*width + y)) { 53 isGameOver = true; 54 return -1; 55 } 56 snake.addFirst(x*width + y); 57 if (index < food.length && food[index][0] == x && food[index][1] == y) { 58 index++; 59 snake.offer(tail); 60 } 61 return snake.size() - 1; 62 } 63 } 64 65 /** 66 * Your SnakeGame object will be instantiated and called as such: 67 * SnakeGame obj = new SnakeGame(width, height, food); 68 * int param_1 = obj.move(direction); 69 */
1. The score got is not original size of snake since starting score is 0 when snake size is 1.
2. Do not forget to add the head after check death.
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5631732.html