Skip to content

Instantly share code, notes, and snippets.

@gujc71
Last active July 3, 2017 05:54
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/7aaf3729416810e94920d5f833b1e412 to your computer and use it in GitHub Desktop.
Save gujc71/7aaf3729416810e94920d5f833b1e412 to your computer and use it in GitHub Desktop.
Tetris
<canvas id="tetrisCanvas" width="100" height="100"></canvas>
<button onclick="leftBtnClick()">Rotate Left</button>
<button onclick="rightBtnClick()">Rotate Right</button>
<button onclick="getNextShape()">Next shape</button>
<script>
// rotate shape with proper size
var canvas = document.getElementById('tetrisCanvas');
var ctx = canvas.getContext('2d');
var shapes = [
[[1, 1, 0, 0], // 'O'
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 1, 0], // 'I'
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]],
[[1, 1, 1, 0], // 'T'
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 1, 1, 0], // 'S'
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[1, 1, 0, 0], // 'Z'
[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 1, 0, 0], // 'J'
[0, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]],
[[1, 0, 0, 0], // 'L'
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]]
];
var shapeSize = [2,4,3,3,3,3,3];
var curShape = shapes[0], curShapeType = 0;;
draw(curShape);
function draw() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 100, 100);
ctx.fillStyle = 'black';
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 4; x++) {
if (curShape[y][x]) {
ctx.fillRect(x * 20, y * 20, 19, 19);
}
}
}
}
function getNextShape() {
curShapeType = (curShapeType + 1) % 7;
curShape = shapes[curShapeType]
draw();
}
function leftBtnClick() {
curShape = rotateLeft(curShape);
draw();
}
function rightBtnClick() {
curShape = rotateRight(curShape);
draw();
}
function initArray(piece) {
var ret = [];
for (var y = 0; y < 4; y++) {
ret[y] = piece[y].slice();
}
return ret;
}
function rotateLeft(piece) {
var ret = initArray(piece);
var size = shapeSize[curShapeType];
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
ret[y][x] = piece[x][(size-1) - y];
}
}
return ret;
}
function rotateRight(piece) {
var ret = initArray(piece);
var size = shapeSize[curShapeType];
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
ret[y][x] = piece[(size-1) - x][y];
}
}
return ret;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment