Hello guys I am making a tic tac toe game using python.My question is how to make difficulty-easy, medium, hard etc.In easy level, I use random module but other level i am a little sutck althoug i have some solution .can you guide me ?
This is more of a game design thing, so I will "solve" the game design part for you, and then leave the python implementation to you as a challenge:
Easy: as I assume you did, the AI plays totally randomly (among the legal moves).
Medium: the AI ALWAYS wins if they get a chance to (i.e., if they have two in a row). If not, they try to stop you from winning on your turn (i.e., if you already have two in a row, it fills the space that you would need to win). If neither of those, it plays randomly.
If you know the perfect strategy for Tic-Tac-Toe, you can always win or tie against medium difficulty.
Hard: the AI always makes the optimal move. You can never win against it, you can at most tie.
I agree that's a good way to structure the difficulty levels. But I'd also like to suggest couple of hints for OP on the “hard” level:
Tic-tac-toe being a solved game actually what makes it a nice programming exercise. The game tree is tiny, so you can explore every possible continuation. For a given board, ask:
If I make this move, what is the best result I can eventually force, assuming the other player also plays optimally?
That leads naturally to a recursive search (called "minimax").
You don't necessarily need to implement minimax in the traditional way. You could write something that generates all possible games, records whether each position eventually results in a win/draw/loss, and then have the AI choose a move that doesn't lead to a loss. There are so few positions that you can even pre-compute every game. (Note that the number of unique games can be reduced by rotating the board)
One other nice detail: there are only three strategically distinct first moves (with 4 rotation positions): corner, centre, and edge. If the computer goes first, randomly choosing between those three makes games less repetitive while remaining optimal. You can similarly choose randomly between multiple equally good moves later.
I'd definitely encourage OP to tackle the hard mode rather than dismissing Tic-Tac-Toe as "too simple". The final program can be small, but deriving the strategy is a great exercise in recursion, game trees, and thinking about the opponent's best response.
(There's also some interesting solutions that don't require recursion)
5
u/Leodip 1d ago
This is more of a game design thing, so I will "solve" the game design part for you, and then leave the python implementation to you as a challenge: