Tic-Tac-Toe

Hi. I'm a C++ noob. One of the first programs that I made is a tic-tac-toe game complete with an AI and 2-player modes. I am curious if there is a better way to do this. would like to hear your comments, thoughts and suggestions.
There are several large switch and if statements here, but they are actually quite simple. The ones in two player mode just check if the move is valid or not. The statements related to the CPU are described below:
First, the CPU checks if the first move was in the middle. If it was, then it chooses a random place to go, discluding the middle. If the first move was not the middle, then the computer goes to the middle. In any other case, the CPU checks if there is a winning move on the players behalf, and tries to block it. After the CPU checks for that, it checks if it has a winning case, and then goes to the position that would make it win. The last case is if there are no winning or losing moves and it's not the first move, the CPU just keeps guessing random positions until it gets a valid one.

Thanks for your help.
-Static

http://www.mediafire.com/?2odmznykbom

Sorry, It's too large to post, so you'll have to download it from mediafire. That's one reason I would like to know if there is a better way to do it (1115 lines of code).
I think pastebin works well for this kind of stuff. Could you put it there? I'm too lazy to download it XD
http://pastebin.com/m69853b72
That seems like a cool site.
I would reorder the checks so that it checks to see if it can win first, because if it can win and it is the CPU's turn, then it might as well win.

Anyway, I'm not really sure how your CPU is working, your code is kind of hard to follow as it is. I would suggest splitting up your code into functions (http://www.cplusplus.com/doc/tutorial/functions/) so that it is easier to read.

If I am reading it correctly, you have a variable to tell you what turn it is, etc. IMHO this isn't really necessary. Instead of having the computer care what turn it is on, it could just do something like this:

If middle isn't taken
Take middle
If can win
Win
If player can win
Block
Else
Try to make 2 in a row that isn't blocked
Thanks for the reply. I've rewritten my code and it went from 1115 lines to 440!

The reason that the CPU checks if it could win after it checks if it has to block something is that it's latter decision overrides the first one.

The turn variable was removed, and the rest optimized. Thanks again, but is it possible to optimize it some more? Should I use some different technique?
http://pastebin.com/m5c7ad5f

PS: How do you get links to work here? I've tried different tags and they don't work
Last edited on
Topic archived. No new replies allowed.