Search code examples
androidtic-tac-toe

how to do different event on first and second touch (TicTacToe for Android)


I'm a beginner in creating apps in android but as my first project I'm trying to build a TicTacToe game.. but it's about long time I'm trying to set X when the Button is touched firstly and set O at second touch. I don't know how to fix this. I thing it should be work as I did following, but it's not...! this is my source code:

public class MainActivity extends Activity implements OnClickListener{

private Button b1,b2,b3,b4,b5,b6,b7,b8,b9;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1=(Button) findViewById(R.id.button1);
    b1.setOnClickListener(this);

    b2=(Button) findViewById(R.id.button2);
    b2.setOnClickListener(this);

    b3=(Button) findViewById(R.id.button3);
    b3.setOnClickListener(this);

    b4=(Button) findViewById(R.id.button6);
    b4.setOnClickListener(this);

    b5=(Button) findViewById(R.id.button10);
    b5.setOnClickListener(this);

    b6=(Button) findViewById(R.id.button11);
    b6.setOnClickListener(this);

    b7=(Button) findViewById(R.id.button7);
    b7.setOnClickListener(this);

    b8=(Button) findViewById(R.id.button8);
    b8.setOnClickListener(this);

    b9=(Button) findViewById(R.id.button5);
    b9.setOnClickListener(this);
}

public void onClick(View v)
{
    boolean press=true;
    int i=0;
    while(i<9){     
            if(press==true)
            {
                if((Button)v==b1)
                {
                    b1.setText("X");
                    press=false;
                }

                else if((Button)v==b2)
                {
                    b2.setText("X");
                    press=false;
                }

                else if((Button)v==b3)
                {
                    b3.setText("X");
                    press=false;
                }

            }

            if(press==false)
            {
                if((Button)v==b1)
                {
                    b1.setText("O");
                    press=true;
                }
                else if((Button)v==b2)
                {
                    b2.setText("O");
                    press=true;
                }
                else if((Button)v==b3)
                {
                    b3.setText("O");
                    press=true;
                }
            }
            i++;
    }
}

Solution

  • onClick firstly you set boolean press=true; so in while loop it always take you into the first if loop

    Declare boolean press=true; as a global variable