我正在制作国际象棋游戏。我达到了一个需要在函数内部更改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是玩家点击的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 我没有提供整个代码的原因是因为它是巨大的而且Stack溢出不允许我粘贴它。
注2 我很蠢。我不得不使用全局变量(因为我认为它们是不好的做法,它是唯一的解决方案。
答案 0 :(得分: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();
}