This project plays the classic game of tic-tac-toe. The player goes first and is X. The computer goes second and is O. The board is laid out 1,2,3 top row, 4,5,6 center row, and 7,8,9 bottom row.
It has two levels. The 'easy' level is where the computer plays dumb, it just checks to find a random open square. After each move, the Stage calls to each square, which is assigned a unique list of a winning combination: i.e Square1 checks if 1,2,3 are filled, Square 2 checks if 4,5,6, etc. there are three across wins, three down wins and two diagonal wins for 8 WinLists.
The 'hard' level has the computer playing aggressively. For the first move, it takes the center square if the player hasn't taken it. For it's second move, if it has the center it tries to take one of the open corners to force X to keep blocking it.
I ran out of time to build more 'smarts' into the hard game. Plus there are limits to what I can do in Scratch to search all combinations. For the third and fourth moves for O, I planned on checking the O-list, to see if it had two of three in any of the 8 WinLists. If so, it would then pass the third square of the possible win list to see if it was free (i.e. if X had it), if not, O would take it and win. It would then check to see if X had two of three in any of the winlists, if the third was free then O would take it to block.
To do this I was going to set OSquare to each of the three squares in succession from each of the 8 WinLists. If the square number was in the O or X list, I would set it back to 0, if not, it would stay set and then if the 'open' square check was true that would be the move.
I also don't let the computer go first to keep the coding simpler.
I probably should have done the Nim game as suggested, but really thought that with my prior computer experience I should try something a bit more challenging. If I had incorporated some search-tree strategy into the game that may have worked too.
I made the assumption that people wouldn't cheat in this game - so you can click on an O and it will change into an X, or you can click an X square multiple times.
However, If you look at Square1, I added code 'amIClicked?' to prevent this. I.E. when Square1 gets set to an X or an O, amIClicked? gets set to true (1). If Square1 gets clicked after it becomes an O or an X (to turn an O into an X for example) it checks to see if amIClicked? is false(0). If it's true, it won't let it change. This code could be added to all squares, but I thought of it late and didn't get it added to all squares.
Thanks Dave - I really did enjoy this class and learned alot. I haven't done much graphic programming, all structured like invoice systems, etc. this really shows me that there is always something new to learn in this field. Have a great break!
Comments
You need to be logged in to post comments
Add a Comment