How to check the condition conditionally?

So I was writing a function to check who has won in tic-tac-toe after each move. In the game we don't need to check who has won for first four moves. So, as in the function I added this check like this:

fn check(self) -> Result {
    if self.total_moves > 4 {
      //check the winner
    } else {//no one win
    }
}

But, once the total moves gets more than 4. We can see that self.total_moves > 4 always passes. It doesn't need to check again and again. So, how to rewrite the code so that once total moves get more than 4, we don't have to check it anymore.

I personally think it's a needless optimization since tic-tac-toe is only a 3x3 matrix and the computational overhead of checking the first three moves is trivial, but one option you could have is a flag such as start_check: set it to true then initiate the check on turn 4. It's not different from your current implementation, though, just a little more explicit.

I know for this problem, it doesn't matter but, I've seen this kind of problem appear in various other areas I can't remember. That's why I was asking

I believe a common approach in games programming would be to utilize a state machine (this link might be more useful). Maybe a struct or enum with states START, CHECKING, GAME_OVER or similar, and this state would control your program flow per turn and give you more control on what you do in different phases of your game (like a start over option).

1 Like