xxxxxxxxxx
135
const STATES = {
MENU: 0,
GAME: 1,
GAME_OVER: 2,
};
function getSpritePosition(row, col, w, h) {
let dx = col * w;
let dy = row * h;
// let dx = int(col * w + w / 2);
// let dy = int(row * h + h / 2);
return { dx: dx, dy: dy };
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
let fg, bg;
let rows, cols;
let tileSize;
let grid;
let state;
let player;
function setup() {
// nokia-ish screen colors
bg = "#9bca1d";
fg = "#203d04";
rows = 25;
cols = 25;
tileSize = 16;
state = STATES.GAME;
grid = [];
for (let r = 0; r < rows; r++) {
grid[r] = [];
for (let c = 0; c < cols; c++) {
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) grid[r][c] = "#";
else grid[r][c] = ".";
}
}
// lazy creation
player = {};
player.tail = [createVector(int(cols / 2), int(rows / 2))];
player.dirs = [createVector(1, 0)];
createCanvas(cols * tileSize, rows * tileSize);
frameRate(2);
}
function keyPressed() {
switch (keyCode) {
case UP_ARROW:
player.dirs[0].x = 0;
player.dirs[0].y = -1;
break;
case DOWN_ARROW:
player.dirs[0].x = 0;
player.dirs[0].y = 1;
break;
case LEFT_ARROW:
player.dirs[0].x = -1;
player.dirs[0].y = 0;
break;
case RIGHT_ARROW:
player.dirs[0].x = 1;
player.dirs[0].y = 0;
break;
}
}
function draw() {
background(bg);
noStroke();
if (state == STATES.GAME) {
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
fill(fg);
if (grid[r][c] == "#" || grid[r][c] == "!") {
let pos = getSpritePosition(r, c, tileSize, tileSize);
rect(pos.dx, pos.dy, tileSize, tileSize);
}
}
}
// update player
for (let i = player.tail.length-1; i >= 0; i--) {
// for (let i = 0; i < player.tail.length; i++) {
if (grid[player.tail[i].y][player.tail[i].x] == "#")
state = STATES.GAME_OVER;
else if (grid[player.tail[i].y][player.tail[i].x] == "!") {
player.tail.push(createVector(player.tail[i].x, player.tail[i].y)) //--> BAD! INFINITE LOOP
player.dirs.push(createVector(0,0));
}
player.tail[i].x += player.dirs[i].x;
player.tail[i].y += player.dirs[i].y;
fill(fg);
let pos = getSpritePosition(
player.tail[i].y,
player.tail[i].x,
tileSize,
tileSize
);
rect(pos.dx, pos.dy, tileSize, tileSize);
}
// food
if (random() > 0.9) {
let _r = getRandomInt(1, rows - 2);
let _c = getRandomInt(1, cols - 2);
grid[_r][_c] = "!";
}
} else {
console.log("GAME OVER");
noLoop();
}
console.log(player.tail);
}