Something like this:
I am not sure how to code for this as I have only
In a small, simple game like tic-tac-toe, you can build a tree, where:
Then X is searching for a move which will maximize the minimum result, knowing that O will search (on his subsequent turn) for a move which will minimize the maximum result, knowing that X will search (on his subsequent turn to that) for a move which will...
This is the minimax algorithm.
In Tic-Tac-Toe, the tree can only get 9 layers deep, and if you want to be slick, you can take advantage of some board symmetries and keep the computations and data structures manageable.
Note that for more complex games this will fail for one reason or another (chess is deterministic, but too large to handle this way; backgammon needs probabilistic techniques, etc) but many approaches are variations on this theme.