xxxxxxxxxx
68
const E_PIECE = 0; // empty piece
const I_PIECE = 1;
const J_PIECE = 2;
const L_PIECE = 3;
const O_PIECE = 4;
const S_PIECE = 5;
const T_PIECE = 6;
const Z_PIECE = 7;
const PIECE_COLOURS = [
[0, 0, 0],
[0, 255, 255],
[0, 0, 255],
[255, 165, 0],
[255, 255, 0],
[0, 255, 0],
[128, 0, 128],
[255, 0, 0]
];
let boardW = 10, boardH = 20;
let grid = create2DArray(boardW, boardH);
function setup() {
createCanvas(1280, 720);
for (let i = 0; i < boardW; i++) {
for (let j = 0; j < boardH; j++) {
grid[i][j] = E_PIECE;
}
}
}
function draw() {
background(0);
push();
translate(width / 2, height / 2);
drawGrid(0, 0, height * 0.9);
pop();
}
function drawGrid(cx, cy, bh) {
let size = bh / boardH;
let bw = size * boardW;
let sx = cx - 0.5 * bw;
let sy = cy - 0.5 * bh;
push();
stroke(255);
strokeWeight(3);
noFill();
rect(sx, sy, bw, bh);
strokeWeight(1);
for (let i = 0; i < boardW; i++) {
for (let j = 0; j < boardH; j++) {
let piece = grid[i][j];
let colour = PIECE_COLOURS[piece];
fill(colour[0], colour[1], colour[2]);
square(sx + i * size, sy + j * size, size);
}
}
pop();
}
function create2DArray(w, h) {
let arr = new Array(w);
for (let i = 0; i < w; i++) arr[i] = new Array(h);
return arr;
}