Skip to content

Instantly share code, notes, and snippets.

@mokevnin
Last active January 1, 2016 18:19
Show Gist options
  • Save mokevnin/8183391 to your computer and use it in GitHub Desktop.
Save mokevnin/8183391 to your computer and use it in GitHub Desktop.
var Game = React.createClass({
getInitialState: function() {
var numbers = _.shuffle(_.range(1, this.props.size * this.props.size));
var table = [];
var thumb_position = {};
for (var x = 0; x < this.props.size; x++) {
table[x] = [];
for (var y = 0; y < this.props.size; y++) {
if (x == this.props.size - 1 && y == this.props.size - 1) {
thumb_position = {"x": x, "y": y};
table[x][y] = "thumb";
} else {
var index = x * this.props.size + y;
table[x][y] = numbers[index];
}
}
}
return {"table": table, "thumb_position": thumb_position};
},
componentDidMount: function() {
key('up', this.handleMove);
key('down', this.handleMove);
key('left', this.handleMove);
key('right', this.handleMove);
},
render: function() {
return (
<div className="game">
<table>
{_.map(this.state.table, function(line) {
return (
<tr>
{_.map(line, function(value) {
return <td style={{"width": "50px"}} key={value}>{value}</td>;
})}
</tr>
);
})}
</table>
</div>
);
},
handleMove: function(event, handler) {
var thumb = this.state.thumb_position;
var table = this.state.table;
switch(handler.shortcut) {
case "down":
if (thumb["x"] > 0) {
table[thumb["x"]][thumb["y"]] = table[thumb["x"] - 1][thumb["y"]];
table[thumb["x"] - 1][thumb["y"]] = "thumb";
thumb["x"] -= 1;
}
break;
case "up":
if (thumb["x"] < this.props.size - 1) {
table[thumb["x"]][thumb["y"]] = table[thumb["x"] + 1][thumb["y"]];
table[thumb["x"] + 1][thumb["y"]] = "thumb";
thumb["x"] += 1;
}
break;
case "right":
if (thumb["y"] > 0) {
table[thumb["x"]][thumb["y"]] = table[thumb["x"]][thumb["y"] - 1];
table[thumb["x"]][thumb["y"] - 1] = "thumb";
thumb["y"] -= 1;
}
break;
case "left":
if (thumb["y"] < this.props.size - 1) {
table[thumb["x"]][thumb["y"]] = table[thumb["x"]][thumb["y"] + 1];
table[thumb["x"]][thumb["y"] + 1] = "thumb";
thumb["y"] += 1;
}
};
this.setState({"table": table, "thumb_position": thumb});
}
});
var game = Game({size: 4});
React.renderComponent(
game,
document.getElementById('games')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment