JSFiddle - React, Tailwind, and code Playground
HTML
<body onkeydown="keydown(event)" onkeyup="keyup(event)">
<canvas id="canvas" width="160" height="352" style="border:1px solid #000000;"></canvas>
JavaScript
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
map = []; //1 is black = filled with piece
WIDTH = 10;
HEIGHT = 22;
for (var x=0;x<WIDTH;x++){
map[x]=[];
for (var y=0;y<HEIGHT;y++){
var v = y<HEIGHT/2 ? 0 : 1;
map[x][y]=v;
}
}
function drawworld(){
for (var x=0;x<WIDTH;x++){
for (var y=0;y<HEIGHT;y++){
var t = map[x][y];
ctx.fillStyle = t==1 ? "#000000" : "#FFFFFF";
ctx.fillRect(x*16,y*16,16,16);
}
}
}
pieces = [];
formats = [
[[1,1,1,1]],
[[1,0,0],
[1,1,1]],
[[0,0,1],
[1,1,1]],
[[1,1],
[1,1]],
[[0,1,1],
[1,1,0]],
[[0,1,0],
[1,1,1]],
[[1,1,0],
[0,1,1]]
];
function R(n) { return Math.floor(n*Math.random());}
function random(a,b) { return a+R(b-a+1); }
function newpos(x,y) { return {x:x,y:y};}
function newpiece(format,signal){
var piece = {format:copyformat(format),signal:signal,pos:newpos(random(0,WIDTH-format[0].length),(signal==1) ? 0 : HEIGHT-1)};
placepiece(piece);
pieces.push(piece);
return piece;
}
function copyformat(format){ //so pieces can be altered when a line is cleared
var f2 = [];
for (var y=0;y<format.length;y++){
f2[y]=[];
for (var x=0;x<format[0].length;x++){
var v = format[y][x];
f2[y][x]=v;
}
}
return f2;
}
function legal(pos) { return pos.x>=0 && pos.x<WIDTH && pos.y>=0 && pos.y<HEIGHT; }
function getpiecepositions(piece){
var piecepos = piece.pos;
var format = piece.format;
var positions = [];
for (var y=0;y<format.length;y++)
for (var x=0;x<format[0].length;x++){
var v = format[y][x];
if (v){
positions.push(newpos(piecepos.x+x,piecepos.y+y));
}
}
return positions;
}
var gameover=false;
function placepiece(piece){
var x = getpiecepositions(piece);
var clear = piece.signal==1?0:1;
var occupied = piece.signal;
var collision = false;
for (var k in x){
var pos = x[k];
if(map[pos.x][pos.y]==occupied){
collision=true; //tried to place piece but couldn't, game over?
break;
}
}
if...