Adding a several random numbers to graphics context above images - java

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.).

Related

Adding values to int from Array List

I am working on a personal project to create a game.
My trouble I seem to be running into is getting my variable called runs to increase value.
I have set my value to zero. I tried using runs++ though it only increases by one.
What I am looking to do is increase by 1 or 6 depending on the result of the if statement.
If anyone can point in the right direction on how to solve would be great!
public class BatsmanDice {
public static void rollBatsmanDice() {
// Roll player dice decides how many runs are scored when the player rolls.
// We have options from 1 to 6 and Owzthat.
// When Owzthat is triggered we return to the main method and run rollUmpireDice();
// Using an Array list to have all options available.
ArrayList batsmanDiceOptions = new ArrayList();
batsmanDiceOptions.add(1);
batsmanDiceOptions.add(2);
batsmanDiceOptions.add(3);
batsmanDiceOptions.add(4);
batsmanDiceOptions.add(5);
batsmanDiceOptions.add(6);
batsmanDiceOptions.add("Owzthat");
int runs = 0;
System.out.println("Total runs " + runs);
// We take our Array list from above and shuffle it using the Collections import tool.
Collections.shuffle(batsmanDiceOptions);
// We then take the shuffled array list and print 1 options to screen showing the dice rolled
// Commented out print line statement to return a random shuffled array option
//System.out.println(batsmanDiceOptions.get(1));
if (batsmanDiceOptions.contains(1)) {
System.out.println(" Scored 1 Run " + batsmanDiceOptions.get(1));
}
}
}
I'm not positive if this is what you're asking. But if you're trying to "roll" and increment runs, just do:
ArrayList<Integer> batsmanDiceOptions = new ArrayList<Integer>();
// your code
runs += batsmanDiceOptions.get(0);
To increment runs by some random value. get(0) returns a random value because you've already shuffled the ArrayList.
That being said... to simulate a dice roll, why not just increment by a random number from 1 to 6? I would recommend using ArrayList for things like picking finite items out of a hat, because then .remove() becomes useful. For dice rolls I would probably just use Random.

How do I count the number of bombs in my Minesweeper code?

So well I tried creating a simpler Minesweeper game and I encountered one main problem..
I am not able to count the number of bombs and print it in a JTextField
Any ideas as to how to count these as I'm setting a random value to check whether they are a bomb
Tried counting it in the ActionListener but the bombs were counted only after the button was clicked.
if(e.getSource()==b[i][j])
{
b[i][j].setVisible(false);
tf[i][j].setVisible(true);
int r1 = rand.nextInt(6);
if(r1>1)
{
tf[i][j].setText("Safe");
tf[i][j].setBackground(Color.green);
}
else
{ count++;
tf[i][j].setText("Bomb");
tf[i][j].setBackground(Color.red);
f.setVisible(false);
restart.setVisible(true);
}
}
As I understand you decide if the the tile will be a bomb in the run-time using a random generator. Doing this you can't really know how many mines are in your game. I think you should decide the number of mines at the beginning of the game and randomly place them to your game board (you can choose the number according to a difficulty level).
EDIT
You can create a list with some random points that contain the mines
int numOfMines = 10;
int rows=5,columns=5;
ArrayList listWithMines = new ArrayList();
while(listWithMines.size()<numOfMines) {
int randRow = random.nextInt(rows);
int randCol = random.nextInt(columns);
Point point = new Point(randRow, randCol);
if(listWithMines.contains(point))
continue;
else
listWithMines.add(point);
}
This list now contains the Points that have the mines.
You can check if Point(x,y) has a mine like this:
if(listWithMines.contains(new Point(1, 2))) {...}
Instead of a list you can use a 2D array, store a boolean value (or int if you store more states) and make a loop until you place 10 mines. You should keep a counter(placedMines like the list.size()) of the mines you placed and make sure you don't add a mine to a tile that has already a mine and you increase the counter(placedMines) until it reaches the numOfMines.

Java - War Game - Getting an object from an array

I'm new to Java and I am having trouble wrapping my mind around one of the concepts.
The assignment I am currently working on is the card game War. The current instructions is for me to remove a random card from a a deck of cards.
I have created an array, but it is an array of class Card. The class creates the card by basically adding an int and a String together. I then created the array from that class. In my mind, I neither have an int or a String in my array, is that correct?
Now I need to remove one of the random cards from the deck and give it to a player. This is where I am getting lost. I would think I can just use Random to remove a random card, but I always seem to get an error.
I'm not asking for you to do the assignment for me, but if you would please point me in the right direction and possibly correct me if I am confused.
Current Class I am working on:
import java.util.Random;
import java.util.*;
public class War3
{
Random ran = new Random();
public FullDeck randomCard()
{
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
int index = ran.nextInt(randCard.size());
FullDeck x = randCard.remove(index);
return x;
}
public void display()
{
System.out.println("Your card is" + randomCard());
}
}
Entire project for clarification Java - War Game - Gist
Many thanks in advance.
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
This creates an ArrayList. You do not need to specify the number 52, since ArrayLists grow dynamically, as opposed to Arrays. The call is similar to
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> ();, the difference being that the constructor you used sets the initial capacity of the ArrayList to 52. That in no way restricts the size of the ArrayList though.
Anyway, you are creating a new, empty ArrayList. Then you want the size, but since you didn't put anything into the list, it is still empty, to the size is zero. You then try to call ran.nextInt(0)... nextInt(int n) expects a number greater than zero. From the javadoc:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
Two issues that I see:
You're creating an ArrayList that can hold a reference to 52 instances of the FullDeck class, but you're not adding anything to it. You need to do something like randCard.add(new FullDeck()) 52 times/in a loop**. Then likely you'll want to "shuffle" the deck, see this question for how to do that.
You're naming is a little weird...the FullDeck class in actuality seems like it should be renamed to just Card, and the randCard variable should be renamed to something like fullDeck...after you've added 52 Cards.
**EDIT: actually, the generation of a deck of cards will be more complicated to make sure you don't have any duplicate cards.

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

Trying to get a random element from an array so that I can mark it as "booked"

This is what I have in my method to randomly select a element in my array, however I'm not sure why it isn't working, I feel like I have tried every way of writing it, any ideas.
public static Seat BookSeat(Seat[][] x){
Seat[][] book = new Seat[12][23];
if (x != null){
book = x[(Math.random()*x.length)];
}
return book;
}
The way you explain things makes me think a couple of concepts somehow got crosswired. I am assuming that book is some (2 dimensional) array of Seat objects from which you want to pick a random one. In order to do so, you need to specify a random choice for each dimension of the array:
// this should be declared elsewhere because if it's local to bookSeat it will be lost
// and reinitialized upon each call to bookSeat
Seat[][] book = new Seat[12][23];
// and this is how, after previous declaration, the function will be called
Seat theBookedSeat = bookSeat(book);
// Okay, now we have selected a random seat, mark it as booked, assuming Seat has a
// method called book:
theBookedSeat.book();
// and this is the modified function. Note also that function in Java by convention
// start with a lowercase letter.
public static Seat bookSeat(Seat[][] x){
if (x != null){
// using Random as shown by chm052
Random r = new Random();
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
}
return book;
}
You should also integrate a test to check whether the selected seat was already booked and repeat the selection:
do {
// need to pick a random one in each dimension
book = x[r.nextInt(x.length)][r.nextInt(x[0].length)];
while (book.isBooked()); // assuming a getter for a boolean indicating
// whether the seat is booked or not
But a full-random selection like this has a couple of disadvantages:
the selection being random, you can repeatedly fall on already booked seats, and the chances that happens increase with the number of already booked seats. But even with few booked seats you could be really unlucky and see the loop spin around tens of times before it hits an unbooked seat.
you should absolutely test whether there are still unbooked seats left before entering the loop or it will spin indefinitely.
Therefore it might be a good idea to implement a smarter selection routine, eg by randomly picking a row and a seat and start searching from there until the first free seat is encountered, but for first steps this one should do just fine.
I hope this is what you wanted to achieve, if not feel free to comment and allow me to correct and adapt.
Floor the number returned by the (Math.random()*x.length) expression.
Math.floor(Math.random()*x.length);
At the moment, you're trying to subscript the array with a floating point number.
The other answer will totally work, but here is another way of doing it using Random.nextInt() if you don't want to have to do all the mathing around:
Random r = new Random();
book = x[r.nextInt(x.length)];
It uses java.util.Random, so make sure you import that if you do this.

Categories