Changing a buttons background image through using a random array - java

OK so I'm trying to get this button on its second click to display an image. I have 8 images for it to choose from and I want it to select it randomly. I set up an array with all of the R.drawable.img in the string and i tried placing it inside of this
else if (click == 1)
{
rpic = generator.nextInt(ppic);
spinntoke.setBackgroundResource(R.pic[rpic]);
}
So it is not allowing me to do that. Any ideas as to how i can get the random generator to select 1 of those 8 pictures at random when it is clicked? Thanks

You have not really provided enough info but here is what I imagine you would do.
have an array int[] that looks like this: [R.drawable.img1, R.drawable.img2, R.drawable.img3]
in onClick(): random = some random between 0 and array.size()-1;
spinntoke.setBackgroundResource(array[random]);
This way you have an array of ints (your R resources) where you can pick a random one. Don't forget to make your random generator only generate numbers from 0 to the array size-1.
Edit: code:
Random randomGenerator = new Random();
int random = randomGenerator.nextInt(array.size());
spinntoke.setBackgroundResource(array[random]);

You probably want to look at drawableLeft property - or one of the others - rather than the background.

Related

How to use randomization, so when you press a button it brings you to a random screen

I have searched for an answer to this question with my time in my Computer Science lab. We are using Android Studio for this app.
What I want to do is to use randomization to make a set of screens be randomized when you click a button. My duo is working on a dice rolling app, and we had the idea to make six different screens for each of the sides of the die. Basically, when we click the button to "roll the dice", it think for a second, then brings you to a random page with a picture of the number on the die which you got.
This is incredibly weird, and I have searched for at least 3 hours straight for a solution to this problem but to no avail. If anybody needs more information on the problem (because I do not know how to properly phrase it), then just ask me.
Just use Random.nextInt() to get a random number up to 6, and use that to choose one image of the 6 for each die side. You do not need to create 6 different screens, you just need 6 different images where the number indicates which image to use. For example:
// A list of drawables you've defined in /res/drawable folder for each die side
final int[] images = new int[6] {
R.drawable.die_side_1,
R.drawable.die_side_2,
R.drawable.die_side_3,
R.drawable.die_side_4,
R.drawable.die_side_5,
R.drawable.die_side_6
};
int random = Random.nextInt(6); // Get random value, 0-5
int dieSideDrawable = images[random]; // Pick image to show based on random value
mDieImageView.setImageResource(dieSideDrawable); // Show image on an image view
Hope that helps!
The easiest way to do exactly what you want would be to put the Activities in an Array, and select by using the Random class' nextInt method to choose the appropriate activity from the Array.
That being said, most likely you want to create a single activity with two images, and instead of selecting an activity or Fragment to show, you'd select the images you'd load into the Activity.
I would recommend using Fragments to achieve this.
create a list of fragments
ArrayList<Fragment> fragmentList = new ArrayList<>();
Now use the java Random class to generate the random number.
Random rand = new Random();
int n = rand.nextInt(fragmentList.size());
then just show that fragment.
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragmentList.get(n))
.addToBackStack(null)
.commit();
Using multiple activities seems unnecessary here (and will significantly slow down your app). If you want to show a different image based on the result of a random number that's been generated, then just .setImageResource() for your Image View based on the result of that random number.
In the example below I separated the random number generation (the generateRandomInt() method which stores a random integer in the thisRoll variable) and only called it when the changeImageView() method runs onClick.
public void changeImageView(View view){
generateRandomInt();
if (thisRoll == 1) {
mainImage.setImageResource(R.drawable.s1);
} else if (thisRoll == 2) {
mainImage.setImageResource(R.drawable.s2);
} else if (thisRoll == 3) {
mainImage.setImageResource(R.drawable.s3);
} else if (thisRoll == 4) {
mainImage.setImageResource(R.drawable.s4);
} else if (thisRoll == 5) {
mainImage.setImageResource(R.drawable.s5);
} else {
mainImage.setImageResource(R.drawable.s6);
}
Toast.makeText(DiceRollActivity.this, thisRoll + " ...But The House Always Wins!", Toast.LENGTH_SHORT).show();
}

Need help randomizing images and not repeat throughout activity

I have a simple educational kids game with 7 questions. One imageView and four buttons for each question, the user must match the correct answer(button) with what is shown in the image view. I want the images(questions) to be random every game but never repeat a question during a game until all 7 have been asked. I am only using 3 images as of now just to get it working.
Option 1
int[] res = {R.drawable.img1, R.drawable.img2, R.drawable.img3};
Method
private void randomImage() {
Random rand = new Random();
int rndInt = rand.nextInt(res .length);
imgView.setImageDrawable(getResources().getDrawable(res[rndInt]));
}
Option 2
private ArrayList<Integer> res1 = new ArrayList<Integer>();
res1.add(R.drawable.img1);
res1.add(R.drawable.img2);
res1.add(R.drawable.img3);
Method
private void randomImage1() {
Collections.shuffle(res1);
for(int i=0;i<res1.size();i++){
imgView.setImageResource(res1.get(i));
}
}
Both of these work for randomizing, but I am having a little trouble figuring out how to check if an image has already appeared and to correct it if it had.
In fact I'm not really quite sure where to start. Any help would be appreciated.
If you dont want to see repeated items from array then use shuffleArray() like this example and for a list use shuffle(list) like this example2

Adding a several random numbers to graphics context above images

I am creating a old school game where the user has to collect the falling objects. Currently I have an image that is printed to the GraphicsContext several times accross the pane and is added and removed from an arrayList() when it disappears off of the screen. I can create a random number and I can print this to the same position as the falling image. However the random number is always the same and I want the number to be different on each of the objects. My code in my start method is as follows:
int i;
for(i=0;i<800; i+=90)
arrayList.add(new Object(ImageView, noOnImage, i,-10));
I then also have an update method where the objects are continously redrawn:
int newObject = 0;
Iterator<Object> objectIterator = object.iterator();
while(objectIterator.hasNext())
{
Object ob = objectIterator.next();
if(ob.move())
{
objectIterator.remove();
newObject++;
}
gc.drawImage(ob.objectImage,ob.r.getX(), ob.r.getY(), ob.r.getWidth(),
ob.r.getHeight());
gc.fillText(String.valueOf(noOnImage), ob.r.getX()+8, ob.r.getY()+22);
}
noOneImage is just a randomly generated number that I declared at the top. I would like each object to contain a different random value, currently they are all the same though, even though it is random.
When you create the object, pass in the random number within your loop.
Random rand = new Random()
arrayList.add(new Object(ImageView, noOnImage, i,-10, rand.nextInt(0, 10)));
That rand will give you a number between 0 and 10. You can put whatever int you want in there.
And make sure the object you create has the field and you are able to retrieve this number (e.g. for a score tally, etc.).

Random number loop

I'm making the connect 4 game in Java and in vs computer mode. The computer will play randomly. I wrote the code to select randomly the column. Computer does play randomly on a column but keep on playing on same column after.
How should I do to make it play randomly on any column whenever its computer's turn.
This is my simple code so far:
public static Random rnd = new Random();
public static final int row = Row - 1;
public static int col = rnd.nextInt(7);
What code should I write and I need the variable col for my next method of this class
You need to call nextInt each time the computer plays, to regenerate a random number.
What you currently have will generate a random number for the column but you never update it. So for each new game, the computer will play only in the same "random" column.
Let's say you have a method computerTurn() that you calls each time it's the turn of the computer to play. So something like that.
void computerTurn(){
int col = rnd.nextInt(7);
placeInCol(compute, col);
}
Note that you will have to check that you can play in the column. So the best way to deal with this is to create a List that will contains the column available to play.
List<Integer> columnsAvailable = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
Now it will look for something like this:
void computerTurn(){
int index = rnd.nextInt(columnsAvailable.size());
int col = columnsAvailable.get(index);
if(isAvailableCol(col)){
placeInCol(computer, col);
} else {
columnsAvailable.remove(index);
//get a new random column here.
}
}
The random number generated may repeat.That is the problem.So, you can save the generated random number temporarily , and check it with the next random number , if they are same loop it again.This is a wide logic. You can use Collections.shuffle(); . Then , there will be no head ache regarding repeatation.

Adding probability without adding more to StringArray

I got this string[] I use in a grid of these images. The grid is generated randomly using a random. now I use the way of just adding the one object more times. but my algorithm to regenerate one if two pictures are the same(eg. egg-tree-blackcar-blackcar-pinkcar) won't work because I check the array indexes of the images.
String bingoObject[] = {
"black_car",
"gray_car",
"white_car",
"red_car",
"yellow_car",
"blue_car",
"pink_car",
"green_car",
"boat",
"tree",
//ADDED MORE FOR CHANCES
"black_car",
"black_car",
"gray_car",
"white_car",
"red_car",
"blue_car",
"green_car"
};
Is there another way to get randoms and assigning probability to each object without having to add them more times into the array? This would clean and help me through a lot of messy coding.
I don't personally know of any ways to assign probability, but we can kind of create our own way. It's not the most efficient way of doing so, but it does create a pseudo-probability.
int [] numbers = {1,2,3,4,5,6,7,8,9,10};
int index = 0;
Random rnd = new Random();
for (int i = 0; i < 3; i ++)
{
index = index + rnd.nextInt(numbers.length);
}
index=index/3;
System.out.println(numbers[index]);
This will skew the array index to be somewhere near the middle, most of the time. So the most common values, in theory, will be near the middle of the array, while the borders will be very uncommon.
You can change the "3" value to be whatever you want, the higher this number is, the more middle-biased the numbers should be.
Upon running this 10 times, my values were:
2,6,7,2,6,5,6,6,4,5

Categories