2016-11-18 64 views
0

我有一個貪吃蛇遊戲,每當我收集蘋果時都會出錯。碰撞後蘋果會消失,一個新的蘋果會在一個新的位置產生,但由於某種原因,第一個蘋果會在原來的位置重新生成。然後當我收集新產生的第二個蘋果時,前兩個蘋果消失,第三個蘋果在新位置產生,但第一個和第二個蘋果然後在原始位置重新生成,並且這個過程繼續...在蛇遊戲中不適當產卵的蘋果

只有最新產生的蘋果能夠檢測與蛇的碰撞併產生新的蘋果。

我有一個Apple類跟蹤其x和y座標以及一個SnakeGame類與蘋果和蛇組成。當收集蘋果時,我將SnakeGame.apple屬性設置爲null,然後使用新的x,y座標創建一個新的Apple對象,並將其設置爲新的SnakeGame.apple對象。

任何想法來解決這個問題,將不勝感激!

繼承人,如果你想和我玩的代碼提琴:https://jsfiddle.net/gabewest1/knuxsa5t/1/

蘋果類:

class Apple { 
    constructor(x, y) { 
    this.xPos = x; 
    this.yPos = y; 
    this.radius = 10; 
    } 

    draw(ctx) { 
    ctx.fillStyle = "black"; 
    ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI); 
    ctx.fill(); 
    } 

    position(x, y) { 
    if (x > -100 && y > -100) { 
     this.xPos = x; 
     this.yPos = y; 
    } else { 
     return { 
     x: this.xPos, 
     y: this.yPos 
     }; 
    } 
    } 
} 

SnakeGame類:

class SnakeGame { 
    constructor(snake) { 
     this.ctx = $("#myCanvas")[0].getContext("2d"); 
     this.canvas = $("#myCanvas")[0]; 
     this.init(); 

     this.frameLength = 500; 
     this.apple = this.createApple(); 
     this.snake = snake; 

     this.score = 0; 
     this.gameloop(); 
    } 

    createApple() { 
     var xPos = Math.floor(Math.random() * this.canvas.width); 
     var yPos = Math.floor(Math.random() * this.canvas.height); 
     var apple = new Apple(xPos, yPos); 
     return apple; 
    } 

    gameloop() { 
     var ctx = this.ctx; 

     this.snake.move(); 

     if (this.collision()) { 
      console.log("There was a collision!"); 
      this.score++; 
      this.increaseSnake(); 
      this.apple = null; 
     } 

     ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); 

     this.snake.draw(ctx); 

     if (this.apple) { 
     this.apple.draw(ctx); 
     } else { 
      this.apple = this.createApple(); 
     } 

     setTimeout($.proxy(this.gameloop, this), this.frameLength); 
    } 
} 
+0

它看起來像你只有一個this.apple。你需要一批蘋果來跟蹤多個蘋果。 – nycynik

+0

但我只想要一個蘋果。這就是爲什麼我會認爲只有一個蘋果應該呈現給屏幕而不是多個。我嘗試過使用一個數組來彈出並在碰撞時推送一個新的蘋果,但沒有成功。 –

回答

0

創建弧前只需添加ctx.beginPath();

ctx.fillStyle = "black"; 
ctx.beginPath(); 
ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI); 
ctx.fill(); 

ctx跟蹤創建的每個圓弧的,並適用fill所有這些形狀。

+0

真棒工作!一般情況下,我應該在我的所有繪圖之前始終使用'beginPath()'嗎? –

+0

是的,你應該在啓動一組獨立形狀時使用'beginPath'。 'beginPath'將放棄最後一個形狀並重新開始。 https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes –