-2

I'm working in this project for 3 days and i can not figure out where I'm doing wrong if you can help me with i really appreciate your help.I'm trying to create a tic tac toe game .When I'm running the game if the player X or O wins a message will pop up saying that X or O win .But if the a non of users win a message should pop up and saying there is no winner . the pop up for the winner is working perfectly but the pop up for no one win does not work.if you can help me to fix it you are really making my day.

public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;

int activePlayer = 0; // for x player

int[] gameState ={2,2,2,2,2,2,2,2,2}; // 2 means unplayed.

int[][] winningLocation ={{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameover =false;

public void gameLogic(View view){

    ImageView tappedView =(ImageView) view;

    int tappedLocation = Integer.parseInt(view.getTag().toString());

    if(gameState[tappedLocation]==2 && !gameover) {
        gameState[tappedLocation]=activePlayer;

        tappedView.setTranslationY(-3000f);

        if (activePlayer == 0) {

            tappedView.setImageResource(R.drawable.x);

            activePlayer = 1;

        } else if (activePlayer == 1) {
            tappedView.setImageResource(R.drawable.o);
            activePlayer = 0;
        }
        tappedView.animate().translationYBy(3000f).setDuration(500);
    }
  String mesg ="";

    for(int[]winningPostion :winningLocation){

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){

            if (activePlayer ==0)

                mesg = "O is the winner!";

            if(activePlayer==1)

                mesg = "X is the winner!";

            else
                gameover=true;
            mesg="there is no winner ";


            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);

            gameover=true;
        }
    }




}

// a method that let the players play again

public void playagain(View view){
    LinearLayout winnerLayout = (LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);
    gameover=false;
    activePlayer=0;

    for (int i =0; i < gameState.length;i++)
        gameState[i]=2;

    GridLayout gridlayout = (GridLayout) findViewById(R.id.gridlayout);
    for(int i =0 ; i < gridlayout.getChildCount(); i++)
        ((ImageView)gridlayout.getChildAt(i)).setImageResource(0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

 // to play the song
      mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song);
      mediaPlayer.start();


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // to show and hide the playing again button

   LinearLayout winnerLayout = ( LinearLayout) findViewById(R.id.winnerLayout);
    winnerLayout.setVisibility(View.INVISIBLE);

   FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

// pause and play the song when the user leaving annd returning the game
@Override
protected void onPause(){
    super.onPause();
    mediaPlayer.stop();
    mediaPlayer.release();
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
afgboy
  • 33
  • 1
  • 10
  • activePlayer can never be different from 0 or 1, you have to think it other way. – Foo Bar Jun 08 '17 at 12:18
  • 1
    Say `it's a draw!` – xenteros Jun 08 '17 at 12:19
  • Thank you for taking your time to answer my question .what other way bro .If you can explain me a bit more plz – afgboy Jun 08 '17 at 12:20
  • @xenteros almost red flag you, because I laughed haha - I said ALMOST, your answer is perfect for the question...harsh- Now for real, problem is that you use **activePlayer ** to determine winner, so, you should do it like "if all boxes are checked but there is no line, then its a draw" in your code -- cant tell you how exactly but I hope this explanation gives you a new way to think the problem – Foo Bar Jun 08 '17 at 12:20
  • 3
    Read [mcve]. "Does not work" is not something we could help with. – GhostCat Jun 08 '17 at 12:20
  • xenteros What you mean by its a draw ? Can you explain me a bit more because im new with this language – afgboy Jun 08 '17 at 12:24
  • @afgboy a draw is literally a [draw](https://en.wikipedia.org/wiki/Tie_(draw)) – Foo Bar Jun 08 '17 at 12:24

5 Answers5

1

Create a function that check your array :

int[] gameState ={2,2,2,2,2,2,2,2,2};

If all are different from 2, and none of the player won, it means its a tie.

EDIT:

Use this function, that will tell if your arr, contains item:

public static boolean my_contains(int[] arr, int item) {
    for (int n : arr) {
        if (item == n) {
            return true;
        }
    }
    return false;
}

Then do :

//Check winning position
for(int[]winningPostion :winningLocation){
    //If there is a winning position
    if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
            && gameState[winningPostion[1]]== gameState[winningPostion[2]]
            && gameState[winningPostion[0]]!=2){
        //Look for the winner
        if (activePlayer ==0)
            mesg = "O is the winner!";

        if(activePlayer==1)
            mesg = "X is the winner!";

        LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
        winnerLayout.setVisibility(View .VISIBLE);

        TextView winnermesg = (TextView) findViewById(R.id.editText);
        winnermesg.setText(mesg);

        gameover=true;
    }
}
//Here, all winning position have been checked, and gameover is still false
//Check if all X and O have been placed
if(!my_contains(gameSate, 2) && !gameover){
    //If so, and gameover is false, then its a tie.
    gameover=true;
    mesg="there is no winner ";

    //README : this may be the wrong layout, its up to you to change it to the good one, but it should pop your message
    LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
    winnerLayout.setVisibility(View .VISIBLE);

    TextView winnermesg = (TextView) findViewById(R.id.editText);
    winnermesg.setText(mesg);
}
Asew
  • 374
  • 2
  • 13
  • Thank you Asew for replaying back . Create a function but why? – afgboy Jun 08 '17 at 12:28
  • keep "if (activePlayer ==0){ (...)" and "if (activePlayer ==1){ (...)" and read your gameState instead of that "else". @afgboy – Foo Bar Jun 08 '17 at 12:28
  • @FooBar I added {} but still did not work man else { gameover=true; mesg="there is no winner "; } – afgboy Jun 08 '17 at 12:35
  • @Asew you could just count symbols played. Once you counted to 9, and no winner has been selected based on lines, then it's a draw. – diginoise Jun 08 '17 at 12:48
  • @diginoise how do u do that ? – afgboy Jun 08 '17 at 12:51
  • 1
    @afgboy Oh right I think I get it. You have to put the if statement I added, outside your `for(int[]winningPostion :winningLocation){` because in this loop, you're looking for the winner, because your condition assume there is one. – Asew Jun 08 '17 at 12:51
  • Thank you so much Asew for taking your time to explain me but it stills does not work the message does not pop up :( – afgboy Jun 08 '17 at 13:03
  • Aaaaah, I think I forgot the pop-up message functions. I copy pasted yours in the end of my `if`. Try and tell me. – Asew Jun 08 '17 at 13:08
0

Enclose the block with braces { }

else {
    gameover=true;
    mesg="there is no winner ";
}
dustblue
  • 557
  • 5
  • 14
0

Probably it doesnt work because of this piece of code

if (activePlayer ==0)

    mesg = "O is the winner!";

if(activePlayer==1)

    mesg = "X is the winner!";

else
    gameover=true;
mesg="there is no winner ";

try to use curly braces, its best practise anyways. Like this:

if (activePlayer ==0){

    mesg = "O is the winner!";

}else if(activePlayer==1){

    mesg = "X is the winner!";

}else{
    gameover=true;
    mesg="there is no winner ";
}
Jozef Dochan
  • 926
  • 10
  • 27
0

Currently you are not going to track no winner, as your if() check for a line of same symbols which were played.

No winner means no line of the same symbols, but the fact that the board is full. You can count not-plaid (count 2s in your array) or increment a counter each time a symbol is played. As soon as you plaid 9 but there is no winning line, then it's a draw.

if(gameState[winningPostion[0]] == gameState[winningPostion[1]]
                && gameState[winningPostion[1]] == gameState[winningPostion[2]]
                && gameState[winningPostion[0]] !=2 ) {
    //somebody has scored a line, but who?
} else if (haveWePlayed9()) {
    //no winner
}
diginoise
  • 7,352
  • 2
  • 31
  • 39
0
change the forloop with below one....

for(int i=0;i<winningLocation.length;i++){
        Boolean istie = true;
        int []winningPostion = winningLocation[i];
        mesg="there is no winner ";

        if(gameState[winningPostion[0]] == gameState [winningPostion[1]]
                && gameState[winningPostion[1]]== gameState [winningPostion[2]]
                && gameState[winningPostion[0]]!=2){
            mesg="there is no winner ";
            if (activePlayer ==0)
                mesg = "O is the winner!";

            if(activePlayer==1)
                mesg = "X is the winner!";

            LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
            winnerLayout.setVisibility(View .VISIBLE);

            TextView winnermesg = (TextView) findViewById(R.id.editText);
            winnermesg.setText(mesg);
            istie = false;
            gameover=true;
             return;
        }
        if(i==winningLocation.length-1){
            if(istie){
                LinearLayout winnerLayout =(LinearLayout)findViewById (R.id.winnerLayout);
                winnerLayout.setVisibility(View .VISIBLE);

                TextView winnermesg = (TextView) findViewById(R.id.editText);
                winnermesg.setText(mesg);
            }

        }
    }
saumil patel
  • 139
  • 1
  • 5