Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Snake</title>
  6. </head>
  7. <body>
  8. <canvas id="snake" width="400" height="400"></canvas>
  9. <script type="text/javascript">
  10. (function (window, document) {
  11. function Snake(el) {
  12. this.el = el;
  13. this.ctx = this.el.getContext('2d');
  14.  
  15. this.xv = 0;
  16. this.yv = 0;
  17.  
  18. this.px = 10;
  19. this.py = 10;
  20.  
  21. this.gs = 20;
  22. this.tc = 20;
  23.  
  24. this.ax = 15;
  25. this.ay = 15;
  26.  
  27. this.trail = [];
  28. this.tail = 5;
  29.  
  30. document.addEventListener('keydown', this.onKeyDown.bind(this));
  31. this.interval = setInterval(this.game.bind(this), 1000/10);
  32. }
  33.  
  34. Snake.prototype.game = function () {
  35. this.px += this.xv;
  36. this.py += this.yv;
  37.  
  38. if (this.px < 0) { this.px = this.tc - 1; }
  39. if (this.px > this.tc - 1) { this.px = 0; }
  40. if (this.py < 0) { this.py = this.tc - 1; }
  41. if (this.py > this.tc - 1) { this.py = 0; }
  42.  
  43. this.ctx.fillStyle = 'black';
  44. this.ctx.fillRect(0, 0, this.el.width, this.el.height);
  45.  
  46. this.ctx.fillStyle = 'lime';
  47. for (var i = 0; i < this.trail.length; i++) {
  48. this.ctx.fillRect(
  49. this.trail[i].x * this.gs,
  50. this.trail[i].y * this.gs,
  51. this.gs - 2,
  52. this.gs - 2);
  53.  
  54. if (this.trail[i].x == this.px && this.trail[i].y == this.py) {
  55. this.tail = 5;
  56. }
  57. }
  58.  
  59. this.trail.push({
  60. x: this.px,
  61. y: this.py,
  62. });
  63.  
  64. while (this.trail.length > this.tail) {
  65. this.trail.shift();
  66. }
  67.  
  68. if (this.ax == this.px && this.ay == this.py) {
  69. this.tail++;
  70. this.ax = Math.floor(Math.random() * this.tc);
  71. this.ay = Math.floor(Math.random() * this.tc);
  72. }
  73.  
  74. this.ctx.fillStyle = 'red';
  75. this.ctx.fillRect(
  76. this.ax * this.gs,
  77. this.ay * this.gs,
  78. this.gs - 2,
  79. this.gs - 2);
  80. }
  81.  
  82. Snake.prototype.onKeyDown = function (e) {
  83. switch (e.keyCode) {
  84. case 37:
  85. this.xv = -1;
  86. this.yv = 0;
  87. break;
  88. case 38:
  89. this.xv = 0;
  90. this.yv = -1;
  91. break;
  92. case 39:
  93. this.xv = 1;
  94. this.yv = 0;
  95. break;
  96. case 40:
  97. this.xv = 0;
  98. this.yv = 1;
  99. break;
  100. }
  101. }
  102.  
  103. window.Snake = Snake;
  104. })(window, document);
  105.  
  106. document.addEventListener('DOMContentLoaded', function () {
  107. var snake = new Snake(document.getElementById('snake'));
  108. });
  109. </script>
  110. </body>
  111. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement