JSFiddle - React, Tailwind, and code Playground
by ilyautkin
HTML
<div id="tetris">
<span id="start-btn">START</span>
</div>
CSS
#tetris {
display: inline-block;
width: 264px;
height: 440px;
border: 2px solid #000;
line-height: 0px;
background: #000;
}
#tetris b, #tetris i {
display: inline-block;
width: 20px;
height: 20px;
background: #000;
border: 1px solid #333;
}
#tetris i {
background: #fff;
border-color: #999;
}
#start-btn {
display: block;
width: 30%;
margin: 70% auto 0;
padding: 20px;
background: #eee;
text-align: center;
cursor: pointer;
}
#start-btn:hover {
background: #fff;
}
JavaScript
var Tetris = {
config: {
pitchID: "tetris",
freeBrick: "<b></b>",
filledBrick: "<i></i>",
figureTypes: {
I: function() {
return [
[[-3,5]],
[[-2,5]],
[[-1,5]],
[[ 0,5]]
];
},
J: function() {
return [
[[-2,6]],
[[-1,6]],
[[0,5],[0,6]]
];
},
L: function() {
return [
[[-2,5]],
[[-1,5]],
[[0,5],[0,6]]
];
},
O: function() {
return [
[[-1,5],[-1,6]],
[[ 0,5], [0,6]]
];
},
S: function() {
return [
[[-1,6],[-1,7]],
[[0,5], [0,6]]
];
},
T: function() {
return [
[[-1,5],[-1,6],[-1,7]],
[[0,6]]
];
},
Z: function() {
return [
[[-1,4],[-1,5]],
[[0,5], [0,6]]
];
}
}
},
startBtn: document.getElementById('start-btn'),
pitch: {
width: 12,
height: 20,
bricks: [],
getDom: function() {
return document.getElementById(Tetris.config.pitchID);
}
},
figure: {
coords: [],
go: function() {
if (this.coords.length == 0) {
this.create();
} else {
this.process();
}
},
create: function() {
this.coords = this.getRandomFigure();
},
getRandomFigure: function() {
var keys = Object.keys(Tetris.config.figureTypes);
var randKey = Math.floor(Math.random() * keys.length);
return Tetris.config.figureTypes[keys[randKey]]();
},
process: function() {
if (this.touched()) {
this.joinToBricks();
if (!Tetris.checkGameOver()) {
this.destroy();
}
} else {
this.makeStep();
}
},
touched: function() {
var contact = false;
Tetris.each(this.coords, function(i,j){
var figureRow =...