2016-11-18 77 views
0

我有類的遊戲:BodyPart,Snake和SnakeGame。 BodyPart類充當組成Snake類的節點,它基本上是BodyParts的鏈接列表,這些方法使用遞歸繪製並檢索/設置在吃蘋果時創建的每個BodyPart的位置。在蛇遊戲中確定蛇運動的錯誤行爲

我正在通過點擊鼠標來模擬這個事件,測試從吃蘋果到蛇的身體部位的添加。我的問題在於當窗口加載時引起的行爲的奇怪,因爲默認情況下<canvas>元素沒有焦點,所以我必須點擊它才能聽到<canvas>上的鍵盤事件。初始點擊給予<canvas>焦點會導致創建身體部位並將其添加到蛇。 我的問題是,當蛇開始移動時,新創建的身體部位不會跟隨頭部只有幾秒鐘後,新創建的身體部位的功能纔開始工作,並跟隨頭部。創建正文部分的其他點擊不會產生任何錯誤,只會產生第一次點擊。

我一直在試圖找出原因,但不能。我確信當我不用鼠標點擊創建新的身體部位時,這個問題會得到解決,但在這個特定的環境中,我真的很想知道這種行爲的原因!

主要的代碼在工作:

gameloop() { 
    var ctx = this.ctx; 

    this.snake.move(); 

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

    this.snake.draw(ctx); 

    setTimeout($.proxy(this.gameloop, this), this.frameLength); 
} 
move() { 
    var head = this.head; 

    //recursively pass back new position for each BodyPart node to be drawn 
    head.passBackPosition(); 

    //get new position for the root node 
    switch(this.direction) { 
     case "up": 
      head.yPosition -= this.velocity; 
      break; 

     case "down": 
      head.yPosition += this.velocity; 
      break; 

     case "left": 
      head.xPosition -= this.velocity; 
      break; 

     case "right": 
      head.xPosition += this.velocity; 
      break; 
    } 
} 
position(x, y) { 
    if(x && y) { 
     this.xPosition = x; 
     this.yPosition = y; 
    }else { 
     return {x:this.xPosition,y:this.yPosition}; 
    } 
} 

繼承人的遊戲的jsfiddle:https://jsfiddle.net/gabewest1/hq8wqwt4/7/

+0

這不會幫助你的代碼工作,但你確實知道在你創建一個新的實例之前必須用JavaScript定義類,對嗎? – PHPglue

+0

@PHPglue是的,我知道。我已經定義了我的類,其餘的代碼已經定義了,我只是選擇只發布與我的問題最相關的位,但是我的代碼的其餘部分處於小提琴中。 –

回答

1

我打你的小提琴和身體不按頭髮生邊界附近,其中x == 0或Ÿ== 0。

讀你的代碼,我發現:

position(x, y) { 
    if(x && y) { 
     this.xPosition = x; 
     this.yPosition = y; 
    }else { 
     return {x:this.xPosition,y:this.yPosition}; 
    } 
} 

這意味着只要你在任何這些邊界的,下面的行不執行:

this.xPosition = x; 
    this.yPosition = y; 

解決方案:

position(x, y) { 
    this.xPosition = x; 
    this.yPosition = y; 
    return {x:this.xPosition,y:this.yPosition}; 
} 

看小提琴:https://jsfiddle.net/vzsf2nee/1/