simple snake game AKA nibbles using d3.js
demo of snake game using d3.js
by Atul
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<h2>
Simple snake game using D3js - by Atul
</h2>
<div id="mainDiv" style="width:800px; height:500px">
<div id="drawAreaOuter" style="width:100%; height:100%; float:left; ">
<div id="menuTop" >
<a id="startStop" style="font-size:x-large" href="javascript:StartStopGame()" >Start</a>
</div>
<div id="drawArea" style="width:100%; height:100%; border:1px solid gray">
</div>
</div>
</div>
JavaScript
// nibble object - multiple snakes can be created by instantiating new objects
function Nibble(svg, x, y, id, color) {
this.startX = x;
this.startY = y;
this.color = color;
this.width = 12;
this.height = 12;
this.svg = svg;
this.id = id;
this.headBoxId = 1;
this.tailBoxId = 1;
this.skipCount = 0;
this.direction = 'right';
this.prizeLocation = null;
var thisobj = this;
this.SetPrizeLocation = function (pt) {
this.prizeLocation = pt;
}
this.Draw = function () {
svg.append("rect")
.attr("id", thisobj.id + "_" + thisobj.headBoxId)
.attr("x", thisobj.startX)
.attr("y", thisobj.startY)
.attr("height", thisobj.height)
.attr("width", thisobj.width)
.style("fill", function () {
if (typeof (thisobj.color) == 'undefined')
return "red";
else
return thisobj.color;
})
.style("stroke", function() {
if (typeof (thisobj.color) == 'undefined')
return "red";
else
return thisobj.color;
})
;
}
this.SetSkip = function (skip) {
thisobj.skipCount = skip;
}
this.SetDirection = function (direction) {
thisobj.direction = direction;
}
this.Move = function () {
var direction = thisobj.direction;
thisobj.headBoxId++;
if (direction.toLowerCase() == 'right') {
thisobj.startX += thisobj.width;
if (parseInt(svg.attr('width')) <= thisobj.startX) {
thisobj.startX = 0;
}
...