Now let’s get to the source of programming. During the next five minutes I’d like you to contemplate what you think has to occur when you click on one of the Noughts and Crosses buttons. List some of the things that should happen and maybe even start thinking about the flow of logic, I’ll wait here…
…so how did you go? Hopefully you realised the complexity of this problem. Therein lies the essence of programming…how do we get Visual Basic (in this instance) to simulate a game of Tic Tac Toe correctly? Let’s start by listing some things that need to be considered, we won’t worry about sequence at this stage:
- Does this position already have a Nought or Cross?
- Does this position mean that I’ve won?
- If I have won, do I initiate some kind of win code?
- If I haven’t won, I need the computer to have a turn.
- What if the computer wins on it’s go?
- What about the instructions label, what should it say?
- What about the Play Again button, can I enable it now?
You might be able to think of other considerations but for now this should be a good start. Our next step in solving this problem is to structure what the computer should be checking and what it should do in a vaguely correct sequence:
1. If the Play Again button is disabled 2. enable it 3. If we're allowed to click on this square 4. Put a cross in it 5. Check if this cross means we win 6. If we have won 7. Respond accordingly 8. If we did not win 9. Let the computer have a turn 10. If the computer has won 11. Respond accordingly 12. If the computer has not won 13. Respond accordingly
Hopefully this makes some kind of sense. It’s not complete. It’s not code. It’s definitely not acceptable to VB, but it is a starting point. Now we’ll turn that into a Flow Chart:
Apologies for the compactness of that diagram but I wanted it to fit into the website structure…it does however show the flow that we will need to achieve with our code.
So it’s probably time to actually create some code, why don’t you double click on your “but1” button (or whatever you called yours) and in the sub procedure that it makes add the following comments:
'IF THE PLAY AGAIN BUTTON IS DISABLED ' ENABLE THE PLAY AGAIN BUTTON 'IF THIS SQUARE IS EMPTY AND CAN BE PLAYED IN ' PUT A CROSS IN THIS SQUARE ' FIND OUT IF THIS MOVE MEANS WE WIN ' IF WE WON ' FINISH THE GAME APPROPRIATELY ' IF WE DID NOT WIN ' HAVE THE COMPUTER'S TURN ' IF THE COMPUTER WON ' FINISH THE GAME APPROPRIATELY ' IF THE COMPUTER DID NOT WIN ' UPDATE THE INSTRUCTIONS LABEL APPROPRIATELY
And this leads us to the topic of “selection“…