How I would like the questions to be like;
When first question is shown, users don't enter the answer. Instead, user has to memorize the answer and with no delay, 2nd question is shown together with the first question still being shown. After every 2 questions, user can only enter the answer for both questions at the same time. However, I'm not sure how to show it in terms of codes. Also, is it possible to go the next question without having to click on the enter button? if it's possible, how do I that?
I want this to happen for the next subsequent questions. I'm still a beginner thus I need some help. I hope I am clear if not, do let me know.
These are my codes;
#Override
public void onClick(View view) {
if (view.getId() == R.id.enter) {
String answerContent = answerTxt.getText().toString();
if(firstQuestion == true)
{
buttonCounter = 1;
firstQuestion = false;
replayBtn.setEnabled(true);
chooseQuestion();
} else if (!answerContent.endsWith("?")) {
int enteredAnswer = Integer.parseInt(answerContent.substring(2));
int exScore = getScore();
if (enteredAnswer == answer){
buttonCounter = 1;
replayBtn.setEnabled(true);
scoreTxt.setText("Score: " + (exScore + 1));
response.setImageResource(R.drawable.tick);
response.setVisibility(View.VISIBLE);
} else {
setHighScore();
buttonCounter = 1;
replayBtn.setEnabled(true);
if (exScore == 0) {
scoreTxt.setText("Score:0");
} else {
scoreTxt.setText("Score: " + (exScore - 1));
}
response.setImageResource(R.drawable.cross);
response.setVisibility(View.VISIBLE);
}
chooseQuestion();
}
} else if (view.getId() == R.id.imageButton1) {
if (buttonCounter == 1) {
replayBtn.setEnabled(false);
Log.d("ins", "called");
}
buttonCounter = 0;
final int DELAY_MS = 1000;
MediaPlayer firstNum = MediaPlayer.create(this,
numberAudioList[operand1]);
firstNum.start();
pauseTimer = true;
firstNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer firstNum) {
firstNum.stop();
firstNum.reset();
firstNum.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer operatorAudio = MediaPlayer.create(this,
operatorAudioList[operator]);
operatorAudio.start();
pauseTimer = true;
operatorAudio.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer operatorAudio) {
operatorAudio.stop();
operatorAudio.reset();
operatorAudio.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer secondNum = MediaPlayer.create(this,
numberAudioList[operand2]);
secondNum.start();
pauseTimer = true;
secondNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer secondNum) {
secondNum.stop();
secondNum.reset();
secondNum.release();
pauseTimer = false;
}
});
if (leftTimeInMillisecondsGlobal == 0) {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(originalTimerTimeInMilliSeconds);
} else {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(leftTimeInMillisecondsGlobal);
}
startTimer();
} else if (view.getId() == R.id.clear) {
cancel = MediaPlayer.create(this, R.raw.cancel);
cancel.start();
cancel.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer cancel) {
cancel.stop();
cancel.reset();
cancel.release();
}
});
answerTxt.setText("= ?");
} else {
response.setVisibility(View.INVISIBLE);
int enteredNum = Integer.parseInt(view.getTag().toString());
if (answerTxt.getText().toString().endsWith("?"))
answerTxt.setText("= " + enteredNum);
else
answerTxt.append("" + enteredNum);
MediaPlayer num = MediaPlayer.create(this,
numberAudioList[enteredNum]);
num.start();
num.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer num) {
num.stop();
num.reset();
num.release();
}
});
}
}
private void setTimer(long timeLeft) {
totalTimeCountInMilliseconds = timeLeft;
timeBlinkInMilliseconds = 20 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (pauseTimer == true) {
leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
countDownTimer.cancel();
} else {
leftTimeInMillisecondsGlobal = leftTimeInMilliseconds;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
textViewShowTime.setTextAppearance(
getApplicationContext(), R.style.blinkText);
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink;
}
textViewShowTime.setText(String
.format("%02d", seconds / 60)
+ ":"
+ String.format("%02d", seconds % 60));
}
}
#Override
public void onFinish() {
Log.i("check", "check if enter onFinish() method");
setResults();
saveScore();
Log.i("check", "check if passes through");
}
}.start();
}
private int getScore() {
String scoreStr = scoreTxt.getText().toString();
return Integer
.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ") + 1));
}
private void chooseQuestion() {
answerTxt.setText("= ?"); //first reset the answer Text View
operator = random.nextInt(operators.length);
operand1 = random.nextInt(numberList.length);
operand2 = random.nextInt(numberList.length);
if (operator == 0) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while ((answer > 20));
answer = operand1 + operand2;
} else if (operator == 1) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while ((operand2 > operand1) || answer > 20);
answer = operand1 - operand2;
} else if (operator == 2) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while (operand1 > 12 || operand2 > 12 || (answer > 20));
answer = operand1 * operand2;
} else if (operator == 3) {
do {
operand1 = getOperand1();
operand2 = getOperand2();
answer = getAnswer();
} while (((((double) operand1 / (double) operand2) % 1 > 0)
|| answer > 20 || (operand1 == operand2) || (operand1 == 0) || (operand2 == 0)));
answer = operand1 / operand2;
}
final int DELAY_MS = 1000;
// moved to onClick()
MediaPlayer firstNum = MediaPlayer.create(this,
numberAudioList[operand1]);
pauseTimer = true;
firstNum.start();
firstNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer firstNum) {
firstNum.stop();
firstNum.reset();
firstNum.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer operatorAudio = MediaPlayer.create(this,
operatorAudioList[operator]);
pauseTimer = true;
operatorAudio.start();
operatorAudio.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer operatorAudio) {
operatorAudio.stop();
operatorAudio.reset();
operatorAudio.release();
pauseTimer = false;
}
});
try {
Thread.sleep(DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
MediaPlayer secondNum = MediaPlayer.create(this,
numberAudioList[operand2]);
pauseTimer = true;
secondNum.start();
secondNum.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer secondNum) {
secondNum.stop();
secondNum.reset();
secondNum.release();
pauseTimer = false;
}
});
int i = getScore();
if (i < 5) {
for (i = 0; i < 5; i++) {
question.setText(operand1 + " " + operators[operator] + " "
+ operand2); //display the question to the user
}
} else {
question.setText("Qns" + (i + 1));
}
// Moved to onClick()
if (leftTimeInMillisecondsGlobal == 0) {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(originalTimerTimeInMilliSeconds);
} else {
if (countDownTimer != null) {
countDownTimer.cancel();
}
setTimer(leftTimeInMillisecondsGlobal);
}
startTimer();
}
private int getOperand1() {
operand1 = 0;
do {
operand1 = random.nextInt(numberList.length);
} while (operand1 < 1 || operand1 > 20);
return operand1;
}
private int getOperand2() {
operand2 = 0;
do {
operand2 = random.nextInt(numberList.length);
} while (operand2 < 1 || operand2 > 20);
return operand2;
}
private int getAnswer() {
if (operator == 0) {
answer = operand1 + operand2;
}
else if (operator == 1) {
answer = operand1 - operand2;
}
else if (operator == 2) {
answer = operand1 * operand2;
}
else if (operator == 3) {
answer = operand1 / operand2;
}
return answer;
}
Is it possible to show the second question after first question ? yes it can be done. Use the handler. When you click the button send a message and show the first question. After that show a handler message with delayed time to show the second question.
mHandler.sendEmptyMessage(FIRST_QUESTION_ID);//Fist question willbe shown immediately
mHandler.sendEmptyMessageDelayed(SECOND_QUESTION_ID, 2000)// second question will be shown after 1st question after 2s
Related
weight_spinner= findViewById(R.id.weight_spinner);
ArrayAdapter<CharSequence> adapter_weight = ArrayAdapter.createFromResource(this,R.array.Weight,android.R.layout.simple_spinner_item);
adapter_weight.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weight_spinner.setAdapter(adapter_weight);
weight_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
weight_et.setHint("Weight(kg)");
weight_et1.setVisibility(View.GONE);
weight_et1.setEnabled(false);
weight_et.setEnabled(true);
if (height_spinner.getSelectedItemPosition()==0)
{
Thread t = new Thread(){
#Override
public void run() {
while (!isInterrupted()){
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
count++;
String Height = height_et.getText().toString().trim();
String Weight = weight_et.getText().toString().trim();
String age = age_et.getText().toString().trim();
String gender = gender_spinner.getSelectedItem().toString().trim();
if(Height.isEmpty()){
return;
}
if(Weight.isEmpty()){
result_tv.setText("");
return;
}
if (gender.isEmpty() || age.isEmpty()){
fat_tv.setText("");
age_et.setError("Please Enter Age");
age_et.requestFocus();
return;
}
//Get the user values from the widget reference
int Age = Integer.parseInt(age);
float weight = Float.parseFloat(Weight);
float height = Float.parseFloat(Height)/100;
//Calculate BMI value
float bmiValue = calculateBMI(weight, height);
DecimalFormat decimalFormat = new DecimalFormat("#.#");
final String rounded_bmivalue= decimalFormat.format(bmiValue);
//Calculate Ideal Weight
float fatpercent = 0.0f;
String rounded_fatpercent = null;
if (gender.equals("Male") && Age <18){
fatpercent = Childfatpercentage(bmiValue,Age,1);
rounded_fatpercent = decimalFormat.format(fatpercent);
}
else if (gender.equals("Male") && Age >=18){
fatpercent = Adultfatpercentage(bmiValue,Age,1);
rounded_fatpercent = decimalFormat.format(fatpercent);
}
else if (gender.equals("Female") && Age <18){
fatpercent = Childfatpercentage(bmiValue,Age,0);
rounded_fatpercent = decimalFormat.format(fatpercent);
}
else if (gender.equals("Female") && Age >=18){
fatpercent = Adultfatpercentage(bmiValue,Age,0);
rounded_fatpercent = decimalFormat.format(fatpercent);
}
//Define the meaning of the bmi value
final String bmiInterpretation = interpretBMI(bmiValue);
if (bmiValue<16) {
result_tv.setTextColor(Color.parseColor("#FF0000"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue >=16 && bmiValue<=17){
result_tv.setTextColor(Color.parseColor("#FF6347"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue>17 && bmiValue <18.5) {
result_tv.setTextColor(Color.parseColor("#9ACD32"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue>=18.5 && bmiValue <= 25) {
result_tv.setTextColor(Color.parseColor("#008000"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if ( bmiValue > 25 && bmiValue < 30) {
result_tv.setTextColor(Color.parseColor("#9ACD32"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue >= 30 && bmiValue <35){
result_tv.setTextColor(Color.parseColor("#FF4500"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue >= 35 && bmiValue <40){
result_tv.setTextColor(Color.parseColor("#FF6347"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
else {
result_tv.setTextColor(Color.parseColor("#FF0000"));
fat_tv.setTextColor(Color.parseColor("#FF0000"));
}
result_tv.setText(rounded_bmivalue + " - " + bmiInterpretation);
fat_tv.setText("Fat : "+rounded_fatpercent+" %");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
if (height_spinner.getSelectedItemPosition()==1){
Thread t = new Thread(){
#Override
public void run() {
while (!isInterrupted()){
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
count++;
String Height = height_et.getText().toString().trim();
String Weight = weight_et.getText().toString().trim();
String Height1 = height_et1.getText().toString().trim();
if(Height.isEmpty()){
return;
}
if(Weight.isEmpty()){
result_tv.setText("");
return;
}
if (Height1.isEmpty()){
return;
}
float weight = Float.parseFloat(Weight);
float feet = Float.parseFloat(Height);
float inches = Float.parseFloat(Height1);
float height = convertftandin(feet,inches)/100;
//Calculate BMI value
float bmiValue = calculateBMI(weight,height);
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String rounded_bmivalue= decimalFormat.format(bmiValue);
//Calculate Ideal Weight
String bmiInterpretation = interpretBMI(bmiValue);
if (bmiValue<16) {
result_tv.setTextColor(Color.parseColor("#FF0000"));
}
else if (bmiValue >=16 && bmiValue<=17){
result_tv.setTextColor(Color.parseColor("#FF6347"));
}
else if (bmiValue>17 && bmiValue <18.5) {
result_tv.setTextColor(Color.parseColor("#9ACD32"));
}
else if (bmiValue>=18.5 && bmiValue <= 25) {
result_tv.setTextColor(Color.parseColor("#008000"));
}
else if ( bmiValue > 25 && bmiValue < 30) {
result_tv.setTextColor(Color.parseColor("#9ACD32"));
}
else if (bmiValue >= 30 && bmiValue <35){
result_tv.setTextColor(Color.parseColor("#FF4500"));
}
else if (bmiValue >= 35 && bmiValue <40){
result_tv.setTextColor(Color.parseColor("#FF6347"));
}
else {
result_tv.setTextColor(Color.parseColor("#FF0000"));
}
result_tv.setText(rounded_bmivalue + " - " + bmiInterpretation);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
break;
case 1:
weight_et.setHint("Weight(lb)");
weight_et1.setVisibility(View.GONE);break;
case 2:
weight_et.setHint("st");
weight_et1.setVisibility(View.VISIBLE);
weight_et1.setHint("lb");break;
}
}
});
}
The condition "if (height_spinner.getSelectedItemPosition()==1)" inside case 0 of onItemSelected is not getting executed only the condition "if (height_spinner.getSelectedItemPosition()==0)" is bieng executed.
The condition "if (height_spinner.getSelectedItemPosition()==1)" inside case 0 of onItemSelected is not getting executed only the condition "if (height_spinner.getSelectedItemPosition()==0)" is bieng executed.
Please suggest an edit and solve my problem
This is because when you are in position 0 (aka case 0) :
#Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
weight_et.setHint("Weight(kg)");
weight_et1.setVisibility(View.GONE);
weight_et1.setEnabled(false);
weight_et.setEnabled(true);
if (height_spinner.getSelectedItemPosition()==0) {...}
the code: height_spinner.getSelectedItemPosition() is equal to 0 (in position 1 it will equal to 1 and so on)
so the condition: height_spinner.getSelectedItemPosition() == 1 will never be called in case 0
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();
This is how I am trying to execute my code.
private final class BoxSelect implements View.OnTouchListener
{
public boolean onTouch(View view, MotionEvent motionEvent)
{
setView(view);
setMotionEvent(motionEvent);
if (t1.getState() == Thread.State.NEW)
{
t1.start();
if (getHit() == false) {
t2.start();
}
}
return false;
}
}
I have two thread created called t1 and t2 which take the two runnable methods r1 and r1 as parameters:
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
R1 is defined as:
Runnable r1 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t1");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
View view1 = getView();
MotionEvent motionEvent1 = getMotionEvent();
public void whenCreate()
{
System.out.println("HERE t1");
hit = false;
boolean goToElse = true;
boolean hit2 = false;
boolean goToElse2 = true;
if (motionEvent1.getAction() == MotionEvent.ACTION_DOWN) {
for (int i = 0; i < ids.length; i++) {
for (int j = 0; j < ids.length; j++) {
String coord = b.getBoard()[i][j];
if (view == ids[i][j]) {
System.out.println("ATTACKING " + b.getCompTempBoard()[i][j]);
player.basicAttack(b.getBoard(), coord, ai);
}
if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("HIT")) {
System.out.println("Hit GUI");
if (ids[i][j].getBackground().equals(hitTarget)) {
hit = true;
goToElse = false;
} else {
ids[i][j].setBackgroundDrawable(hitTarget);
System.out.println("ert 1 " + b.getCompTempBoard()[i][j]);
playerCount++;
if (playerCount == 10) {
player.endGame();
b.incrementPlayerCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU WIN :)\nScore is:\nPlayer: " + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
hit = true;
goToElse = false;
}
} else if (view == ids[i][j] && b.getCompTempBoard()[i][j].equalsIgnoreCase("MISS")) {
System.out.println("MISS GUI 1");
if (ids[i][j].getBackground().equals(missTarget)) {
hit = true;
goToElse = false;
} else {
System.out.println("MISS GUI");
ids[i][j].setBackgroundDrawable(missTarget);
System.out.println("ert 2 " + b.getCompTempBoard()[i][j]);
hit = true;
goToElse = true;
}
}
if (goToElse == true) {
hit = false;
System.out.println("MISS PLAYER GUI");
view.setBackgroundDrawable(missTarget);
}
}
}
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
}
}
};
and R2 is:
Runnable r2 = new Runnable() {
public void run() {
System.out.println("ENTERING RUN t2");
try {
TimeUnit.NANOSECONDS.sleep(1);
System.out.println("HERE 2");
class BoxSelect implements View.OnTouchListener {
Drawable hitTarget = getResources().getDrawable(R.drawable.hit);
Drawable missTarget = getResources().getDrawable(R.drawable.miss);
public boolean onTouch(View view, MotionEvent motionEvent) {
System.out.println("HERE t2");
if (hit == false) {
System.out.println("SLEEPING 2");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("COMPUTERS TURN");
ai.advancedAttack(b.getBoard(), ai.getRandomCoordinate_For_Attacking_6x6(), player);
System.out.println("First attack: " + ai.getFirstCoord());
boolean goAgain = true;
while (goAgain == true) {
for (int w = 0; w < ids2.length; w++) {
for (int y = 0; y < ids2.length; y++) {
if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("HIT")) {
System.out.println("DR 1");
ids2[w][y].setBackgroundDrawable(hitTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
System.out.println("Next: " + ai.getFirstCoord());
ai.advancedAttack(b.getBoard(), ai.getFirstCoord(), player);
System.out.println("After attack in loop");
goAgain = true;
CompCount++;
if (CompCount == 10) {
b.incrementCompCount();
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("YOU LOSE :(\n" + "Score is:\n" + "Player: \n" + b.getPlayerWinCount() + "\nComputer: " + b.getCompWinCount());
builder1.setCancelable(true);
builder1.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(AttackShips6.this, MainMenu.class);
startActivity(intent);
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
for (int k = 0; k < ids2.length; k++) {
for (int r = 0; r < ids2.length; r++) {
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getCompTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getCompTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getCompTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids[k][r].setBackgroundDrawable(missTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("HIT") || b.getTempBoard()[k][r].equalsIgnoreCase("NULL NOT HIT")) {
ids2[k][r].setBackgroundDrawable(hitTarget);
}
if (b.getTempBoard()[k][r].equalsIgnoreCase("MISS") || b.getTempBoard()[k][r].equalsIgnoreCase(b.getBoard()[k][r])) {
ids2[k][r].setBackgroundDrawable(missTarget);
}
}
}
}
} else if (b.getBoard()[w][y].equalsIgnoreCase(ai.getFirstCoord()) && b.getTempBoard()[w][y].equalsIgnoreCase("MISS")) {
System.out.println("DR 2");
ids2[w][y].setBackgroundDrawable(missTarget);
ai.setFirstCoord(ai.getNextCoordToAttack());
goAgain = false;
}
}
}
}
}
return hit;
}
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
System.out.println("IN CATCH");
}
System.out.println("END");
}
};`
I originally had these two together as one block, but separated it as I wish to pause thread 2 from occurring for one second after thread 2.
The problem I am having is that the BoxSelect class is not getting executed inside the R1 and R2 and so none of the code is executing. Any help on this matter would be appreciated!
Currently, I am making an android app that is going to be a very simple memory game where 1 random button is going to be highlighted, then the user must click the button that was highlighted after the button goes back to normal. If the user gets the button correct the original button that was highlighted the first time will light up, then another random button will light up after just like the first time and they have to click them in order. For further clarification if your unsure its kind of like Simon (The game).
Currently the game is just going to the next random button instead of repeating AND THEN going to a new one and i'm unsure how to change that. Any help would be greatly appreciated!
package com.MakeItMobile.fixmymemory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainScreen extends Activity implements OnClickListener {
Button buttonRed, buttonYellow, buttonOrange, buttonBlack, buttonGreen,
buttonPurple, buttonPink, buttonLime, buttonDarkBlue;
Random randNumber;
List<Integer> whichButton;
int userInput[] = {};
int counter = 0;
int compareCounter = 0;
int n = 0;
Boolean yourTurn = false;
Boolean aiTurn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
//Getting the buttons
buttonRed = (Button) findViewById(R.id.buttonRed);
buttonYellow = (Button) findViewById(R.id.buttonYellow);
buttonOrange = (Button) findViewById(R.id.buttonOrange);
buttonBlack = (Button) findViewById(R.id.buttonBlack);
buttonGreen = (Button) findViewById(R.id.buttonGreen);
buttonPurple = (Button) findViewById(R.id.buttonPurple);
buttonPink = (Button) findViewById(R.id.buttonPink);
buttonLime = (Button) findViewById(R.id.buttonLime);
buttonDarkBlue = (Button) findViewById(R.id.buttonDarkBlue);
//Setting them clickable
buttonRed.setOnClickListener(this);
buttonYellow.setOnClickListener(this);
buttonOrange.setOnClickListener(this);
buttonBlack.setOnClickListener(this);
buttonGreen.setOnClickListener(this);
buttonPurple.setOnClickListener(this);
buttonPink.setOnClickListener(this);
buttonLime.setOnClickListener(this);
buttonDarkBlue.setOnClickListener(this);
//Giving them a tag for easier comparison in onClick
buttonRed.setTag(1);
buttonYellow.setTag(2);
buttonOrange.setTag(3);
buttonBlack.setTag(4);
buttonGreen.setTag(5);
buttonPurple.setTag(6);
buttonPink.setTag(7);
buttonLime.setTag(8);
buttonDarkBlue.setTag(9);
//Showing a would you like to play dialog
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to begin?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
// Main loop
public void whenStarted() {
if (aiTurn) {
whichButton = new ArrayList<Integer>();
repeatBack();
randomNumber();
n = randomNumber();
if (n == 1) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 2) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 3) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 4) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 5) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 6) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 7) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 8) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 9) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
whichButton.add(n);
yourTurn = true;
} else if (yourTurn) {
}
}
// Repeating back what buttons were clicked each turn
public void repeatBack() {
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 2) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 3) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 4) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 5) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 6) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 7) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 8) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 9) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
System.out.println("Which button size and number is "
+ whichButton.size());
System.out.println(i);
}
}
// For repeating back the buttons
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delayRepeat(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(endID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(endID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(endID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
for (int i = 0; i < whichButton.size(); i++) {
// TODO Auto-generated method stub
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue
.setBackgroundResource(newStartID);
}
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
// creating a blinking color button for each specific random number
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delay(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(endID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (n == 7) {
buttonPink.setBackgroundResource(endID);
} else if (n == 8) {
buttonLime.setBackgroundResource(endID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (n == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (n == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(newStartID);
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
//Used to generate a different random number each time
public int randomNumber() {
randNumber = new Random();
int n = randNumber.nextInt(9) + 1;
return n;
}
// On click for when they click each button
// Buttons are set to specific tags in the onCreate
// Checks if the tag is equal to what the output of whichButton.get(x) is
// If it isn't they fail
public void onClick(View v) {
// TODO Auto-generated method stub
int tag = (Integer) v.getTag();
for (int x = 0; x < whichButton.size(); x++) {
if (tag == 1 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 2 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 3 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 4 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 5 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 6 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 7 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 8 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 9 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else {
aiTurn = false;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
aiTurn = true;
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You failed, would you like to play again?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
}
}
}
In your onClick(...) handler you're calling whenStarted() each time.
In the whenStarted() method you do this...
whichButton = new ArrayList<Integer>();
...which basically sets whichButton to a new empty ArrayList.
Move that line elsewhere in your code so it only initializes the ArrayList at the start of each game and not at every turn.
The way you are going about this is overcomplicated. Instead of using else-if blocks to pick the button from a random number, put the buttons in a list or array and get a random buttons like this:
private final Button[] buttons = new Button[] {
findViewById(R.id.buttonRed),
findViewById(R.id.buttonYellow),
/* etc, etc */
};
public Button getRandomButton() {
return buttons[new Random().nextInt(buttons.length)];
}
The reason the sequence isn't playing back correctly is because you aren't storing the sequence as an instance variable. The easiest way to store the sequence would be to store a list of integers. The integers would represent the position of the buttons in your array and you would add a new entry every turn.
private final List<Integer> currentSequence = new ArrayList<>();
public void nextTurn() {
// first play the previous buttons
for (int i : currentSequence) {
Button b = buttons[i];
// then play it here
}
// play a new button and add it to the sequence
Button randomButton = getRandomButton();
// play it here
currentSequence.add(Arrays.asList(buttons).indexOf(randomButton)));
}
Then when you're done with the current game just remember to clear the sequence with.
currentSequence.clear();
I have a trivia game that is 10 timed questions. A wrong answer is supposed to output 0 points. A correct answer is supposed to output the remaining of the 20,000 milliseconds converted to a 100 point scale.
Right now the game works on the first game. Then, if the user keeps playing for a second time, the points for each question becomes incorrect. For example, incorrect answers begin to have a variety of points from 1 to 100 and also correct answers sometimes have 0 points and also sometimes wrong point totals. So I am guessing some variable is possibly not resetting on the second game so it is causing the points to be a little off.
I posted all the code that deals with the algorithm. My question is how I can get this code to output the correct answer no matter how many times the user plays before closing the app.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
AdView adView;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
tracker.sendView("/QuestionView - Started Quiz");
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
return pointsPerQuestion;
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
loadQuestion();
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = millisUntilFinished / 200;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
Here is a Question object:
exodus.add(new Question("6th", "3rd", "5th", "4th", 2, "Name that plague: All livestock dies", -1, "Exodus 9:6"));
In my Results class, which is where the points per question is displayed, this is the line that displays the points:
scoreTV.setText("You received " + QuestionView.getPointsPerQuestion().get(x) + " out of a possible 100 points.");
Everything else is pretty much in my QuestionView above. Let me know if you still need something else.
First 3 Strings are answers A (index 0), B (index 1), C (index 2) and D (index 3). The first int is the correct answer. The 5th String is the question. The second int is set to the answer selected by user during quiz. Last String is the bible verse where the answer is found.