Skip to content

Instantly share code, notes, and snippets.

@rogerbraun
Created February 26, 2012 21:17
Show Gist options
  • Save rogerbraun/1919036 to your computer and use it in GitHub Desktop.
Save rogerbraun/1919036 to your computer and use it in GitHub Desktop.
Snaaaake
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Canvas</h1>
<p>
<button id="button">start</button>
<br />
<canvas id="canvas" width="640" height="480" ></canvas>
</p>
</body>
</html>
//200 x 200 Feld
gridWidth = 50;
//Kordinatien
var Pos = function(x,y){
this.x = x;
this.y = y;
};
var Block = function(canvas, pos, dir){
this.canvas = canvas;
this.pos = pos;
this.dir = dir;
this.width = this.canvas.width / gridWidth;
this.height = this.canvas.height / gridWidth;
this.draw = function(context){
context.fillStyle = "rgba(250, 0, 0, 1)"
context.beginPath();
context.rect(this.pos.x, this.pos.y, this.width, this.height);
context.fill();
};
this.move = function(new_direction){
switch(this.dir){
case "up":
this.pos = new Pos(this.pos.x, this.pos.y - this.height)
break;
case "down":
this.pos = new Pos(this.pos.x, this.pos.y + this.height)
break;
case "left":
this.pos = new Pos(this.pos.x - this.width, this.pos.y)
break;
default:
this.pos = new Pos(this.pos.x + this.width, this.pos.y)
break;
}
this.dir = new_direction;
}
};
var Snake = function(blocks){
this.blocks = blocks;
this.direction = "right";
this.changeDir= function(event){
switch(event.keyCode){
case 38:
this.direction = "up";
break;
case 40:
this.direction = "down";
break;
case 37:
this.direction = "left";
break;
case 39:
this.direction = "right";
break;
default:
return
break;
}
};
this.draw = function(canvas){
var context = canvas.getContext("2d");
context.clearRect(0,0,canvas.width,canvas.height);
for(var i = 0; i < this.blocks.length; i++){
this.blocks[i].draw(context);
}
};
this.move = function(){
var next_direction = this.direction;
for(var i = 0; i < this.blocks.length; i++){
var current_direction = this.blocks[i].dir;
this.blocks[i].move(next_direction);
next_direction = current_direction;
}
};
}
window.onload = function(){
var body = document.body;
var button = document.getElementById("button");
var canvas = document.getElementById("canvas");
var pos = new Pos(100, 100);
var head = new Block(canvas, pos, "right");
var s1 = new Block(canvas, new Pos(pos.x - head.width, pos.y), "right");
var s2 = new Block(canvas, new Pos(pos.x - head.width*2, pos.y), "right");
var s3 = new Block(canvas, new Pos(pos.x - head.width*3, pos.y), "right");
var snake = new Snake([head, s1, s2, s3]);
button.onclick = function() {
var m = function(){
snake.draw(canvas);
snake.move();
var keydown = false;
body.onkeydown = function(event){
snake.changeDir(event);
console.log(event);
};
}
window.setInterval(m, 1000 / 30)
}
}
canvas {
border-style: dotted;
border-width: 1px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment