Создание змейки с помошью canvas
Добрый день дорогие форумчани. пытаюсь создать еду для змейки но не получается использовать beginPath и closePath. вот в чем проблема, змейка движется по принципу "удалить первый объект и создать новый" из-за этого удаляется и еда. Помогите исправить.
var app=new game(); app.start(); function game(){ var _this=this; this.snake=new snake(); this.food=new food(); this.start=function(){ this.snake.paint(); this.food.paintFood(); // _this.food.foodEmergence(); setInterval(function(){ _this.snake.move(); },350) this.bindEvents(); } this.bindEvents=function(){ document.body.addEventListener("keydown",function(e){ if(e.key=="ArrowDown"){ _this.snake.uxxutyun="down"; }else if(e.key=="ArrowUp"){ _this.snake.uxxutyun="up" }else if(e.key=="ArrowRight"){ _this.snake.uxxutyun="right" }else if(e.key=="ArrowLeft"){ _this.snake.uxxutyun="left" } }) } game.canvas=document.querySelector("canvas"); game.ctx=game.canvas.getContext("2d"); } function rectangle(){ this.x=50; this.y=50; this.w=20; } function snake(){ this.kobra=[new rectangle(),new rectangle(),new rectangle()]; this.uxxutyun="right"; this.paint=function(){ game.ctx.fillStyle="red"; for(let i=0;i<this.kobra.length;i++){ game.ctx.fillRect(this.kobra[i].x,this.kobra[i].y,this.kobra[i].w,this.kobra[i].w) } } this.move=function(){ game.ctx.beginPath(); game.ctx.clearRect(0,0,game.canvas.width,game.canvas.height) for(let i=this.kobra.length-1;i>=0;i--){ if(i==0){ if(this.uxxutyun=="right"){ this.kobra[i].x+=20; }else if(this.uxxutyun=="left"){ this.kobra[i].x-=20; }else if(this.uxxutyun=="up"){ this.kobra[i].y-=20; }else if(this.uxxutyun=="down"){ this.kobra[i].y+=20; } }else{ this.kobra[i].x=this.kobra[i-1].x; this.kobra[i].y=this.kobra[i-1].y; } } this.paint(); } } function foodRectangle(){ this.x=/*parseInt(Math.random()*800);*/150; this.y=/*parseInt(Math.random()*500);*/150; this.w=20; } function food(){ this.uteliq=[new foodRectangle()]; this.paintFood=function(){ game.ctx.beginPath(); game.ctx.fillStyle="green"; for(let i=0;i<this.uteliq.length;i++){ game.ctx.fillRect(this.uteliq[i].x,this.uteliq[i].y,this.uteliq[i].w,this.uteliq[i].w) } } this.foodEmergence=function(){ this.paintFood() } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <canvas width="800" height="500" style="background:lightgreen"></canvas> </body> <script type="text/javascript" src="js/class.js"></script> <script type="text/javascript" src="js/script.js"></script> </html> Прошу не обращать внимание на некоторые имена переменных |
Часовой пояс GMT +3, время: 23:52. |