I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];
Related
I have 2 activities, on the second one i read and make some changes to a local JSON file and it works for everything i need but when i go to the mainActivity and then come back to the second one it seems that the file just resets and looks like i didn't apply any changes. I don't know what to do...
I hope there is something to do here...
Here's the code for the second activity:
package com.example.plasticopedia;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class calculator extends AppCompatActivity {
int buttonClicked = MainActivity.buttonClicked;
Button plus;
Button minus;
public int amountTrash;
/public boolean openingActivity = true;
public boolean clickedPlus = true;/
public int clickedPlus;
String firstParagraph;
String secondParagraph;
String thirdParagraph;
String fourthParagraph;
String fifthParagraph;
String[] nameArray = {"BAG", "BOTTLE", "STRAW", "DETERGENT_CONTAINER", "BOTTLE_CAP", "FOOD_CONTAINER", "CUTLERY", "CRISPS_PACKET"};
String[] titleArray = {"Plastic Bag", "Water Bottle", "Straw", "Detergent Container", "Bottle Cap", "Food Container", "Cutlery", "Crisps Packet"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
getJSON();
changeImageTitleText();
plus = findViewById(R.id.plus);
minus = findViewById(R.id.minus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickedPlus = 1;
getJSON();
clickedPlus = 0;
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickedPlus = 2;
getJSON();
clickedPlus = 0;
}
});
}
public void changeImageTitleText(){
TextView title = findViewById(R.id.title);
TextView P1 = findViewById(R.id.firstParagraph);
TextView P2 = findViewById(R.id.secondParagraph);
TextView P3 = findViewById(R.id.thirdParagraph);
TextView P4 = findViewById(R.id.fourthParagraph);
TextView P5 = findViewById(R.id.fifthParagraph);
for(int i = 0; i < titleArray.length; i++){
if(buttonClicked == i){
title.setText(titleArray[i]);
P1.setText(firstParagraph);
P2.setText(secondParagraph);
P3.setText(thirdParagraph);
P4.setText(fourthParagraph);
P5.setText(fifthParagraph);
changeImage(i);
}
}
}
private void changeImage(int i){
Button image = findViewById(R.id.image);
if(i == 0){
image.setBackgroundResource(R.drawable.button_plastic_bag);
} else if (i == 1){
image.setBackgroundResource(R.drawable.button_plastic_bottle);
} else if (i == 2){
image.setBackgroundResource(R.drawable.button_plastic_straw);
} else if (i == 3){
image.setBackgroundResource(R.drawable.button_plastic_detergent_container);
} else if (i == 4){
image.setBackgroundResource(R.drawable.button_plastic_bottle_cap);
} else if (i == 5){
image.setBackgroundResource(R.drawable.button_plastic_food_container);
} else if (i == 6){
image.setBackgroundResource(R.drawable.button_plastic_cutlery);
} else if (i == 7){
image.setBackgroundResource(R.drawable.button_plastic_crisps_packet);
}
}
public void getJSON(){
String json;
try{
InputStream is = getAssets().open("plastic.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
JSONArray jsonArray = new JSONArray(json);
if(clickedPlus == 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
for (int j = 0; j < nameArray.length; j++) {
if (buttonClicked == j) {
if (obj.getString("name").equals(nameArray[j])) {
Log.e("TrashOpening", "" + amountTrash);
//((JSONObject)jsonArray.get(i)).put("amountTrash", "20");
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
Log.e("TrashOpeningSecond", "" + amountTrash);
firstParagraph = obj.getString("1");
secondParagraph = obj.getString("2");
thirdParagraph = obj.getString("3");
fourthParagraph = obj.getString("4");
fifthParagraph = obj.getString("5");
}
}
}
}
}
if(clickedPlus == 1){
//changing the values
for(int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
for(int j = 0; j < nameArray.length; j++){
if(buttonClicked == j){
if(obj.getString("name").equals(nameArray[j])){
amountTrash ++;
Log.e("TrashClickedPlus", "" + amountTrash);
((JSONObject)jsonArray.get(i)).put("amountTrash", "" + amountTrash);
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
Log.e("TrashAfterChangingJSON", "" + Integer.parseInt(obj.getString("amountTrash")));
}
}
}
}
}else if(clickedPlus == 2){
for(int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
for(int j = 0; j < nameArray.length; j++){
if(buttonClicked == j){
if(obj.getString("name").equals(nameArray[j])){
if(amountTrash > 0){
amountTrash --;
((JSONObject)jsonArray.get(i)).put("amountTrash", "" + amountTrash);
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
}
}
}
}
}
}
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
}
}
Assets are read only por accomplish that use shared preferences or a local database
I have a tic tac toe application which is only one little step away from being perfect. Basically the game works perfect during game play, the play makes a move by placing an X, then the computer makes a move a couple of seconds earlier placing their O and then it's back to the players move and then after their move a couple of seconds later the computer moves and etc.
The only issue I have which I cannot seem to figure out is when the game board resets. Basically when the winning move is made, we do not see the winning move, the board is reset, toast message is displayed stating who has won and if it is computers move first then their first move is made and this all happens at the same time. For the user they will be like what is going on how was the game won as it all happened in a flash.
I need to make a slight adjust so that the following happens:
1: Player sees the winning move either if it's their move or computers
2:
After seeing the winning move then the game board resets and the toast message appears stating who won or a draw
I don't mind the computer already making the first move already after the game board has reset, but the other two points I believe needs to be addressed.
Below is my code but I cannot seem to figure out how to ensure the above two points are reached when trying to manipulate the code:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
private TextView textViewFooterTitle;
Button selectButton;
Random random = new Random();
boolean firstComputerMove = false;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player1);
Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/ConcertOne-Regular.ttf");
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
textViewFooterTitle = findViewById(R.id.footer_title);
textViewPlayerOne.setTypeface(customFont);
textViewPlayerTwo.setTypeface(customFont);
textViewFooterTitle.setTypeface(customFont);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setTypeface(customFont);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setTypeface(customFont);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
turnsCount++;
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
isGameOver();
}
}
public void isGameOver() {
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
if (!playerOneMove) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
computerMove();
}
}, 1000);
}
}
}
private void computerMove() {
String[][] field = new String[3][3];
List<Button> emptyButtons = new ArrayList<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
emptyButtons.add(buttons[i][j]);
}
}
}
//IS COMPUTER GOING FIRST
if (firstComputerMove == true){
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
else {
//TAKE MIDDLE SQUARE IF NOT TAKEN
if (field[1][1].equals("")) {
selectButton = buttons[1][1];
}
//FIRST ROW ACROSS
else if (field[0][0] != "" && field[0][0].equals(field[0][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[0][0] != "" && field[0][0].equals(field[0][2])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
} else if (field[0][1] != "" && field[0][1].equals(field[0][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//SECOND ROW ACROSS
else if (field[1][0] != "" && field[1][0].equals(field[1][1])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][0] != "" && field[1][0].equals(field[1][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[1][2])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
}
//THIRD ROW ACROSS
else if (field[2][0] != "" && field[2][0].equals(field[2][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[2][0] != "" && field[2][0].equals(field[2][2])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[2][1] != "" && field[2][1].equals(field[2][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//FIRST COLUMN DOWN
else if (field[0][2] != "" && field[0][2].equals(field[1][2])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[0][2] != "" && field[0][2].equals(field[2][2])
&& field[1][2].equals("")) {
selectButton = buttons[1][2];
} else if (field[1][2] != "" && field[1][2].equals(field[2][2])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
}
//SECOND COLUMN DOWN
else if (field[0][1] != "" && field[0][1].equals(field[1][1])
&& field[2][1].equals("")) {
selectButton = buttons[2][1];
} else if (field[0][1] != "" && field[0][1].equals(field[2][1])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[1][1] != "" && field[1][1].equals(field[2][1])
&& field[0][1].equals("")) {
selectButton = buttons[0][1];
}
//THIRD COLUMN DOWN
else if (field[0][0] != "" && field[0][0].equals(field[1][0])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
} else if (field[0][0] != "" && field[0][0].equals(field[2][0])
&& field[1][0].equals("")) {
selectButton = buttons[1][0];
} else if (field[2][0] != "" && field[2][0].equals(field[1][0])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
}
//DIAGAONAL TOP RIGHT BOTTOM LEFT
else if (field[2][0] != "" && field[2][0].equals(field[0][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[2][0] != "" && field[2][0].equals(field[1][1])
&& field[0][2].equals("")) {
selectButton = buttons[0][2];
} else if (field[1][1] != "" && field[1][1].equals(field[0][2])
&& field[2][0].equals("")) {
selectButton = buttons[2][0];
}
//DIAGAONAL TOP LEFT BOTTOM RIGHT
else if (field[0][0] != "" && field[0][0].equals(field[2][2])
&& field[1][1].equals("")) {
selectButton = buttons[1][1];
} else if (field[0][0] != "" && field[0][0].equals(field[1][1])
&& field[2][2].equals("")) {
selectButton = buttons[2][2];
} else if (field[1][1] != "" && field[1][1].equals(field[2][2])
&& field[0][0].equals("")) {
selectButton = buttons[0][0];
} else {
selectButton = emptyButtons.get(random.nextInt(emptyButtons.size()));
}
}
selectButton.setText("O");
selectButton.setTextColor(playerO);
firstComputerMove = false;
turnsCount++;
isGameOver();
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
firstComputerMove = true;
computerMove();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
playerOneMove = !playerOneMove;
switchPlayerTurn();
if (!playerOneMove){
firstComputerMove = true;
computerMove();
}
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("PLAYER 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("COMPUTER: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
I would recommend that you use Thread.sleep if a player wins to give time to show the final move.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resetBoard();
firstComputerMove = true;
computerMove();
You could also incorporate an AlertDialog to ask the user to play again after pause and the final move
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Play again?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Play Again
resetBoard();
firstComputerMove = true;
computerMove();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Exit Game
}
})
.show();
I have a functionality for tic tac toe where basically when the player clicks a button to place their X, the computer's O is placed at the same time within the first empty button available.
However what I prefer is after the player places an X, the computer places their O on the first empty button available, not the same time. Is there a way to get the computer to click on an empty button by itself?
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
computerMove();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
UPDATE
Whole code snippet:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player2);
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
playerOneMove = false;
computerMove();
}
turnsCount++;
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
switchPlayerTurn();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("Player 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("Computer: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
Try this
button.performClick();
UPDATE after going through op's code:
Your code was perfectly fine but had one small bug. In your computerMove() function, you had compared strings using == which is prone to cause problems in Java. I replaced it with String.equals(String) and played a game. Works fine.
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.
My GameView class:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
int turns = 0;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
int cellContent;
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
turns++;
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getTurns() {
return turns;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
GameView mGameView = new GameView(getApplicationContext());
this.turns = mGameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void AddData() {
boolean isInserted = myDb.insertData(Integer.toString(turns));
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
}
In MainAcivity, inside setTurns()
Replace this
this.turns = mGameView.turns; //you can't access this variable directly
with
this.turns = mGameView.getTurns(); // Calling the public method getTurns()
please see this answer for explanation about Access modifiers in Java
There are two ways to fix this.
1. Preferred way:
Add a new Method in GameView class
public int getTurns() {
return turns;
}
And use this method where you want to access turns like:
this.turns = mGameView.getTurns();
2. Bad way:
Make turns variable public.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Ok so here is my problem. I am working on a trivia game that uses a question counter to display 10 questions and once that happens it calls the finalscore class. I have implemented a timer that resets for every question and if time runs up it proceeds to the next question. However if nothing is clicked on the final question it will keep looping back to the finalscore class even after starting a new game.
public class game extends Activity implements OnClickListener {
// int[] anArray;
int[] anArray2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int numberOfQuestionsDisplayedCounter = 0;
int nextOrFinishValue = 0;
int randomValueZeroToThree = 0;
int randomValue0to29 = 0;
boolean alreadyDisplayQuestion = false;
boolean validQuestionNumber = false;
boolean rightButton1 = false;
boolean rightButton2 = false;
boolean rightButton3 = false;
boolean rightButton4 = false;
String questionFromDatabase;
String answer1FromDatabase;
String answer2FromDatabase;
String answer3FromDatabase;
String answer4FromDatabase;
String displayedQuestionFromDatabase = "question ";
String displayedAnswer1FromDatabase = "answer1a ";
String displayedAnswer2FromDatabase = "answer2a ";
String displayedAnswer3FromDatabase = "answer3a ";
String displayedAnswer4FromDatabase = "answer4a ";
int categoryId = 0;
int questionId = 0;
int currentScore = 0;
private CountDownTimer mCountDown;
public void onCreate(Bundle savedInstanceState) {
int randomInt = 1;
super.onCreate(savedInstanceState);
categoryId = com.triviagame.Trivia_Game.categoryIdInMainMenu;
// System.out.println("categoryID =" + categoryId);
setContentView(R.layout.displayquestion);
// gathers question and answers from database
gatherInfoBeforePopulating(); // includes generating random number
// between getting info from database 1
// to 30
// displays question, answers, score
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
// Sets buttons and listers for the buttons with the 4 possible answers
View answer1button = findViewById(R.id.answer1button);
answer1button.setOnClickListener(this);
View answer2button = findViewById(R.id.answer2button);
answer2button.setOnClickListener(this);
View answer3button = findViewById(R.id.answer3button);
answer3button.setOnClickListener(this);
View answer4button = findViewById(R.id.answer4button);
answer4button.setOnClickListener(this);
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
// Displays question, answers, score
public void populateWithQuestionInfo(String question, String answer1,
String answer2, String answer3, String answer4,
int nextQuestionOrFinish) {
// populate the question label
TextView questionLabel = (TextView) findViewById(R.id.question);
questionLabel.setText(question);
// populate answer1
Button buttonAnswer1 = (Button) findViewById(R.id.answer1button);
buttonAnswer1.setText(answer1);
// populate answer2
Button buttonAnswer2 = (Button) findViewById(R.id.answer2button);
buttonAnswer2.setText(answer2);
// populate answer3
Button buttonAnswer3 = (Button) findViewById(R.id.answer3button);
buttonAnswer3.setText(answer3);
// populate answer4
Button buttonAnswer4 = (Button) findViewById(R.id.answer4button);
buttonAnswer4.setText(answer4);
numberOfQuestionsDisplayedCounter++;
}
// Generates a random number between 0 and 3 to be used to display the
// possible answers randomly
int RandomGeneratorZeroToThree() {
int randomInt = 0;
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(4);
}
return randomInt;
}
// Generates a random number between 0 and 29 to be used to select the
// question to be displayed
int RandomGenerator0To29() {
int randomInt2 = 0;
Random randomGenerator2 = new Random();
for (int idx2 = 1; idx2 <= 10; ++idx2) {
randomInt2 = randomGenerator2.nextInt(30);
}
return randomInt2;
}
// returns true if the question has already been displayed
// returns false if the question has not been already displayed
boolean questionsAlreadyDisplayed(int randomValue0to29) {
for (int i = 0; i < 10; i++) {
if (anArray2[i] == randomValue0to29) {
return true; // question already displayed
}
}
anArray2[numberOfQuestionsDisplayedCounter] = randomValue0to29; // questionId
// added
// to
// array
// of
// displayed
// questions
return false; // random number can be used as it has been used already
}
// Connects to the database to gather the question and 4 possible answers.
// Uses DataBaseHelper class
void getInfoFromDatabase(int categoryId, int questionId) {
DataBaseHelper myDbHelper = new DataBaseHelper(
this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
questionFromDatabase = myDbHelper.getQuestion(categoryId,
questionId);
displayedQuestionFromDatabase = questionFromDatabase;
System.out
.println("questionFromDatabase = " + questionFromDatabase);
answer1FromDatabase = myDbHelper.getCorrectAnswer(categoryId,
questionId); // correct answer from database
System.out.println("correct answer from db = "
+ answer1FromDatabase);
answer2FromDatabase = myDbHelper.getWrongAnswer1(categoryId,
questionId);
answer3FromDatabase = myDbHelper.getWrongAnswer2(categoryId,
questionId);
answer4FromDatabase = myDbHelper.getWrongAnswer3(categoryId,
questionId);
myDbHelper.close();
} catch (SQLException sqle) {
System.out.println("Errored out");
try {
throw sqle;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// If the player selects the right answer this method is called to increase
// the score by 10 points
void increaseScore() {
currentScore = currentScore + 10;
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// If the player selects the wrong answer this method is called to decrease
// the score by 10 points
void decreaseScore() {
currentScore = currentScore - 10;
// score can't go below 0
if (currentScore < 0) {
currentScore = 0;
}
com.triviagame.Trivia_Game.finalScore = currentScore;
}
// Displays the current scores on the activity
void displayScore() {
TextView yourScore = (TextView) findViewById(R.id.yourscore);
String currentScoreText;
currentScoreText = Integer.toString(currentScore);
yourScore.setText(currentScoreText);
}
void resetTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
final TextView myCounter = (TextView) findViewById(R.id.tv);
mCountDown = new CountDownTimer(21000, 1000) {
#Override
public void onFinish() {
questionCheck();
resetTimer();
}
#Override
public void onTick(long millisUntilFinished) {
myCounter.setText("Time left: "
+ String.valueOf(millisUntilFinished / 1000));
}
}.start();
}
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
void questionCheck() {
if (nextOrFinishValue == 1) {
Intent e = new Intent(this, finalscore.class);
startActivity(e);
cancelTimer();
}
if (nextOrFinishValue == 0) { // If 10 questions have not been displayed
// yet, display the next question
gatherInfoBeforePopulating();
displayScore();
populateWithQuestionInfo(displayedQuestionFromDatabase,
displayedAnswer1FromDatabase, displayedAnswer2FromDatabase,
displayedAnswer3FromDatabase, displayedAnswer4FromDatabase,
nextOrFinishValue);
}
}
// gathers question and answers from database
void gatherInfoBeforePopulating() {
categoryId = Trivia_Game.getCategoryIdInMainMenu();
// Loop until a valid questionId that hasn't been used is obtained
while (validQuestionNumber == false) {
randomValue0to29 = RandomGenerator0To29();
System.out.println("random30 in onClick = " + randomValue0to29);
alreadyDisplayQuestion = questionsAlreadyDisplayed(randomValue0to29);
if (alreadyDisplayQuestion == true) {
System.out
.println("question number already displayed looking for a non displayed question");
}
if (alreadyDisplayQuestion == false) {
System.out.println("question not displayed yet");
validQuestionNumber = true;
}
}
validQuestionNumber = false;
alreadyDisplayQuestion = false;
questionId = randomValue0to29; // sets the valid random generated number
// to the questionID
// connect to database to gather the question and answers
getInfoFromDatabase(categoryId, questionId);
// Calls random number from 0 to 3 to determine which button will
// display the correct answer
randomValueZeroToThree = RandomGeneratorZeroToThree();
System.out.println("random4 in onClick = " + randomValueZeroToThree);
// Sets the order according to the button that is to display the correct
// answer
switch (randomValueZeroToThree) {
case 0:
displayedAnswer1FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = true;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
break;
case 1:
displayedAnswer2FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = true;
rightButton3 = false;
rightButton4 = false;
break;
case 2:
displayedAnswer3FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer2FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = true;
rightButton4 = false;
break;
case 3:
displayedAnswer4FromDatabase = answer1FromDatabase; // correct
// answer
displayedAnswer1FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer2FromDatabase = answer4FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = true;
break;
default:
displayedAnswer1FromDatabase = answer4FromDatabase; // no correct
// answer
displayedAnswer2FromDatabase = answer2FromDatabase;
displayedAnswer3FromDatabase = answer3FromDatabase;
displayedAnswer4FromDatabase = answer1FromDatabase;
rightButton1 = false;
rightButton2 = false;
rightButton3 = false;
rightButton4 = false;
}
// After the 9th question is displayed, the nextOfFinishValue should be
// set to 1 so the button displayes Finish instead of Next
if (numberOfQuestionsDisplayedCounter < 9) {
nextOrFinishValue = 0;
} else {
nextOrFinishValue = 1;
}
}
// Listeners for the 4 buttons with answers and the Next or Finish buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.answer1button:
if (rightButton1 == true) {
increaseScore();
resetTimer();
// put here to change color of button
} else {
decreaseScore();
resetTimer();
// change button to red
}
questionCheck();
break;
case R.id.answer2button:
if (rightButton2 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer3button:
if (rightButton3 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
case R.id.answer4button:
if (rightButton4 == true) {
increaseScore();
resetTimer();
} else {
decreaseScore();
resetTimer();
}
questionCheck();
break;
}
}
#Override
protected void onResume() {
super.onResume();
music.play(this, R.raw.musicbackground); // play background music
}
#Override
protected void onPause() {
super.onPause();
music.stop(this); // stop playing background music
}
}
mCountdown is never null so change your code
void cancelTimer() {
if (mCountDown != null) {
mCountDown.cancel();
}
}
To
void cancelTimer() {
mCountDown.cancel();
}