Tic-tac-toe code help improve

后端 未结 1 1419
北恋
北恋 2021-01-26 13:13

This is the code i have to check the players win for the tic tact toe game. It is a very long if statement that can be improved. The board is made of 9 picture boxes.I am a c# b

相关标签:
1条回答
  • 2021-01-26 13:46

    You should create a 2-dimensional array for your game. Possibly with an enum type.

     enum FieldState { Empty, Player1, Player2 };
    private FieldState[,] _gameField = new FieldState[3,3];
    

    If there is a turn, update your game field accordingly. Also assign the pictures. If you have your gamestate in an array, its much easier to find the win condition because you can loop.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题