Last active
July 8, 2017 06:08
-
-
Save gujc71/eec87aff591628e03b737a0b53c2a723 to your computer and use it in GitHub Desktop.
Tetris
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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 by for | |
var canvas = document.getElementById('tetrisCanvas'); | |
var ctx = canvas.getContext('2d'); | |
var shapes = [ | |
[[0, 0, 0, 0], // 'O' | |
[0, 1, 1, 0], | |
[0, 1, 1, 0], | |
[0, 0, 0, 0]], | |
[[0, 0, 1, 0], // 'I' | |
[0, 0, 1, 0], | |
[0, 0, 1, 0], | |
[0, 0, 1, 0]], | |
[[0, 0, 0, 0], // 'T' | |
[1, 1, 1, 0], | |
[0, 1, 0, 0], | |
[0, 0, 0, 0]], | |
[[0, 0, 0, 0], // 'S' | |
[0, 0, 1, 1], | |
[0, 1, 1, 0], | |
[0, 0, 0, 0]], | |
[[0, 0, 0, 0], // 'Z' | |
[0, 1, 1, 0], | |
[0, 0, 1, 1], | |
[0, 0, 0, 0]], | |
[[0, 0, 1, 0], // 'J' | |
[0, 0, 1, 0], | |
[0, 1, 1, 0], | |
[0, 0, 0, 0]], | |
[[0, 1, 0, 0], // 'L' | |
[0, 1, 0, 0], | |
[0, 1, 1, 0], | |
[0, 0, 0, 0]] | |
]; | |
var curShape = shapes[0], curShapeType = 0;; | |
draw(); | |
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 rotateLeft(piece) { | |
var ret = []; | |
for (var y = 0; y < 4; y++) { | |
ret[y] = piece[y].slice(); | |
} | |
for (var y = 0; y < 4; y++) { | |
for (var x = 0; x < 4; x++) { | |
ret[y][x] = piece[x][3 - y]; | |
} | |
} | |
return ret; | |
} | |
function rotateRight(piece) { | |
var ret = []; | |
for (var y = 0; y < 4; y++) { | |
ret[y] = piece[y].slice(); | |
} | |
for (var y = 0; y < 4; y++) { | |
for (var x = 0; x < 4; x++) { | |
ret[y][x] = piece[3 - x][y]; | |
} | |
} | |
return ret; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment