这是我必须检查球员赢得tic圆通脚趾比赛的代码。这是一个非常长的if语句,可以改进。该板由9个图片框组成。我是一个c#初学者。
pBox.Image = Player.players[Player.playerTurn].getImage();
//check for wins
if (pbxSquare0.Image == Player.players[Player.playerTurn].getImage() && //horizontal
pbxSquare1.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare2.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare3.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare4.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare5.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare6.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare7.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare8.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare0.Image == Player.players[Player.playerTurn].getImage() && //vertical
pbxSquare3.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare6.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare1.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare4.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare7.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare2.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare5.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare8.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare0.Image == Player.players[Player.playerTurn].getImage() && //diagnonal
pbxSquare4.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare8.Image == Player.players[Player.playerTurn].getImage()
||
pbxSquare2.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare4.Image == Player.players[Player.playerTurn].getImage() &&
pbxSquare6.Image == Player.players[Player.playerTurn].getImage())
{
//playerturn is the winner
MessageBox.Show(playerturn + "wins");
}
答案 0 :(得分:0)
您应该为游戏创建一个二维数组。可能是枚举类型。
enum FieldState { Empty, Player1, Player2 };
private FieldState[,] _gameField = new FieldState[3,3];
如果有转弯,请相应更新您的游戏区域。同时分配图片。 如果你的游戏状态在数组中,则更容易找到胜利条件,因为你可以循环。
private bool win(FieldState player){
return winHorizontal(player) || winVertical(player) || winDiagonal(player);
}
private bool winHorizontal(FieldState player){
for (int y = 0; y < 3; y++){
bool win = true;
for (int x = 0; x < 3; x++)
win &= _gameField[x,y] == player;
if (win) return true;
}
return false;
}