Skip to content

Instantly share code, notes, and snippets.

@mango314
Last active August 29, 2015 14:10
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 mango314/37986058e85b24048b5b to your computer and use it in GitHub Desktop.
Save mango314/37986058e85b24048b5b to your computer and use it in GitHub Desktop.
2048 clone - progress report
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<svg id="board" width=500 height=500></svg>
<script type="text/javascript">
N = 5;
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
d3.select("#board")
.append("rect")
.attr("x", 10 + 60*i)
.attr("y", 10 + 60*j)
.attr("width", 50)
.attr("height",50);
}
}
c = ["#E0E0E0" , "#000000"];
var X = Array(N);
for (i = 0; i < N; i++){
X[i] = Array(N);
for (j = 0; j < N; j++){
X[i][j] = '.';
}
}
X[Math.floor(N*Math.random())][Math.floor(N*Math.random())] = 'o';
function sq(){
// find empty square
empty = []
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
if (X[i][j]=='.'){
empty.push([i,j]);
}
}
}
if (empty.length > 0) {
return empty[Math.floor(empty.length*Math.random())];
}
else {
return null;
}
}
function fillSq(){
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
if(X[i][j] =='o'){
document.getElementsByTagName('rect')[N*j+i].style.fill = c[1];
}
else if (X[i][j]=='.'){
document.getElementsByTagName('rect')[N*j+i].style.fill = c[0];
}
}
}
}
function gravity(X, dir){
if(dir=="L"){
for (i = 0; i < N; i++){
zz = ""
for(j=0; j<N;j++){
zz += X[i][j]
}
zz = zz.replace(/\./g, "");
zz = zz + Array(N-zz.length+1).join(".");
for(j=0; j<N;j++){
X[i][j] = zz[j]
}
}
return X;
}
else if(dir=="R"){
for (i = 0; i < N; i++){
zz = ""
for(j=0; j<N;j++){
zz += X[i][j]
}
zz = zz.replace(/\./g, "");
zz = Array(N-zz.length+1).join(".") + zz;
for(j=0; j<N;j++){
X[i][j] = zz[j]
}
}
return X;
}
else if(dir=="U"){
for (i = 0; i < N; i++){
zz = ""
for(j=0; j<N;j++){
zz += X[j][i]
}
zz = zz.replace(/\./g, "");
zz = zz + Array(N-zz.length+1).join(".");
for(j=0; j<N;j++){
X[j][i] = zz[j]
}
}
return X;
}
else if(dir=="D"){
for (i = 0; i < N; i++){
zz = ""
for(j=0; j<N;j++){
zz += X[j][i]
}
zz = zz.replace(/\./g, "");
zz = Array(N-zz.length+1).join(".") + zz;
for(j=0; j<N;j++){
X[j][i] = zz[j]
}
}
return X;
}
}
fillSq();
document.onkeydown = checkKey;
function checkKey(e) {
z = sq();
if( z != null){
X[z[0]][z[1]]='o';
}
else console.log("GAME OVER");
e = e || window.event;
if (e.keyCode == '37') {
// left arrow
console.log("left");
X = gravity(X,'L');
}
else if (e.keyCode == '38') {
// up arrow
console.log("up");
X = gravity(X,'U');
}
else if (e.keyCode == '39') {
// right arrow
console.log("right");
X = gravity(X,'R');
}
else if (e.keyCode == '40') {
// down arrow
console.log("down");
X = gravity(X,'D');
}
fillSq();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment