Saturday, October 24, 2009

Pseudocode use (example of Tic-Tac-Toe)

Now your programs are becoming bigger and you need to exercise some discipline by planning the structure of your program before rushing to code.
For example in Tic-Tac-Toe task the plan (sometimes called pseudocode) can be more or less detailed in the beginning but rather more detailed when you are approaching actual coding. Initially it might look like the following:

  • Set up your JPanel with GridLayout
  • Declare an integer counter variable
  • Declare 9 JButtons (for example named b1, b2, etc.)
  • Add ActionLiteners for all buttons in init() method and add each button to the display panel of the game field
  • Add a listener method itself using actionPerformed(ActionEvent e)
  • Add logic for each possible variation of clicked button along with the counter logic checking if it is an odd click or even when in one case use (for example if b1 is clicked) something like b1.setText(“X”) ; or setting the text to “O” and also add button logic like if(actionCommand==”1”){… where you will be setting text to the proper letter and incrementing the counter variable by one (so that next click will setText to a different letter).

Note1: the last logic assumes that you define buttons like: JButton b1=new JButton("1");

Note2: you can use actionCommand in your IF-logic, which uses the label that you gave the button (see Note1) or you can use the system name (b1 - this case) if you get it from a.getSource() method like in the Example 8-14, where a comes from actionPerformed(ActionEvent a)

Remember that if you need more info oin any method - use google.


If after this you have a clear understanding of your programming sections – start coding. If you need to iron out more details – add these details to the pseudocode.

Of course the program can be enhanced in many ways like detecting the winner or even playing against human, etc.

No comments:

Post a Comment