2016-10-31 26 views
-1

我正在做一個象棋遊戲。我達到了需要更改函數內部4個變量的點,所以下次運行函數時,變量將會不同。下面我有需要看的代碼:下一次我調用它時,更改函數中的變量?

功能件Rotation將所有件的位置顛倒,以便其他玩家將會玩。

的Javascript:

function piecesRotation(){ 
    //rotate the pieces 
} 

function check(el){ 

    //there variables indicate which user turn is it 
    var FirstCurrentPlayersPiece = "B"; 
    var CurrentPlayersPieceColor = "black"; 
    var FirstOpponentsPieceLetter = "W"; 
    var OpponentsPieceColor = "white"; 
    //If player played then run the function below to change the position of the pieces and change the 4 variables so the other player will play 
    piecesRotation(); 
    FirstCurrentPlayersPiece = "W"; 
    CurrentPlayersPieceColor = "white"; 
    FirstOpponentsPieceLetter = "B"; 
    OpponentsPieceColor = "black"; 
} 

在HTML我所說的功能檢查(EL),其中EL是玩家點擊了elepemt。

爲了說明,我需要以某種方式改變這些變量:

var FirstCurrentPlayersPiece = "B"; 
var CurrentPlayersPieceColor = "black"; 
var FirstOpponentsPieceLetter = "W"; 
var OpponentsPieceColor = "white"; 

要這樣:

var FirstCurrentPlayersPiece = "W"; 
var CurrentPlayersPieceColor = "white"; 
var FirstOpponentsPieceLetter = "B"; 
var OpponentsPieceColor = "black"; 

而這些變量的變化,每次會發生的播放器播放。有沒有辦法做到這一點?

重要 英語不是我的第一語言,這就是爲什麼我在它不好。

NOTE1 我沒有提供整個代碼的原因是因爲它的龐大和堆棧溢出不會讓我貼吧。

NOTE2 我很蠢。我不得不使用全局變量(我認爲他們是不好的做法,這是唯一的解決辦法。

+7

聲明函數外部變量以保持它們的值 – Ted

+0

功能檢查(el)由HTML函數調用onClick =「check()」 – GeorGios

+1

如果將函數轉換爲對象,則可以聲明變量,如'this.OpponentsPieceColor ='black' ;'隨時用'check.OpponentsPieceColor ='white';'改變它(用你的對象實例化的變量來改變'check') –

回答

1

只需將一個對象的變量,並將它們傳遞給函數

var boardState = { 
     FirstCurrentPlayersPiece : "B", 
     CurrentPlayersPieceColor : "black", 
     FirstOpponentsPieceLetter: "W", 
     OpponentsPieceColor: "white" 
} 

function piecesRotation(){  
    boardState = { 
      FirstCurrentPlayersPiece : boardState.FirstOpponentsPieceLetter, 
      CurrentPlayersPieceColor : boardState.OpponentsPieceColor, 
      FirstOpponentsPieceLetter: boardState.FirstCurrentPlayersPiece, 
      OpponentsPieceColor: boardState.CurrentPlayersPieceColor 
    } 
} 


function check(el){ 
    piecesRotation(); 
} 
+0

在使用您的代碼之前,請您向我解釋您的代碼是如何工作的? (我問,因爲如果我不明白它是如何工作的,我不想使用一段代碼)。 – GeorGios

+0

我將變量放置在一個obejct中,當您調用'piecesRotation'並傳遞對象時,它將使用FirstOpponentsPieceLetter OpponentsPieceColor交換FirstCurrentPlayersPiece和CurrentPlayersPieceColor,並返回修改的對象。然後,您可以使用該修改的對象來更改應用程序的狀態 –

+0

我試過了您的代碼,但它不起作用。 – GeorGios

相關問題