JSFiddle - React, Tailwind, and code Playground
by julianjelfs
HTML
<html>
<body>
<div class="instructions">
<p>Use the arrow keys to controls the snake</p>
<br/>
<input id="start" type="button" value="Start"></input>
</div>
<div class="canvas">
</div>
</body>
</html>
CSS
body{
text-align:center;
font-family:helvetica;
}
input{
padding:5px;
}
div.instructions{
background-color:#eeeeee;
border:1 solid #000;
padding:40px;
text-align:center;
margin-top:200px;
position:absolute;
top:-20px;
left:70px;
}
div.canvas{
width:500px;
height:500px;
background-color:#cccccc;
}
div.vertebra{
width:10px;
height:10px;
background-color:#000000;
position:absolute;
}
#trace{
width:500px;
}
JavaScript
$(function() {
var up = 1,
down = 2,
left = 3,
right = 4,
direction = 4,
food;
var dimensions = {
top: 500,
left: 500
};
function snake(){
var vertTemplate = $("<div class='vertebra'/>");
function vertebra(s) {
var div = vertTemplate.clone().css({
top: 0,
left: 0
}).appendTo("body");
this.coords = {x: 0,y: 0};
this.previous = {top: 0,left: 0};
this.pos = {top: 0,left: 0};
this.div = div;
this.leading = null;
this.follow = function(vert) {
this.pos = div.position();
this.previous = {
top: this.pos.top,
left: this.pos.left
};
this.pos = vert.previous;
div.css({
top: this.pos.top,
left: this.pos.left
});
this.coords = {
y: this.pos.top / 10,
x: this.pos.left / 10
};
if (this.leading != null) {
this.leading.follow(this);
}
}
this.crashed = function(head) {
if (this != head && this.coords.y == head.coords.y && this.coords.x == head.coords.x) return true;
if (this.leading != null) {
return this.leading.crashed(head);
}
return false;
}
this.setPosition = function() {
this.pos = div.position();
this.previous = {
top: this.pos.top,
left: this.pos.left
};
if (direction === right) {
this.pos.left = this.pos.left + 10;
}
if (direction === left) {
...