Skip to content

Instantly share code, notes, and snippets.

@philippeantoine
Last active September 30, 2015 15:58
Show Gist options
  • Save philippeantoine/1821788 to your computer and use it in GitHub Desktop.
Save philippeantoine/1821788 to your computer and use it in GitHub Desktop.
Tetris
<!doctype html><html><head><meta charset="UTF-8"><title>Tetris</title></head>
<body><pre></pre><script>
var ttrs = { board: 0, block: 3, position: 32, offset: 0, layer: 0, speed: 1000, size: 32,
play: function(){
this.position += this.offset;
if ( this.bottom() || this.bang() ) {
this.position -= this.offset;
this.board = this.merge();
this.board = this.clear();
this.block = this.random();
this.position = this.size;
} else {
this.layer = this.merge();
}
this.render();
},
bottom: function(){ return this.position < 0 },
bang: function(){ return this.board & this.block << this.position },
merge: function(){ return this.board | this.block << this.position },
clear: function(){ return parseInt( this.board.toString( this.size ).replace(/v/,''), this.size ) },
random: function(){ return new Date%2?1:3 },
render: function(){
var txt = '', b = this.binary( this.layer );
for(var i=1; i<31;i++){
txt += b[i] == '1' ? '#' : '.';
if(i%5 == 0) txt+= '\n';
}
document.querySelector('pre').innerHTML = txt;
},
binary: function(l){ return ( 1<<30 | + l ).toString(2) },
loop: function(){ ttrs.play(); setTimeout(ttrs.loop, ttrs.speed) },
key: function(e){
switch (e.keyCode){
case 37: ttrs.offset = 1; break; //left
case 39: ttrs.offset = -1; break; //right
case 40: ttrs.offset = -5; break; //down
}
ttrs.play();
//ttrs.log();
},
log: function(){
console.log('layout : '+this.layout);
console.log('display : '+this.binary(this.layout));
console.log('offset : '+this.offset);
console.log('position: '+this.position);
}
};
onkeydown = ttrs.key;
ttrs.play();
</script><!--<script src="sunit.js"></script><script src="test.js"></script>-->
<!-- thanks to https://gist.github.com/1672254 -->
<style>*{font:14px monospace;}</style></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment