tik-tac-toc game main activity code
public class MainActivity extends ActionBarActivity {
// 0 = yellow, 1 = red
int activePlayer = 0;
boolean gameIsActive = true;
// 2 means unplayed
int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};
int[][] winningPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public void dropIn(View view) {
ImageView counter = (ImageView) view;
int tappedCounter = Integer.parseInt(counter.getTag().toString());
if (gameState[tappedCounter] == 2 && gameIsActive) {
gameState[tappedCounter] = activePlayer;
counter.setTranslationY(-1000f);
if (activePlayer == 0) {
counter.setImageResource(R.drawable.yellow);
activePlayer = 1;
} else {
counter.setImageResource(R.drawable.red);
activePlayer = 0;
}
counter.animate().translationYBy(1000f).rotation(360).setDuration(300);
for (int[] winningPosition : winningPositions) {
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2) {
// Someone has won!
gameIsActive = false;
String winner = "Red";
if (gameState[winningPosition[0]] == 0) {
winner = "Yellow";
}
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText(winner + " has won!");
LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
} else {
boolean gameIsOver = true;
for (int counterState : gameState) {
if (counterState == 2) gameIsOver = false;
}
if (gameIsOver) {
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText("It's a draw");
LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
layout.setVisibility(View.VISIBLE);
}
}
}
}
}
public void playAgain(View view) {
gameIsActive = true;
LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
layout.setVisibility(View.INVISIBLE);
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);
}
}
I love this blog . It is so technical and so useful for me . This blog made my day . 😊
ReplyDeletethankyou so much 😊
Delete