Ajax Loader
HTML
<canvas id="canvas"></canvas>
1
<canvas id="canvas"></canvas>
2
 
3
<div id="reMenu">
4
  <h1 id="snake2">Snake</h1>
5
  <p id="info2">Game Over</p>
6
  <a href="javascript: void(0)" id="restart" onclick="reset()" >Restart</a>   
7
  <a href="#" id="tweet" target="_blank" rel="nofollow">Tweet My Score</a> 
8
</div>
9
 
10
<div id="menu">
11
  <h1 id="snake">Snake</h1>
12
  <p id="info">by <a target="_blank" rel="nofollow" href="http://twitter.com/SolitaryDesigns">Kushagra Agarwal</a></p>
13
  <a href="javascript: void(0)" id="start" onclick="init()" >Start</a>
14
  <p id="loading">Loading...</p>
15
</div>
16
 
17
<p id="score">Score: 0</p>
18
 
19
<!-- Audio -->
20
<audio id="main_music" loop>
21
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/main.mp3" type="audio/mp3" />
22
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/main.ogg" type="audio/ogg"/>
23
</audio>
24
 
25
<audio id="gameOver">
26
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/go.mp3" type="audio/mp3" />
27
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/go.ogg" type="audio/ogg"/>
28
</audio>
29
 
30
<audio id="food">
31
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/food.mp3" type="audio/mp3" />
32
  <source src="http://dl.dropbox.com/u/26141789/canvas/snake/food.ogg" type="audio/ogg"/>
33
</audio>
 
CSS
@import url("http://fonts.googleapis.com/css?family=Press+Start+2P");
1
@import url("http://fonts.googleapis.com/css?family=Press+Start+2P");
2
 
3
body {padding: 0; margin: 0; overflow: hidden;}
4
#canvas {background: black;}
5
 
6
#menu, #reMenu {
7
  position: absolute;
8
  z-index: 1;
9
  top: 0;
10
  left: 0;
11
  width: 100%;
12
  height: 100%;
13
  background: black;
14
}
15
 
16
#reMenu {background: transparent;}
17
 
18
h1, p, a {
19
  position: relative;  
20
  z-index: 1; 
21
  font: 72px "Press Start 2P", cursive;
22
  color: white;
23
  text-align: center;
24
  margin: 0;
25
}
26
 
27
a{
28
  font-size : 16px; 
29
  margin: 0;
30
  display: inline-block;
31
  position: relative;
32
  left: 0;
33
}
34
 
35
h1 {margin-top: 5%;}
36
 
37
p {
38
  font-size: 16px;
39
  margin-top: 10px;
40
  padding-left: 200px;
41
}
42
 
43
a#start, a#restart, a#tweet, p#loading {
44
  font-size: 24px;
45
  display: block;
46
  width: 120px;
47
  top: 30%; 
48
  left: 0; 
49
  border-top: 5px solid white;
50
  border-bottom: 5px solid white;
51
  padding: 10px;
52
  text-decoration: none;
53
  margin: 0 auto; 
54
}
55
 
56
a#restart {width: 165px; top: 20%}
57
 
58
a#tweet {top: 25%; width: 342px;}
59
 
60
#score {
61
  bottom: 10px;
62
  position: absolute;
63
  z-index: 1;
64
  padding-left: 10px;
65
  font-size: 16px;
66
}
67
 
68
p#loading {
69
  border: none;
70
  font-size: 16px;
71
  top: 20%;
72
  width: 200px;
73
}
74
 
75
a#start{top: 100%;}
76
 
77
#info2 {padding : 0;}
 
JavaScript
//Preloading audio stuff
1
//Preloading audio stuff
2
var mainMusic = document.getElementById("main_music"),
3
    foodMusic = document.getElementById("food"), 
4
    goMusic = document.getElementById("gameOver");
5
 
6
var files = [mainMusic, foodMusic, goMusic];
7
var counter = 0;
8
 
9
var start = document.getElementById("start"),
10
    loading = document.getElementById("loading");
11
 
12
for(var i = 0; i < files.length; i++) {
13
  var file = files[i];
14
  file.addEventListener("loadeddata", function() {
15
    counter++;
16
    var percent = Math.floor((counter/files.length)*100);
17
    loading.innerHTML = "Loading " + percent + "%";
18
    if(percent == 100) showButton();
19
  });
20
}
21
 
22
function showButton() {
23
  start.style.top = "30%";
24
  loading.style.top = "100%";
25
}
26
 
27
//Initializing Canvas
28
var canvas = document.getElementById("canvas"),
29
    ctx = canvas.getContext("2d"),
30
    
31
    //Full width and height
32
    w = window.innerWidth,
33
    h = window.innerHeight;
34
  
35
canvas.height = h;
36
canvas.width = w;
37
 
38
var reset, scoreText,menu, reMenu, score = 0;
39
 
40
function init() {
41
  mainMusic.play();
42
  menu.style.zIndex = "-1";
43
  
44
  var snake,
45
      size = 10,
46
      speed = 25,
47
      dir,
48
      game_loop,
49
      over = 0,
50
      hitType;
51
  
52
  //Custom funny gameover messages
53
  var msgsSelf = [];
54
  msgsSelf[0] = "There's plenty of food. Don't eat yourself!";
55
  msgsSelf[1] = "Is your body tastier than the food?";
56
  msgsSelf[2] = "AArrgghhh!! I bit myself!!"; 
57
  msgsSelf[3] = "Do you have Autophagia?";  
58
  
59
  var msgsWall = [];
60
  msgsWall[0] = "You broke your head!";
61
  msgsWall[1] = "The wall is stronger than it seems!";
62
  msgsWall[2] = "There's no way to escape the game...";
63
  msgsWall[3] = "LOOK MA! NO HEAD..!!";
64
  msgsWall[4] = "Can't see the wall? Huh?";
65
  
66
  function paintCanvas() {
67
    ctx.fillStyle = "black";
68
    ctx.fillRect(0, 0, w, h);
69
  }
70
  
71
  var Food = function(){
72
    this.x = Math.round(Math.random() * (w - size) / size);
73
    this.y = Math.round(Math.random() * (h - size) / size);
74
    
75
    this.draw = function() {
76
      ctx.fillStyle = "white";
77
      ctx.fillRect(this.x*size, this.y*size, size, size);
78
    }
79
  }
80
      
81
      var f = new Food();
82
  
83
  //Initialize the snake
84
  function initSnake() {
85
    var length = 10;
86
    snake = [];
87
    for(var i = length - 1; i >= 0; i--) {
88
      snake.push({x: i, y: 0});
89
    }
90
  }
91
  
92
  function paintSnake() {
93
    for(var i = 0; i < snake.length; i++) {
94
      var s = snake[i];
95
      
96
      ctx.fillStyle = "white";
97
      ctx.fillRect(s.x*size, s.y*size, size, size);
98
    }
99
  }
100
  
101
  function updateSnake() {
102
    //Update the position of the snake
103
    var head_x = snake[0].x;
104
    var head_y = snake[0].y;
105
    
106
    //Get the directions
107
    document.onkeydown = function(e) {
108
      var key = e.keyCode;
109
      //console.log(key);
110
      
111
      if(key == 37 && dir != "right") setTimeout(function() {dir = "left"; }, 30);
112
      else if(key == 38 && dir != "down") setTimeout(function() {dir = "up"; }, 30);
113
      else if(key == 39 && dir != "left") setTimeout(function() {dir = "right"; }, 30);
114
      else if(key == 40 && dir != "up") setTimeout(function() {dir = "down"; }, 30);
115
 
116
      if(key) e.preventDefault();
117
 
118
    }
119
      
120
      //Directions
121
      if(dir == "right") head_x++;
122
    else if(dir == "left") head_x--;
123
    else if(dir == "up") head_y--;
124
    else if(dir == "down") head_y++;
125
    
126
    //Move snake
127
    var tail = snake.pop();
128
    tail.x = head_x;
129
    tail.y = head_y;
130
    snake.unshift(tail);
131
     
132
    //Wall Collision
133
    if(head_x >= w/size || head_x <= -1 || head_y >= h/size || head_y <= -1) {          
134
      if(over == 0) {
135
        hitType = "wall";
136
        gameover();
137
      }
138
      over++
139
    }
140
    
141
    //Food collision
142
    if(head_x == f.x && head_y == f.y) {
143
      coll = 1;
144
      f = new Food();
145
      var tail = {x: head_x, y:head_y};
146
      snake.unshift(tail);  
147
      score += 10;
148
      scoreText.innerHTML = "Score: "+score;
149
      foodMusic.pause();
150
      foodMusic.currentTime = 0;
151
      foodMusic.play();
152
      
153
      //Increase speed
154
      if(speed <= 45) speed ++;
155
      clearInterval(game_loop);
156
      game_loop = setInterval(draw, 1000/speed);
157
    }
158
    
159
    else {
160
      //Check collision between snake parts
161
      for(var j = 1; j < snake.length; j++) {
162
        var s = snake[j];
163
        if(head_x == s.x && head_y == s.y) {
164
          if(over == 0) {
165
            hitType = "self";
166
            gameover(); 
167
          }
168
          over++;
169
        }
170
      } 
171
    }
172
  }
173
  
174
  function draw() {
175
    paintCanvas();
176
    paintSnake();
177
    updateSnake();
178
    
179
    //Draw food
180
    f.draw();
181
  }
182
  
183
  reset = function() {
184
    initSnake();
185
    f = new Food();
186
    reMenu.style.zIndex = "-1"
187
    dir = "right";
188
    over = 0;
189
    speed = 30;
190
    if(typeof game_loop != "undefined")  clearInterval(game_loop); 
191
    game_loop = setInterval(draw, 1000/speed);
192
    
193
 
194
    score = 0;
195
    scoreText.innerHTML = "Score: "+score;
196
    mainMusic.currentTime = 0;
197
    mainMusic.play();
198
    
199
    return;
200
  }
201
    
202
    function gameover() {
203
      clearInterval(game_loop);
204
      mainMusic.pause();
205
      goMusic.play();
206
      
207
      var tweet = document.getElementById("tweet");
208
      tweet.href='http://twitter.com/share?url=http://bit.ly/SnakeHTML5&text=I scored ' +score+ ' points in the classic HTML5 Snake game&count=horiztonal&via=cssdeck';
209
      
210
      //Get the gameover text
211
      var goText = document.getElementById("info2");
212
      
213
      //Show the messages
214
      if(hitType == "wall") {
215
        goText.innerHTML = msgsWall[Math.floor(Math.random() * msgsWall.length)];
216
      }
217
      else if(hitType == "self") {
218
        goText.innerHTML = msgsSelf[Math.floor(Math.random() * msgsSelf.length)];
219
      }
220
      
221
      reMenu.style.zIndex = "1";
222
    }
223
  
224
  reset();
225
}
226
 
227
//Menus
228
function startMenu() {
229
  menu = document.getElementById("menu");
230
  reMenu = document.getElementById("reMenu");
231
  
232
  scoreText = document.getElementById("score");
233
  reMenu.style.zIndex = "-1"
234
}
235
 
236
startMenu();
 

Classic Snake Game with HTML5 Canvas

CSSDeck G+