我正在做一个国际象棋游戏。我达到了一个点,我需要改变4个变量在一个函数中,所以下次我运行这个函数,变量将是不同的。下面我有必要查看的代码:
函数piecesRotation将所有棋子的位置颠倒过来,这样其他玩家就可以玩了。
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中,我调用check(el)函数,其中el是玩家点击的元素。
为了说明,我需要改变这些变量:
var FirstCurrentPlayersPiece = "B";
var CurrentPlayersPieceColor = "black";
var FirstOpponentsPieceLetter = "W";
var OpponentsPieceColor = "white";
:
var FirstCurrentPlayersPiece = "W";
var CurrentPlayersPieceColor = "white";
var FirstOpponentsPieceLetter = "B";
var OpponentsPieceColor = "black";
玩家每次玩游戏时,这些变量都会发生变化。有办法吗?
重要英语不是我的第一语言,这就是我不擅长英语的原因。
注一我没有提供整个代码的原因是它太大了,Stack overflow不允许我粘贴它。
注2 我很笨。我不得不使用全局变量(因为我认为它们是不好的做法,这是唯一的解决方案。
只需将变量放在对象中并传递给函数
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();
}