package com.example.chirag.example;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView TV;
Button upbutton;
Button downbutton;
TextView score;
String n1;
int bool=0;
int a;
int b;
int sc=0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView TV = (TextView)findViewById(R.id.TV);
TextView score = (TextView)findViewById(R.id.score);
Button upbutton = (Button) findViewById(R.id.upbutton);
Button downbutton = (Button) findViewById(R.id.downbutton);
Button start = (Button) findViewById(R.id.start);
n1 = generate();
TV.setText(n1);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start();
}
});
}
String generate()
{
TextView TV = (TextView)findViewById(R.id.TV);
int n = new Random().nextInt(20);
String s = String.valueOf(n);
return s;
}
void start() {
Runnable myRunnable = new Runnable() {
@Override
public void run()
{while (bool == 0) {
final TextView TV = (TextView) findViewById(R.id.TV);
final TextView score = (TextView) findViewById(R.id.score);
Button upbutton = (Button) findViewById(R.id.upbutton);
Button downbutton = (Button) findViewById(R.id.downbutton);
Button start = (Button) findViewById(R.id.start);
String n2 = generate();
TV.setText(n2);
a = Integer.valueOf(n1.toString());
b = Integer.valueOf(n2.toString());
if (a > b) {
downbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String n3 = generate();
TV.setText(n3);
a = b;
b = Integer.valueOf(n3.toString());
score.setText("Score" + (sc + 1));
}
});
upbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TV.setText("Game Over");
bool = 1;
}
});
} else {
upbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String n3 = generate();
TV.setText(n3);
a = b;
b = Integer.valueOf(n3.toString());
score.setText("Score" + (sc + 1));
}
});
downbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TV.setText("Game Over");
bool = 1;
}
});
}
}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}
I have put the code in a runnable. The logic seems correct but it doesn't work. the generate method creates a new number and displays it in 'TV'. when start is clicked, a new number is generated and the second number is compared with the first. if the correct button( up or down) is pressed, the score is increased and the process is continued. "Game Over" if the wrong button is clicked