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.
Related
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.
I'm in the process of writing a very simple quiz-style boardgame that moves players around the board based on if they answer the question correctly and what they roll on the dice. I'm attempting to create and pass an array mehtod that stores the scores of player 1 and player 2, but the array doesn't seem to actually keep track of the score. For example, a fragment of some of the code is as follows:
public static int[] scorearray
{
int scoreplayer1 = 0;
int scoreplayer2 = 0;
return new int[] = {scoreplayer1, scoreplayer2};
}
public static int questions(int diceroll, int[] score)
{
String textinput = input("What's 9+10?");
int ans = Integer.parseInt(textinput);
if (ans == 19)
{
output("Fantastic answer, that's correct!");
diceroll = dicethrow(diceroll); // rolls the dice
output("Move forward " + diceroll + " squares. You are on square " + score[0]);
//I need the output above to print position 0 in the above array
score[0] = score[0] + diceroll; //array stores the cumulative score
}
else
{
output("Sorry, the answer was 19. Next player's turn.")
//This is where I need the loop to switch between players
}
In addition, I need to come up with a way of switching between player 1 and 2 while also switching to the position 1 in the above array, that is, I need to add to player two's score instead of player one's. I've been combing through this code for ages now trying to figure out how to do this but I can only come up with the idea of using a for/while loop. Other than that I'm truly stumped.
Thanks.
EDIT: It appears that my array apparently still does not store the score when being used in the method questions.
Also I have now realised I can control whose turn it is by creating another method, for example public static void activePlayer() but I'm still not sure how to use a loop (or anything else for that matter) to switch between the two. Also my concern is where I use score[0] = score[0] + diceroll; in my questions method only keeps the score (or at least attempts to; see above problem) for player one. How would I switch it to keep score for score[1]? Please.
your options here seem to be either have your questions function output the score or change your score object to be a static object instead of a static function.
public static int[] scorearray = [0,0];
or
public static int[] questions(int diceroll, int[] score)
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.
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.
So my professor gave out an assignment in which we have to create an operating slot machine program. The machine has 3 reels, which themselves consist of 6 six symbols stored in an enum:
public enum Symbol
{
SEVEN(12,"images/seven.jpg"),
WATERMELON(10,"images/watermelon.jpg"),
ORANGE(8,"images/orange.jpg"),
PLUM(6,"images/plum.jpg"),
LEMON(4,"images/lemon.jpg"),
CHERRY(2,"images/cherry.jpg");
}
We're supposed to use these symbols to create a "reel" object. My problem is centered around populating this reel (which is really just a Symbol[] array) with the symbols in the order requested by the professor.
He asked us to use the Random class to populate the reel using 10 as the seed number. Here's what I have so far:
//Creating an unrandomized reel array, which contains the symbols in the exact order as they appear in the enum
private Symbol[] unrandomizedReel = new Symbol[]{Symbol.SEVEN, Symbol.WATERMELON, Symbol.ORANGE, Symbol.PLUM, Symbol.LEMON, Symbol.CHERRY};
//Declares local Symbol array
Symbol[] randomizedReel = new Symbol[6];
//Keeps track of the position in the unradomized reel array
int unrandomizedReelIndex = 0;
//Creates a Random object which will be used to generate values based
//on the seed. **seed == 10**
Random randNum = new Random(seed);
//Loop will populate the randomized reel
while(unrandomizedReelIndex < 6)
{
//This int will hold values ranging from 0-5. Will be used as an index
//to populate randomized reel
int rangedRandomNumIndex = randNum.nextInt(6);
//if the element at the given index in the randomized reel is empty
if(randomizedReel[rangedRandomNumIndex] == null)
{
//A symbol from the unrandomized reel is added to it
randomizedReel[rangedRandomNumIndex] = unrandomizedReel[unrandomizedReelIndex];
//The index used to iterate through the unrandomized reel is incremented by 1
unrandomizedReelIndex++;
}
}
Running this "shuffling" code, I get the following output:
WATERMELON
PLUM
CHERRY
SEVEN
ORANGE
LEMON
However, according to my professor, the output should be:
ORANGE
PLUM
SEVEN
LEMON
WATERMELON
CHERRY
What am I doing wrong? Why is my output different from his, even though we are both using 10 as a seed? Any help would be appreciated. Thanks.
new Symbol[]{Symbol.SEVEN, Symbol.WATERMELON, Symbol.ORANGE, Symbol.PLUM, Symbol.LEMON, Symbol.CHERRY};
can be simplified to
Symbol.values()
My guess would be that your professor is putting
unrandomizedReel[Random.nextInt(6)]
in position 0, then nulling that out that element of unrandomizedReel, getting a random number x between 1 and 5 and taking the x-th non-null value and putting it in position 1, nulling it, then repeating with a number between 1 and 4 and so on.
If you have a reason to believe your professor is using a different algo, then edit your question with that information.