xxxxxxxxxx
79
let grid;
let w = 20;
let current;
function setup() {
createCanvas(400, 800);
grid = make2DArray(10, 20);
current = new Piece();
}
function draw() {
background(220);
current.show();
current.update();
drawGrid();
}
function drawGrid() {
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 20; j++) {
if (grid[i][j] != 0) {
fill(255, 0, 0);
rect(i * w, j * w, w, w);
}
}
}
}
function make2DArray(cols, rows) {
let arr = new Array(cols);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(rows);
for (let j = 0; j < arr[i].length; j++) {
arr[i][j] = 0;
}
}
return arr;
}
class Piece {
constructor() {
this.x = 5;
this.y = 0;
this.speed = 1;
}
show() {
fill(255);
rect(this.x * w, this.y * w, w, w);
}
update() {
if (frameCount % this.speed == 0) {
if (this.y < height / w - 1 && grid[this.x][this.y + 1] == 0) {
this.y++;
} else {
grid[this.x][this.y] = 1;
current = new Piece();
}
}
}
move(dir) {
if (dir === 'LEFT' && this.x > 0 && grid[this.x - 1][this.y] === 0) {
this.x--;
} else if (dir === 'RIGHT' && this.x < width / w - 1 && grid[this.x + 1][this.y] === 0) {
this.x++;
}
}
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
current.move('LEFT');
} else if (keyCode === RIGHT_ARROW) {
current.move('RIGHT');
}
}