Simple Snake Game using HTML5 canvas and Pure Javascript

Getting Started

It is important that the browser you use to play this game is accepting HTML5 canvas since where going to use this as the container of our game. The original source code of this tutorial can be found using the youtube link below which I modify by adding score and highscore. https://www.youtube.com/results?search_query=snake+game+using+angular+js

Full Source Code

Here's the full code for this simple snake game.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Simple Snake Game</title>
  5. </head>
  6. <body>
  7. <p>Score: <span id="score">0</span></p>
  8. <p>High Score <span id="highscore">0</span></p>
  9. <canvas id="gc" width="400" height="400"></canvas>
  10. <script>
  11. window.onload=function() {
  12. canv=document.getElementById("gc");
  13. ctx=canv.getContext("2d");
  14. document.addEventListener("keydown",keyPush);
  15. setInterval(game,1000/15);
  16. scoreShow=document.getElementById('score');
  17. highscoreShow=document.getElementById('highscore');
  18. }
  19. px=py=10;
  20. gs=tc=20;
  21. ax=ay=15;
  22. xv=yv=0;
  23. trail=[];
  24. tail = 5;
  25. score = 0;
  26. highscore = 0;
  27. function game() {
  28. px+=xv;
  29. py+=yv;
  30. if(px<0) {
  31. px= tc-1;
  32. }
  33. if(px>tc-1) {
  34. px= 0;
  35. }
  36. if(py<0) {
  37. py= tc-1;
  38. }
  39. if(py>tc-1) {
  40. py= 0;
  41. }
  42. ctx.fillStyle="black";
  43. ctx.fillRect(0,0,canv.width,canv.height);
  44.  
  45. ctx.fillStyle="lime";
  46. for(var i=0;i<trail.length;i++) {
  47. ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
  48. if(trail[i].x==px && trail[i].y==py) {
  49. gameOver();
  50. }
  51. }
  52. trail.push({x:px,y:py});
  53. while(trail.length>tail) {
  54. trail.shift();
  55. }
  56.  
  57. if(ax==px && ay==py) {
  58. score = score + 10;
  59. scoreShow.innerHTML = score;
  60. tail++;
  61. ax=Math.floor(Math.random()*tc);
  62. ay=Math.floor(Math.random()*tc);
  63. }
  64. ctx.fillStyle="red";
  65. ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
  66. }
  67. function keyPush(evt) {
  68. switch(evt.keyCode) {
  69. case 37:
  70. if((xv!=1 && yv!=0) || (xv==0 && yv==0)){
  71. xv=-1;yv=0;
  72. }
  73. break;
  74. case 38:
  75. if((xv!=0 && yv!=1) || (xv==0 && yv==0)){
  76. xv=0;yv=-1;
  77. }
  78. break;
  79. case 39:
  80. if((xv!=-1 && yv!=0) || (xv==0 && yv==0)){
  81. xv=1;yv=0;
  82. }
  83. break;
  84. case 40:
  85. if((xv!=0 && yv!=-1) || (xv==0 && yv==0)){
  86. xv=0;yv=1;
  87. }
  88. break;
  89. }
  90. }
  91. function gameOver(){
  92. tail = 5;
  93. if(score > highscore){
  94. highscore = score;
  95. }
  96. score = 0;
  97. scoreShow.innerHTML = 0;
  98. highscoreShow.innerHTML = highscore;
  99.  
  100. }
  101. </script>
  102. </body>
  103. </html>
That ends this tutorial. Happy Coding :)

Add new comment