January 25, 2013
HTML, JavaScript Snake v1.2
Because Retro is cool!Source:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Snake v1.2</title>
- <script type="text/javascript">
- /**
- * @author Manish Raj
- * @version 1.2
- * @website http://www.technoslab.in/
- */
- window.onload = function(){
- // Constants
- var KEY_UP = 38;
- var KEY_LEFT = 37;
- var KEY_DOWN = 40;
- var KEY_RIGHT = 39;
- var DIR_UP = 38;
- var DIR_LEFT = 37;
- var DIR_DOWN = 40;
- var DIR_RIGHT = 39;
- // Play ground width and height
- var ground_width = window.innerWidth;
- var ground_height = window.innerHeight;
- // Snake configurations
- var snake_width = 15;
- var snake_audio = new Audio("b.ogg");
- var snake_speed = 100;
- var snake_initial_length = 1;
- var snake_color = '#FFFFFF';
- var food_color = '#FFFFFF';
- var game_level = 0;
- var speed_increment = 10;
- var game_score = 0;
- var body = document.getElementsByTagName('body')[0];
- var set_style = function(element, styles){
- for (var key in styles){
- element.style[key] = styles[key];
- }
- }
- set_style(body, {
- 'padding' : '0px',
- 'margin' : '0px'
- });
- // Snake ground
- var snake_ground = document.createElement("div");
- set_style(snake_ground, {
- 'background' : '#000000',
- 'display' : 'block',
- 'width' : ground_width + 'px',
- 'height' : ground_height + 'px',
- 'margin' : '0px;',
- 'padding' : '0px',
- 'position' : 'relative',
- 'overflow' : 'hidden'
- });
- // Add snake ground
- body.appendChild(snake_ground);
- // Food block
- var food = document.createElement("div");
- var food_position = [0,0]
- var boundary = 50;
- var max1 = ground_width - boundary;
- var max2 = ground_height - boundary;
- var min1 = snake_width + boundary;
- var min2 = snake_width + boundary;
- var map_food_position = function(){
- food_position[0] = Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1;
- food_position[1] = Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2;
- }
- map_food_position();
- set_style(food, {
- 'background' : food_color,
- 'display' : 'block',
- 'width' : snake_width + 'px',
- 'height' : snake_width + 'px',
- 'position' : 'absolute',
- 'left' : food_position[0] + 'px',
- 'top' : food_position[1] + 'px',
- 'border' : '2px solid #000000'
- });
- // Add food block to ground
- snake_ground.appendChild(food);
- // Game stats
- var game_stat_right = document.createElement('div');
- set_style(game_stat_right, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'right' : '10px',
- 'top' : '10px',
- 'font' : 'bold 25px Arial',
- 'color' : '#FFFFFF'
- });
- var game_stat_left = document.createElement('div');
- set_style(game_stat_left, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'left' : '10px',
- 'top' : '10px',
- 'font' : 'bold 25px Arial',
- 'color' : '#FFFFFF'
- });
- // Add game stats to ground
- snake_ground.appendChild(game_stat_right);
- snake_ground.appendChild(game_stat_left);
- // Snake
- var snake = new Array();
- // Define first two blocks or elements of snake
- snake[0] = [Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1, Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2];
- for(var i = 1; i <= snake_initial_length; i++){
- snake[i] = [snake[0][0] - i * snake_width, snake[0][1]];
- }
- // Set initial direction to right
- var snake_direction = DIR_RIGHT;
- // Variable to track game position
- var game_over = false;
- // Loop for as long as needed
- var game_loop =
- function(){
- if(!game_over){
- move_snake({keyCode : snake_direction});
- window.setTimeout(game_loop, snake_speed - speed_increment * game_level);
- }else{
- var gameover_dialog = document.createElement("div");
- set_style(gameover_dialog, {
- 'display' : 'block',
- 'position' : 'absolute',
- 'width' : '400px',
- 'height' : '100px',
- 'font' : 'bold 25px Arial',
- 'color' : 'orangered',
- 'background' : '#DDDDDD',
- 'left' : '50%',
- 'top' : '50%',
- 'marginLeft' : '-200px',
- 'marginTop' : '-50px',
- 'z-index' : '99',
- 'textAlign' : 'center'
- });
- gameover_dialog.innerHTML = 'GAME OVER!';
- gameover_dialog_button = document.createElement('button');
- set_style(gameover_dialog_button, {
- 'display' : 'block',
- 'margin' : 'auto',
- 'font' : 'bold 15px Merienda',
- });
- gameover_dialog_button.innerHTML = 'Click To Play Again';
- gameover_dialog_button.onclick = function(){
- document.location.reload(false);
- }
- gameover_dialog.appendChild(gameover_dialog_button);
- body.appendChild(gameover_dialog);
- gameover_dialog_button.focus();
- }
- }
- window.setTimeout(game_loop, snake_speed);
- // Add keyDown event handler
- document.onkeydown = function(e){
- move_snake({keyCode : e.keyCode});
- };
- // Move snake according to direction
- var move_snake = function(e){
- // Ignore keyDown events if game is over
- if(game_over){
- return null;
- }
- // Prevent snake from moving in reverse direction
- if(snake_direction == DIR_UP && e.keyCode == KEY_DOWN){
- return null;
- }
- if(snake_direction == DIR_RIGHT && e.keyCode == KEY_LEFT){
- return null;
- }
- if(snake_direction == DIR_LEFT && e.keyCode == KEY_RIGHT){
- return null;
- }
- if(snake_direction == DIR_DOWN && e.keyCode == KEY_UP){
- return null;
- }
- // If one of the four navigation keys was pressed
- if(e.keyCode == KEY_UP || e.keyCode == KEY_LEFT || e.keyCode == KEY_DOWN || e.keyCode == KEY_RIGHT){
- // Store position of last block, will be used when adding new tail block i.e. when snake's head eats food block
- var last_x_position = snake[snake.length - 1][0];
- var last_y_position = snake[snake.length - 1][1];
- // Update every element to move to position of block ahead
- for(var i = snake.length - 1; i > 0 ; i--){
- snake[i][0] = snake[i-1][0];
- snake[i][1] = snake[i-1][1];
- }
- // If UP key was pressed ( basically released )
- if(e.keyCode == KEY_UP){
- snake[0][1] -= snake_width;
- snake_direction = DIR_UP;
- }
- // If LEFT key was pressed
- if(e.keyCode == KEY_LEFT){
- snake[0][0] -= snake_width;
- snake_direction = DIR_LEFT;
- }
- // If DOWN key was pressed
- if(e.keyCode == KEY_DOWN){
- snake[0][1] += snake_width;
- snake_direction = DIR_DOWN;
- }
- // If RIGHT key was pressed
- if(e.keyCode == KEY_RIGHT){
- snake[0][0] += snake_width;
- snake_direction = DIR_RIGHT;
- }
- // Wrap the snake at right egde
- if(snake[0][0] > ground_width){
- snake[0][0] = 0;
- }
- // Wrap the snake at bottom edge
- if(snake[0][1] > ground_height){
- snake[0][1] = 0;
- }
- // Wrap the snake at left edge
- if(snake[0][0] < 0){
- snake[0][0] = ground_width;
- }
- // Wrap the snake at top edge
- if(snake[0][1] < 0){
- snake[0][1] = ground_height;
- }
- for(var i = 1; i < snake.length; i++){
- if(snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]){
- game_over = true;
- }
- }
- }
- // If snake's head has approached a food block
- if(Math.abs(snake[0][0] - food_position[0]) < snake_width && Math.abs(snake[0][1] - food_position[1]) < snake_width){
- // Add a new tail block
- snake[snake.length] = [last_x_position, last_y_position];
- game_score++;
- if(game_score != 0 && game_score%10 == 0 && game_level != 10){
- game_level++;
- }
- // Play the audio
- snake_audio.play();
- // Find and update food block's new position
- map_food_position();
- set_style(food, {
- 'left' : food_position[0] + 'px',
- 'top' : food_position[1] + 'px'
- });
- }
- game_stat_left.innerHTML = 'Score: ' + game_score;
- game_stat_right.innerHTML = 'Level: ' + (game_level + 1);
- // Add or modify snake blocks on each event
- for(var i = 0; i < snake.length; i++){
- var snake_elem = document.getElementById("snake_"+i);
- if(snake_elem == null){
- snake_elem = document.createElement("div");
- snake_elem.setAttribute("id", "snake_"+i);
- set_style(snake_elem, {
- 'position' : 'absolute',
- 'display' : 'block',
- 'width' : snake_width + 'px',
- 'height' : snake_width + 'px',
- 'border' : '0px solid #000000',
- 'background' : snake_color
- });
- snake_ground.appendChild(snake_elem);
- }
- set_style(snake_elem, {
- 'left' : snake[i][0] + 'px',
- 'top' : snake[i][1] + 'px'
- });
- }
- };
- }
- </script>
- </head>
- <body>
- <noscript>
- <h1 style="text-align: center;">Please use a Javascript enabled web browser. Thank you.</h1>
- </noscript>
- </body>
- </html>
Download: http://pastebin.com/raw.php?i=gEdVMMJG
Demo: http://pastehtml.com/view/cqkp8hmf1.html
Related Posts
Subscribe to:
Post Comments (Atom)
nice 1...
ReplyDeleteenjoyed d game..
source download link?
ReplyDeleteAn impressive share! I have just forwarded this onto a colleague who was doing a little research
ReplyDeleteon this. And he in fact bought me dinner due to the fact that I discovered it for
him... lol. So allow me to reword this..
.. Thank YOU for the meal!! But yeah, thanx for spending time to talk about this matter here
on your blog. cellulite treatment
Review my web-site ... cellulite treatment
Unquestіοnably believe that which you said.
ReplyDeleteҮour favorite justifiсation ѕeеmeԁ
to be on the net the eaѕiest thing to be awaгe of.
I saу tо you, I ԁеfinitely get irked while pеoρle consider worries thаt
thеу ρlainly ԁo not know аbout.
Υou manаged to hit the nаil uρon thе top and alsο definеԁ out the whole thing without having side effect , pеoρle could take a signal.
Will pгobаbly be back to get mоrе.
Τhanks
My homepage loans for bad credit
Nice blog heгe! Also yοur wеb site loads
ReplyDeleteup fast! What wеb host are you uѕіng? Сan І get your affiliatе linκ to your host?
I wish mу websitе loadеd up as fast as youгs lol
Feel free to surf my homepage how to stop snoring
ReplyDeleteStοp by my web site - web site
Check out my webpage ... payday loan online
We abѕοlutely love yоur blog and finԁ
ReplyDeletealmοst all of уour рost's to be just what I'm lооkіng foг.
Dо yοu offer guest ωгiters to write contеnt fοг yοu ρeгsonally?
I wouldn't mind writing a post or elaborating on some of the subjects you write with regards to here. Again, awesome web site!
My web-site : 1 month loan
Simply want to say your article is as astounding. The clearness
ReplyDeletein your post is simply spectacular and i could assume you're knowledgeable on this subject. Well along with your permission allow me to snatch your RSS feed to keep up to date with drawing close post. Thanks 1,000,000 and please continue the enjoyable work.
Also visit my web-site I found it
Τhat іs very inteгestіng,
ReplyDeleteYou аre an exсesѕivelу profеѕsional blogger.
I've joined your rss feed and sit up for in the hunt for extra of your fantastic post. Additionally, I have shared your web site in my social networks
Here is my page: bucket truck
Μayhap this is pаrtially reѕponѕible for the aсhievеr that it's one of many TENS units useable on the marketplace, but the aurawave price is exclusively close to $150 in amount.
ReplyDeleteMy web page ... Daniel
Attractive section of content. I just stumbled upon your weblog and
ReplyDeletein accession capital to assert that I get in fact enjoyed account your blog posts.
Anyway I will be subscribing to your augment and even I achievement you access
consistently fast.
Stop by my web site; fast twitter followers
What a data of un-ambiguity and preserveness of precious know-how about unexpected feelings.
ReplyDeleteLook at my web-site: option fair
My web site > option fair