Wednesday, July 18, 2012

TicTacToe

TicTacToe::
UI->>
For the game logic, declare following variables::

 Button button=null;
    String vPlayer="Player1"; //for storing the current player. Switches with every btnClick
    int vRow1=0, vRow2=0, vRow3=0, vCol1=0, vCol2=0, vCol3=0, vDiag1=0, vDiag2=0;
    /*above variables changes for each button click.
     * if button 1 is pressed, vRow1,vCol1,vDiag1 are incremented for player1 else decremented for player 2
     * For player 1 to win, the value of any of the above variable should be +3 and for player 2, it should be -3
     */
    int vClicks=0; //game ends when its value reaches 9

for each button, increment rows, columns and diagonals accordingly..

public void btn11_Click(View view){
    vClicks++;
    button=(Button)view;
    view.setEnabled(false);
        if(vPlayer=="Player1"){
    vRow1++;
    vCol1++;
    vDiag1++;
        vPlayer="Player2";
    button.setText("X");
    }
    else{
    vRow1--;
    vCol1--;
    vDiag1--;
        vPlayer="Player1";
    button.setText("0");
    }
    win_or_lose();     }


and the win_or_lose method:



 public void win_or_lose(){
    EditText editText=new EditText(this);
    int flag=0;
    if(vRow1==3 || vRow2==3 || vRow3==3 || vCol1==3 || vCol2==3 || vCol3==3 || vDiag1==3 || vDiag2==3){
    editText.setText("Player 1 wins");       setContentView(editText);
    flag++;
    }
    else if(vRow1==-3 || vRow2==-3 || vRow3==-3 || vCol1==-3 || vCol2==-3 || vCol3==-3 || vDiag1==-3 || vDiag2==-3){
    editText.setText("Player 2 wins");
    setContentView(editText);
    flag++;
    }
        if(vClicks==9 && flag==0){
    editText.setText("Game Draw");
    setContentView(editText);
    }
    }


a lot of code optimization can definitely be done. Looking forward for your comments on how you would like to optimize the code.

No comments:

Post a Comment