January 25, 2013

HTML, JavaScript Snake v1.2

Because Retro is cool!

Source:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Snake v1.2</title>
  5. <script type="text/javascript">
  6.  
  7. /**
  8. * @author Manish Raj
  9. * @version 1.2
  10. * @website http://www.technoslab.in/
  11. */
  12.  
  13. window.onload = function(){
  14.  
  15. // Constants
  16. var KEY_UP = 38;
  17. var KEY_LEFT = 37;
  18. var KEY_DOWN = 40;
  19. var KEY_RIGHT = 39;
  20. var DIR_UP = 38;
  21. var DIR_LEFT = 37;
  22. var DIR_DOWN = 40;
  23. var DIR_RIGHT = 39;
  24.  
  25. // Play ground width and height
  26. var ground_width = window.innerWidth;
  27. var ground_height = window.innerHeight;
  28.  
  29. // Snake configurations
  30. var snake_width = 15;
  31. var snake_audio = new Audio("b.ogg");
  32. var snake_speed = 100;
  33. var snake_initial_length = 1;
  34. var snake_color = '#FFFFFF';
  35. var food_color = '#FFFFFF';
  36.  
  37. var game_level = 0;
  38. var speed_increment = 10;
  39. var game_score = 0;
  40.  
  41. var body = document.getElementsByTagName('body')[0];
  42.  
  43. var set_style = function(element, styles){
  44. for (var key in styles){
  45. element.style[key] = styles[key];
  46. }
  47. }
  48.  
  49. set_style(body, {
  50. 'padding' : '0px',
  51. 'margin' : '0px'
  52. });
  53.  
  54. // Snake ground
  55. var snake_ground = document.createElement("div");
  56. set_style(snake_ground, {
  57. 'background' : '#000000',
  58. 'display' : 'block',
  59. 'width' : ground_width + 'px',
  60. 'height' : ground_height + 'px',
  61. 'margin' : '0px;',
  62. 'padding' : '0px',
  63. 'position' : 'relative',
  64. 'overflow' : 'hidden'
  65. });
  66.  
  67. // Add snake ground
  68. body.appendChild(snake_ground);
  69.  
  70. // Food block
  71. var food = document.createElement("div");
  72.  
  73. var food_position = [0,0]
  74.  
  75. var boundary = 50;
  76. var max1 = ground_width - boundary;
  77. var max2 = ground_height - boundary;
  78. var min1 = snake_width + boundary;
  79. var min2 = snake_width + boundary;
  80.  
  81. var map_food_position = function(){
  82. food_position[0] = Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1;
  83. food_position[1] = Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2;
  84. }
  85.  
  86. map_food_position();
  87. set_style(food, {
  88. 'background' : food_color,
  89. 'display' : 'block',
  90. 'width' : snake_width + 'px',
  91. 'height' : snake_width + 'px',
  92. 'position' : 'absolute',
  93. 'left' : food_position[0] + 'px',
  94. 'top' : food_position[1] + 'px',
  95. 'border' : '2px solid #000000'
  96. });
  97.  
  98. // Add food block to ground
  99. snake_ground.appendChild(food);
  100.  
  101. // Game stats
  102. var game_stat_right = document.createElement('div');
  103. set_style(game_stat_right, {
  104. 'display' : 'block',
  105. 'position' : 'absolute',
  106. 'right' : '10px',
  107. 'top' : '10px',
  108. 'font' : 'bold 25px Arial',
  109. 'color' : '#FFFFFF'
  110. });
  111.  
  112. var game_stat_left = document.createElement('div');
  113. set_style(game_stat_left, {
  114. 'display' : 'block',
  115. 'position' : 'absolute',
  116. 'left' : '10px',
  117. 'top' : '10px',
  118. 'font' : 'bold 25px Arial',
  119. 'color' : '#FFFFFF'
  120. });
  121.  
  122. // Add game stats to ground
  123. snake_ground.appendChild(game_stat_right);
  124. snake_ground.appendChild(game_stat_left);
  125.  
  126.  
  127. // Snake
  128. var snake = new Array();
  129.  
  130. // Define first two blocks or elements of snake
  131. snake[0] = [Math.floor((Math.random() * (max1 - min1) + min1)/min1) * min1, Math.floor((Math.random() * (max2 - min2) + min2)/min2) * min2];
  132. for(var i = 1; i <= snake_initial_length; i++){
  133. snake[i] = [snake[0][0] - i * snake_width, snake[0][1]];
  134. }
  135.  
  136. // Set initial direction to right
  137. var snake_direction = DIR_RIGHT;
  138.  
  139. // Variable to track game position
  140. var game_over = false;
  141.  
  142. // Loop for as long as needed
  143. var game_loop =
  144. function(){
  145. if(!game_over){
  146.  
  147. move_snake({keyCode : snake_direction});
  148. window.setTimeout(game_loop, snake_speed - speed_increment * game_level);
  149. }else{
  150. var gameover_dialog = document.createElement("div");
  151. set_style(gameover_dialog, {
  152. 'display' : 'block',
  153. 'position' : 'absolute',
  154. 'width' : '400px',
  155. 'height' : '100px',
  156. 'font' : 'bold 25px Arial',
  157. 'color' : 'orangered',
  158. 'background' : '#DDDDDD',
  159. 'left' : '50%',
  160. 'top' : '50%',
  161. 'marginLeft' : '-200px',
  162. 'marginTop' : '-50px',
  163. 'z-index' : '99',
  164. 'textAlign' : 'center'
  165. });
  166. gameover_dialog.innerHTML = 'GAME OVER!';
  167. gameover_dialog_button = document.createElement('button');
  168. set_style(gameover_dialog_button, {
  169. 'display' : 'block',
  170. 'margin' : 'auto',
  171. 'font' : 'bold 15px Merienda',
  172. });
  173. gameover_dialog_button.innerHTML = 'Click To Play Again';
  174. gameover_dialog_button.onclick = function(){
  175. document.location.reload(false);
  176. }
  177. gameover_dialog.appendChild(gameover_dialog_button);
  178. body.appendChild(gameover_dialog);
  179. gameover_dialog_button.focus();
  180. }
  181. }
  182.  
  183. window.setTimeout(game_loop, snake_speed);
  184.  
  185.  
  186. // Add keyDown event handler
  187. document.onkeydown = function(e){
  188. move_snake({keyCode : e.keyCode});
  189. };
  190.  
  191. // Move snake according to direction
  192. var move_snake = function(e){
  193.  
  194. // Ignore keyDown events if game is over
  195. if(game_over){
  196. return null;
  197. }
  198.  
  199. // Prevent snake from moving in reverse direction
  200. if(snake_direction == DIR_UP && e.keyCode == KEY_DOWN){
  201. return null;
  202. }
  203.  
  204. if(snake_direction == DIR_RIGHT && e.keyCode == KEY_LEFT){
  205. return null;
  206. }
  207.  
  208. if(snake_direction == DIR_LEFT && e.keyCode == KEY_RIGHT){
  209. return null;
  210. }
  211.  
  212. if(snake_direction == DIR_DOWN && e.keyCode == KEY_UP){
  213. return null;
  214. }
  215.  
  216. // If one of the four navigation keys was pressed
  217. if(e.keyCode == KEY_UP || e.keyCode == KEY_LEFT || e.keyCode == KEY_DOWN || e.keyCode == KEY_RIGHT){
  218.  
  219. // Store position of last block, will be used when adding new tail block i.e. when snake's head eats food block
  220. var last_x_position = snake[snake.length - 1][0];
  221. var last_y_position = snake[snake.length - 1][1];
  222.  
  223. // Update every element to move to position of block ahead
  224. for(var i = snake.length - 1; i > 0 ; i--){
  225. snake[i][0] = snake[i-1][0];
  226. snake[i][1] = snake[i-1][1];
  227. }
  228.  
  229. // If UP key was pressed ( basically released )
  230. if(e.keyCode == KEY_UP){
  231. snake[0][1] -= snake_width;
  232. snake_direction = DIR_UP;
  233. }
  234.  
  235. // If LEFT key was pressed
  236. if(e.keyCode == KEY_LEFT){
  237. snake[0][0] -= snake_width;
  238. snake_direction = DIR_LEFT;
  239. }
  240.  
  241. // If DOWN key was pressed
  242. if(e.keyCode == KEY_DOWN){
  243. snake[0][1] += snake_width;
  244. snake_direction = DIR_DOWN;
  245. }
  246.  
  247. // If RIGHT key was pressed
  248. if(e.keyCode == KEY_RIGHT){
  249. snake[0][0] += snake_width;
  250. snake_direction = DIR_RIGHT;
  251. }
  252.  
  253. // Wrap the snake at right egde
  254. if(snake[0][0] > ground_width){
  255. snake[0][0] = 0;
  256. }
  257.  
  258. // Wrap the snake at bottom edge
  259. if(snake[0][1] > ground_height){
  260. snake[0][1] = 0;
  261. }
  262.  
  263. // Wrap the snake at left edge
  264. if(snake[0][0] < 0){
  265. snake[0][0] = ground_width;
  266. }
  267.  
  268. // Wrap the snake at top edge
  269. if(snake[0][1] < 0){
  270. snake[0][1] = ground_height;
  271. }
  272.  
  273. for(var i = 1; i < snake.length; i++){
  274. if(snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]){
  275. game_over = true;
  276. }
  277. }
  278.  
  279. }
  280.  
  281. // If snake's head has approached a food block
  282. if(Math.abs(snake[0][0] - food_position[0]) < snake_width && Math.abs(snake[0][1] - food_position[1]) < snake_width){
  283.  
  284. // Add a new tail block
  285. snake[snake.length] = [last_x_position, last_y_position];
  286.  
  287. game_score++;
  288. if(game_score != 0 && game_score%10 == 0 && game_level != 10){
  289. game_level++;
  290. }
  291.  
  292. // Play the audio
  293. snake_audio.play();
  294.  
  295. // Find and update food block's new position
  296. map_food_position();
  297. set_style(food, {
  298. 'left' : food_position[0] + 'px',
  299. 'top' : food_position[1] + 'px'
  300. });
  301. }
  302.  
  303. game_stat_left.innerHTML = 'Score: ' + game_score;
  304. game_stat_right.innerHTML = 'Level: ' + (game_level + 1);
  305.  
  306. // Add or modify snake blocks on each event
  307. for(var i = 0; i < snake.length; i++){
  308. var snake_elem = document.getElementById("snake_"+i);
  309. if(snake_elem == null){
  310. snake_elem = document.createElement("div");
  311. snake_elem.setAttribute("id", "snake_"+i);
  312. set_style(snake_elem, {
  313. 'position' : 'absolute',
  314. 'display' : 'block',
  315. 'width' : snake_width + 'px',
  316. 'height' : snake_width + 'px',
  317. 'border' : '0px solid #000000',
  318. 'background' : snake_color
  319. });
  320. snake_ground.appendChild(snake_elem);
  321. }
  322. set_style(snake_elem, {
  323. 'left' : snake[i][0] + 'px',
  324. 'top' : snake[i][1] + 'px'
  325. });
  326. }
  327.  
  328. };
  329.  
  330. }
  331. </script>
  332. </head>
  333. <body>
  334. <noscript>
  335. <h1 style="text-align: center;">Please use a Javascript enabled web browser. Thank you.</h1>
  336. </noscript>
  337. </body>
  338. </html>


Download: http://pastebin.com/raw.php?i=gEdVMMJG

Demo: http://pastehtml.com/view/cqkp8hmf1.html

12 comments:

  1. source download link?

    ReplyDelete
  2. An impressive share! I have just forwarded this onto a colleague who was doing a little research
    on 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

    ReplyDelete
  3. Unquestіοnably believe that which you said.
    Ү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

    ReplyDelete
  4. Nice blog heгe! Also yοur wеb site loads
    up 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

    ReplyDelete


  5. Stοp by my web site - web site
    Check out my webpage ... payday loan online

    ReplyDelete
  6. We abѕοlutely love yоur blog and finԁ
    almο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

    ReplyDelete
  7. Simply want to say your article is as astounding. The clearness
    in 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

    ReplyDelete
  8. Τhat іs very inteгestіng,
    You а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

    ReplyDelete
  9. Μ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.

    My web page ... Daniel

    ReplyDelete
  10. Attractive section of content. I just stumbled upon your weblog and
    in 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

    ReplyDelete
  11. What a data of un-ambiguity and preserveness of precious know-how about unexpected feelings.



    Look at my web-site: option fair
    My web site > option fair

    ReplyDelete