simon says game java android - java

I'm a beginner on java and android, and now I'm trying to program the "simon says" game to learn this language, but this doesn't works fine. :-(
The first and most important problem: When I try to show the sequence of colors [number 1 to 4] stored in the array seq[] with the method seq_show().... ho call but_show(x) to change the background color of each button... But I can't see the change of the backgroud color of the corresponding linearlayout...
Also I has erased the READY? source code button because is not closed before seq_show().
I do not understand this java's way to program... is not line by line, step by step... I thing is by threads and I do not understand where the pointer of the executed code is. :-(
Can someone help me ?
Then, in the method seq_input() I catch the click's on the LinearLayout... and I thing this runs fine... but I need to solve the seq_show() problem first to continue with the program.
thanks !!
public class MainActivity extends Activity {
public LinearLayout l1, l2, l3, l4;
public GestureDetector gd1,gd2,gd3,gd4;
public static int seq[] = new int[25];
public int seq_pos = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array pos[] amb 25 clics del joc simon
//
for (int i = 0; i < 25; i++) {
seq[i] = (int) (Math.random() * 4) + 1;
}
// declaració 4 onClickListener
//
l1 = (LinearLayout) findViewById(R.id.layout_green);
l1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
seq_input(1);
}
});
l2 = (LinearLayout) findViewById(R.id.layout_red);
l2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
seq_input(2);
}
});
l3 = (LinearLayout) findViewById(R.id.layout_yellow);
l3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
seq_input(3);
}
});
l4 = (LinearLayout) findViewById(R.id.layout_blue);
l4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
seq_input(4);
}
});
seq_show(0);
}
// Mostra la sequencia de botons a pulsar
//
public void seq_show(int seq_end) {
for (int i=0; i <= seq_end; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but_show(seq[i]);
}
}
// Espera la pulsació de la sequencia de botons
//
public void seq_input(int but_pushed){
if (seq[seq_pos] == but_pushed) {
seq_pos++;
but_show(seq[but_pushed]);
seq_show(seq_pos);
}else{
MediaPlayer sound = MediaPlayer.create(this, R.raw.wrong);
sound.start();
new Handler().postDelayed(new Runnable() {
public void run() {
}
}, 1000);
}
}
// Canvia el color i emet un so al botó but_num
//
public void but_show(int but_num) {
if (but_num == 1) {
l1.setBackgroundResource(color.green_on);
MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_green);
sound.start();
new Handler().postDelayed(new Runnable() {
public void run() {
l1.setBackgroundResource(color.green_off);
}
}, 200);
} else if (but_num == 2) {
l2.setBackgroundResource(color.red_on);
MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_red);
sound.start();
new Handler().postDelayed(new Runnable() {
public void run() {
l2.setBackgroundResource(color.red_off);
}
}, 200);
} else if (but_num == 3) {
l3.setBackgroundResource(color.yellow_on);
MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_yellow);
sound.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
l3.setBackgroundResource(color.yellow_off);
}
}, 200);
} else if (but_num == 4) {
l4.setBackgroundResource(color.blue_on);
MediaPlayer sound = MediaPlayer.create(this, R.raw.tone_blue);
sound.start();
// SLEEP HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
l4.setBackgroundResource(color.blue_off);
}
}, 200);
}
}
Bye !!

Related

project performs actions all at once

i am doing an android simon says app and i am in the light up loop,
for this example i have defined it so it would light up 4 colors because the array that has the numbers that light up the according numbers is 4 cells long
unfortunately it lights up all of the colors at the same time you could not distinguish the order i am trying to figure out why that is and how do imake it light up one color at once here's the code for my main activity and java calss that helps it
this is the activity:
package com.gabie212.simonsays;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements View.OnClickListener {
private int i = 0;
private Thread t = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private ArrayList<Integer> randomColors = new ArrayList<Integer>();
private ArrayList<Integer> userColors = new ArrayList<Integer>();
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gm = new GameManger(this);
setContentView(R.layout.activity_game);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(this);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int num;
for (i=0;i<3;i++) {
num = gm.getColor(4);
randomColors.add(num);
}
android.os.Handler handler = new android.os.Handler();
//TODO if the start button is pressed multiple times simultaneously it starts the lightup loop multiple times simultaneously
if (v.getId() == startButton.getId()) {
for (i = 0; i < randomColors.size(); i++) //light up loop
{
switch (randomColors.get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
}
}, 2000);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
}
}, 2000);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
}
}, 2000);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
}
}, 2000);
break;
}
}
/*
for(i=0;i<randomColors.size();i++)
{
if(v.getId()==greenButton.getId())
{
userColors.add(1);
}
else
{
if(v.getId()==redButton.getId()){
userColors.add(2);
}
else
{
if(v.getId()==blueButton.getId())
{
userColors.add(3);
}
else
{
userColors.add(4);
}
}
}
}
for(i=0;i<randomColors.size();i++)
{
if(randomColors.get(i) != userColors.get(i))
{
Intent i = new Intent( GameActivity.this, GameOverActivity.class);
startActivity(i);
}
}
*/
}
}
}
and this is the java class:
package com.gabie212.simonsays;
import java.util.Random;
/**
* Created by Ronit on 21/02/2018.
*/
public class GameManger {
private GameActivity gActivity;
static Random rnd = new Random();
public GameManger(GameActivity mA)
{
this.gActivity =mA;
}
public int getColor(int size)
{
return rnd.nextInt(4)+1;
}
}
the part i had problems with is this part:
int num;
for (i=0;i<3;i++) {
num = gm.getColor(4);
randomColors.add(num);
}
android.os.Handler handler = new android.os.Handler();
//TODO if the start button is pressed multiple times simultaneously it starts the lightup loop multiple times simultaneously
if (v.getId() == startButton.getId()) {
for (i = 0; i < randomColors.size(); i++) //light up loop
{
switch (randomColors.get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
}
}, 2000);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
}
}, 2000);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
}
}, 2000);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
}
}, 2000);
break;
}
as i mentioned it lights up the 4 buttons at once instead of doing it in an order and i using functions such as sleep didn't work and the delay mills i used either didn't seem to work either, how do i make it light up the colors in an order (i think its using sleep functions but i am not sure).
I think the problem is that you are starting multiple coroutines all at once (inside the for loop). I guess you are not very familiar with the Runnable interface: everytime a runnable is run, it runs in parallel to your main process, which means that your code keeps going no matter what.
It runs
greenButton.setBackgroundResource(R.drawable.greenlightup);
and sets a timer to run the delayed method. But while this method is waiting the for loop goes on, and
redButton.setBackgroundResource(R.drawable.redlightup);
is executed, and so forth. This is why your buttons are all colored at (almost) the same time. Your delayed methods all fire at (almost) the same time too!

How to implement "turn off music" button Android

I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed

Checking integer against array index not working

I'm making an android app where you tap a button to stop a looping counter when it is showing a particular number. I have an array (aNums) holding some int values and want the counter to stop when it is clicked when showing the first number in the array (in this case "2"). For some reason however it decides to stop on "1" when clicked. I'm not sure if my code is just wrong or if there's a timing issue and it's stopping right when it's about to change to the number "2". Here is my code so far:
public class MainActivity extends Activity {
public int a = 0;
private Handler handler = new Handler();
TextView textView2;
Button Stop;
public Runnable myRunnable = new Runnable() {
#Override
public void run() {
updateText();
a = ++a % 10;
if (a < 10) {
handler.postDelayed(this, 1000);
}
}
};
public int aNums[] = { 2, 4, 6, 8, 10, 12 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView2 = (TextView) findViewById(R.id.textView2);
loop();
Stop = (Button)findViewById(R.id.Stop);
Stop.setOnClickListener(handler2);
}
View.OnClickListener handler2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (a == aNums[0]) {
Stop();
}
}
}
public void loop() {
handler.post(myRunnable);
}
public void updateText() {
textView2.setText("" + a);
}
public void Stop() {
super.onStop();
handler.removeCallbacks(myRunnable);
}
}
Does anyone know what the problem is?
Thanks
You forgot two closing brackets here:
View.OnClickListener handler2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i <= aNums.length; i++) {
if (a == aNums[0]) {
Stop();
} //I added this
}
}
}//and this
but I think there is no need for a for loop here: you want to stop the thread when you click at the moment a equals the number in your array at index 0, right?
View.OnClickListener handler2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (a == aNums[0]) {
Stop();
}
}
}
Also, this check is not necessary because a will never be 10 or more:
if (a < 10) {
handler.postDelayed(this, 1000);
}
The last thing: when you quit the thread, the text is not updated. Try adding the updateText() after the click:
View.OnClickListener handler2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (a == aNums[0]) {
Stop();
updateText();
}
}
}

How to call a method multiple times in Android

I would like to ask, If is there a better way to call a method in android multiple time.
But What I really want to know, is how to delay which showToas("Message 1"); call for 10 second and only after call the next.
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
showToas("Message 1");
showToas("Message 2");
showToas("Message 3");
showToas("Message 4");
showToas("Message 5");
showToas("Message 6");
showToas("Message 7");
...
private void showToas(String message){
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
UPDATED
This is the away I managed to get it to work.
giving each method call a 5 sec break, But I think there most a be better way to implement this function ? Can you advice please. Thanks
private void CallMultipleToast(){
Runnable call_1 = new Runnable() {
#Override
public void run() {
Toast("Message one");
Runnable call_2 = new Runnable() {
#Override
public void run() {
Toast("Message two");
Runnable call_3 = new Runnable() {
#Override
public void run() {
Toast("Message three");
//CAN I ADD MORE
}
};//end call_3
new Handler().postDelayed(call_3, 5000);
}
};//end call_2
new Handler().postDelayed(call_2, 5000);
}
};//end call_1
new Handler().postDelayed(call_1, 5000);
}
try this way
Runnable r2=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
showToas("Message 1");
}
};
new Handler().postDelayed(r2,1000);
do the same for others and increase Time Delay
You can use Timer for that:
//global variable counter
int counter = 1;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
showToas("Message "+counter);
counter++;
}
}, 0, 10000); //It will be repeated every 10 seconds
Hope this helps.
public class ToastShow {
private Context context;
private Toast toast = null;
public ToastShow(Context context) {
this.context = context;
}
public void toastShow(String text) {
if(toast == null)
{
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
else {
toast.setText(text);
}
toast.show();
}
}
and you can call toastShow(String text) many times it only changes the content of toast
runOnUiThread(new Runnable() {
public void run() {
try {
for(String str : array){
showToast(str);
Thread.sleep(10000L);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

setBackgroundResource doesn't set the image

Handler hnd = new Handler() {
#Override
public void handleMessage(Message msg) {
int id = sequence.get(msg.arg1);
if(msg.arg1 % 2 == 0) {
sq.get(id-1).setBackgroundResource(R.drawable.square_show);
} else {
sq.get(id-1).setBackgroundResource(R.drawable.square);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < sequence.size()-1; i++) {
record_tv.setText(""+i);
Thread.sleep(200);
Message msg = hnd.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch(Throwable t) {
}
}
});
background.start();
}
[CODE UPDATED] now it goes through the first loop and stops
do you have any idea why the code in the first runOnUiThread gets executed but it doesn't do what i want?
what i want is: change the image to "square", wait 2 seconds, change the image to "square_show", wait 2 secs and repeat the loop
i've been struggling for an hour now...
You can easily set image using following code.
sq.get(id-1).setImageResource(R.drawable.square_show);
sq.get(id-1).setImageResource(R.drawable.square);
public void show(int size) {
// CICLE THROUGH EACH SQUARE
for(int i = 0; i <= size-1; i++) {
Thread thrd = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id-1).setImageResource(R.drawable.square_show);
// System.out.println("1st..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sq.get(id-1).setImageResource(R.drawable.square);
// System.out.println("2nd..........");
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
thrd.start();
}
}
This is a wrong way to achieve it. This may help you.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation
I would suggest you to use a handler
int drawablebkg[] ={R.drawable.ic_launcher,R.drawable.icon};
Handler m_handler;
Runnable m_handlerTask ;
ImageView iv;
iv = (ImageView)findViewById(R.id.imageView1);
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
iv.setImageResource(android.R.color.transparent);
if(i<2)
{
ivsetBackgroundResource(drawablebkg[i]);
i++;
}
else
{
i=0;
}
m_handler.postDelayed(m_handlerTask, 2000);
}
};
m_handlerTask.run();
In onPause() of your activity
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//_t.cancel();
m_handler.removeCallbacks(m_handlerTask);
}
Another way
iv= (ImageView)findViewById(R.id.imageView1);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.ic_launcher), 2000);
iv.setImageResource(android.R.color.transparent);
animation.addFrame(getResources().getDrawable(R.drawable.icon), 2000);
animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
//set setBackgroundDrawable(animation) is decprecreated i guess. not sure in which api
// start the animation!
animation.start();
Another way
Define background.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="#drawable/ic_launcher" android:duration="2000" />
<item android:drawable="#drawable/icon" android:duration="2000" />
</animation-list>
I your activity onCreate();
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setBackgroundResource(R.drawable.background);
AnimationDrawable animation= (AnimationDrawable)loadingRaven.getBackground();
loadingRaven.setImageResource(android.R.color.transparent);
animation.start();
Note to stop the animation you need to call animation.stop()
Because the resource changes in the UI thread and you are sleeping your background thread. The UI thread is running normally.
Use handlers:
public class MainActivity extends Activity {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.arg1 % 2 == 0) {
b.setBackgroundResource(R.drawable.analytic_icon);
} else {
b.setBackgroundResource(R.drawable.ic_launcher);
}
}
};
#Override
public void onResume() {
super.onResume();
Thread background = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(2000);
Message msg = handler.obtainMessage();
msg.arg1 = i;
msg.sendToTarget();
}
} catch (Throwable t) {
// just end the background thread
}
}
});
background.start();
}
}
Try this,It will work:
public void show(final int size) {
Thread thrd = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i <= size - 1; i++) {
id = (Integer) sequence.get(i);
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square_show);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
sq.get(id - 1).setBackgroundResource(
R.drawable.square);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrd.start();
}

Categories

Resources