Snake/Java: Difference between revisions

m
→‎Code: Use enum constructor rather than EnumMap
mNo edit summary
m (→‎Code: Use enum constructor rather than EnumMap)
Line 10:
public class Snake extends JPanel implements Runnable {
enum Dir {
up(0, -1), right(1, 0), down(0, 1), left(-1, 0);
 
Dir(int x, int y) {
dirs.put(Dir.up, xy = new int[]{0x, -1y});
}
 
final int[] xy;
};
 
static final Random rand = new Random();
static final EnumMap<Dir, int[]> dirs = new EnumMap<>(Dir.class);
static final int WALL = -1;
static final int MAX_ENERGY = 1500;
 
static {
dirs.put(Dir.up, new int[]{0, -1});
dirs.put(Dir.right, new int[]{1, 0});
dirs.put(Dir.down, new int[]{0, 1});
dirs.put(Dir.left, new int[]{-1, 0});
}
 
volatile boolean gameOver = true;
Line 161 ⟶ 159:
boolean hitsWall() {
Point head = snake.get(0);
int nextCol = head.x + dirs.get(dir).xy[0];
int nextRow = head.y + dirs.get(dir).xy[1];
return grid[nextRow][nextCol] == WALL;
}
Line 168 ⟶ 166:
boolean hitsSnake() {
Point head = snake.get(0);
int nextCol = head.x + dirs.get(dir).xy[0];
int nextRow = head.y + dirs.get(dir).xy[1];
for (Point p : snake)
if (p.x == nextCol && p.y == nextRow)
Line 178 ⟶ 176:
boolean eatsTreat() {
Point head = snake.get(0);
int nextCol = head.x + dirs.get(dir).xy[0];
int nextRow = head.y + dirs.get(dir).xy[1];
for (Point p : treats)
if (p.x == nextCol && p.y == nextRow) {
Line 200 ⟶ 198:
}
Point head = snake.get(0);
head.x += dirs.get(dir).xy[0];
head.y += dirs.get(dir).xy[1];
}
 
void growSnake() {
Point tail = snake.get(snake.size() - 1);
int x = tail.x + dirs.get(dir).xy[0];
int y = tail.y + dirs.get(dir).xy[1];
snake.add(new Point(x, y));
}
Anonymous user