Skip to content

Instantly share code, notes, and snippets.

@gujc71
Last active July 15, 2017 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gujc71/ceafd793c1a90c8a0c3cff9eedd0f7f1 to your computer and use it in GitHub Desktop.
Save gujc71/ceafd793c1a90c8a0c3cff9eedd0f7f1 to your computer and use it in GitHub Desktop.
Tetris
<canvas id="tetrisCanvas" width="200" height="400"></canvas>
<script>
// shapes are falling until game over
var canvas = document.getElementById('tetrisCanvas');
var ctx = canvas.getContext('2d');
var shapes = [
[ 0x4640, 0x0E40, 0x4C40, 0x4E00 ], // 'T'
[ 0x8C40, 0x6C00, 0x8C40, 0x6C00 ], // 'S'
[ 0x4C80, 0xC600, 0x4C80, 0xC600 ], // 'Z'
[ 0x4444, 0x0F00, 0x4444, 0x0F00 ], // 'I'
[ 0x44C0, 0x8E00, 0xC880, 0xE200 ], // 'J'
[ 0x88C0, 0xE800, 0xC440, 0x2E00 ], // 'L'
[ 0xCC00, 0xCC00, 0xCC00, 0xCC00 ] // 'O'
];
var curShapeType = 0, curRotation = 0, curShape = shapes[curShapeType][curRotation];
var sPos = {x:0, y:0};
var gamePanel = [];
for (var y = 0; y < 20; y++) {
gamePanel[y] = [];
for (var x = 0; x < 10; x++) {
gamePanel[y][x] = 0;
}
}
var intervalHandler = setInterval(playingTetris, 400);
function playingTetris() {
if ( intersects(sPos.y + 1, sPos.x)) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if ((curShape & (0x8000 >> (i * 4 + j))) && gamePanel[sPos.y+i]) {
gamePanel[sPos.y+i][sPos.x+j] = 1;
}
curShape = getNextShape();
sPos = {x:0, y:0};
if ( intersects(sPos.y, sPos.x)) {
clearInterval(intervalHandler);
alert("Game Over");
}
} else {
sPos.y++;
}
draw();
}
function intersects(y, x) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (curShape & (0x8000 >> (i * 4 + j)))
if (y+i >= 20 || x+j < 0 || x+j >= 10 || gamePanel[y+i][x+j])
return true;
return false;
}
function draw() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 200, 400);
ctx.rect(0, 0, 200, 400);
ctx.strokeStyle="blue";
ctx.stroke();
ctx.fillStyle = 'black';
for (var y = 0; y < gamePanel.length; y++) {
for (var x = 0; x < gamePanel[y].length; x++) {
if (gamePanel[y][x]) {
ctx.fillRect(x * 20, y * 20, 19, 19);
}
}
}
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 4; x++) {
if (curShape & (0x8000 >> (y * 4 + x))) {
ctx.fillRect((sPos.x+x) * 20, (sPos.y+y) * 20, 19, 19);
}
}
}
}
function getNextShape() {
curShapeType = (curShapeType + 1) % 7;
curRotation = 0;
return shapes[curShapeType][curRotation]
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment