document.body.onkeydown = function( e ) {
var keys = {
37: 'left',
39: 'right',
40: 'down',
38: 'rotate',
32: 'drop'
};
if ( typeof keys[ e.keyCode ] != 'undefined' ) {
keyPress( keys[ e.keyCode ] );
render();
}
};
var canvas = document.getElementsByTagName( 'canvas' )[ 0 ];
var ctx = canvas.getContext( '2d' );
var W = 300, H = 600;
var BLOCK_W = W / COLS, BLOCK_H = H / ROWS;
// draw a single square at (x, y)
function drawBlock( x, y ) {
ctx.fillRect( BLOCK_W * x, BLOCK_H * y, BLOCK_W - 1 , BLOCK_H - 1 );
ctx.strokeRect( BLOCK_W * x, BLOCK_H * y, BLOCK_W - 1 , BLOCK_H - 1 );
}
// draws the board and the moving shape
function render() {
ctx.clearRect( 0, 0, W, H );
ctx.strokeStyle = 'black';
for ( var x = 0; x < COLS; ++x ) {
for ( var y = 0; y < ROWS; ++y ) {
if ( board[ y ][ x ] ) {
ctx.fillStyle = colors[ board[ y ][ x ] - 1 ];
drawBlock( x, y );
}
}
}
ctx.fillStyle = 'red';
ctx.strokeStyle = 'black';
for ( var y = 0; y < 4; ++y ) {
for ( var x = 0; x < 4; ++x ) {
if ( current[ y ][ x ] ) {
ctx.fillStyle = colors[ current[ y ][ x ] - 1 ];
drawBlock( currentX + x, currentY + y );
}
}
}
}
var COLS = 10, ROWS = 20;
var board = [];
var lose;
var interval;
var intervalRender;
var current; // current moving shape
var currentX, currentY; // position of current shape
var freezed; // is current shape settled on the board?
var shapes = [
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 0,
1 ],
[ 1, 1, 1, 0,
0, 0, 1 ],
[ 1, 1, 0, 0,
1, 1 ],
[ 1, 1, 0, 0,
0, 1, 1 ],
[ 0, 1, 1, 0,
1, 1 ],
[ 0, 1, 0, 0,
1, 1, 1 ]
];
var colors = [
'cyan', 'orange', 'blue', 'yellow', 'red', 'green', 'purple'
];
// creates a new 4x4 shape in global variable 'current'
// 4x4 so as to cover the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.