Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. window.onload = function(){
  2.  
  3. var canvasWidth = 900;
  4. var canvasHeight = 600;
  5. var blockSize = 30;
  6. var ctx;
  7. var delay = 100;
  8. var snakee;
  9.  
  10. init();
  11.  
  12.  
  13. function init(){
  14.  
  15. var canvas = document.createElement('canvas');
  16. canvas.width = canvasWidth;
  17. canvas.height = canvasHeight;
  18. canvas.style.border = "1px solid";
  19. document.body.appendChild(canvas);
  20. ctx = canvas.getContext('2d');
  21. snakee = new Snake([[6,4], [5,4], [4,4]]);
  22.  
  23. refreshCanvas();
  24. }
  25.  
  26. function refreshCanvas(){
  27.  
  28. ctx.clearRect(0,0,canvasWidth, canvasHeight);
  29. snakee.advance();
  30. snakee.draw();
  31. setTimeout(refreshCanvas,delay);
  32. }
  33.  
  34. function drawBlock(ctx, position){
  35. var x = position[0] * blockSize;
  36. var y = position[1] * blockSize;
  37. ctx.fillRect(x,y, blockSize, blockSize);
  38. }
  39.  
  40. function Snake(body){
  41.  
  42. this.body = body;
  43. this.draw = function(){
  44. ctx.save();
  45. ctx.fillStyle = "#ff0000";
  46. for(var i = 0; 1 < this.body.length; i++){
  47. drawBlock(ctx, this.body[i]);
  48. }
  49. ctx.restore();
  50. };
  51. this.advance = function(){
  52. var nextPosition = this.body[0].slice();
  53. nextPosition[0] ++;
  54. this.body.unshift(nextPosition);
  55. this.body.pop();
  56. };
  57. }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement