Java loops in a programming game [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am having an issue with my loops in a game that I created. I have a game board that is a 10 x 10 grid. It is a 3 part challenge. The first part asked for 20 random treasures, which I worked out just fine. Then the second part was adding 20 random trolls. The loop(s) I used gave me 20 treasures and 30 trolls. I AM TERRIBLE AT LOOPS. I have to stay along these lines of code and cannot use break (I am new to Java, but these are my profs rules).
private int width = 10;
private int height = 10;
//Create an array to hold buttons in a 10 by 10 grid
private EmptyButton[] buttons = new EmptyButton[width * height];
Random random = new Random();
int counter = 0;
//Using a while loop when counter is less than number of treasures still hidden
while (counter < game.getNumberStillHidden()) {
//Declare insertion variable and set to random to place buttons randomly
int insertionIndex = random.nextInt(buttons.length);
//Using conditional if button at index is null
if (buttons[insertionIndex] == null) {
//insert a treasure button
buttons[insertionIndex] = new TreasureButton(game, this);
//Use an acumulator for the counter to move on
counter++;
}
}
while (counter < game.getNumberOfTriesLeft()) {
Random randomOne = new Random();
//Declare insertion variable and set to random to place buttons randomly
int insertionIndex = randomOne.nextInt(buttons.length);
if (buttons[insertionIndex] == null) {
//insert a treasure button
buttons[insertionIndex] = new TrollButton(game, this);
//Use an acumulator for the counter to move on
counter++;
}
}
// Loop to add EmptyButton()'s into remaining null indexes within the button array
for (int index = 0; index < buttons.length; index++) {
// if the current index is null
if (buttons[index] == null) {
//add an EmptyButton()
buttons[index] = new EmptyButton(newGame, this);
}
}
// Loop to add all of the contents of the buttonGrid into the gamePanel
for (int index = 0; index < buttons.length; index++) {
//add buttons to panel
gridPanel.add(buttons[index]);
}

When you use
while (counter < game.getNumberOfTriesLeft())
the value of counter is 20 if you have 20 treasures.
You need to reset counter to 0 or use a different one.

Related

Inserting 20 random treasures into a 10 x 10 grid in Java [duplicate]

This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 2 years ago.
I created a GUI that will be 10 x 10 and have 100 buttons. I had to insert 20 treasures and have the other 80 be empty. This is the code I used. Sometimes I get 17 treasures, sometimes 18, sometimes 19. How do I fix this?
Thank you in advance.
Random random = new Random();
for (int index = 0; index < 20; index++)
{
int insertionIndex = random.nextInt(99)+1;
buttonGrid[insertionIndex] = new TreasureButton(treasureGame, this);
}
// Loop to add EmptyButton()'s into remaining null indexes within the buttonGrid
for (int index = 0; index < 100; index++)
{
// if the current index is null, add an EmptyButton() into it
if (buttonGrid[index] == null)
{
buttonGrid[index] = new EmptyButton(treasureGame, this);
}
}
// Loop to add all of the contents of the buttonGrid into the gamePanel
for (int index = 0; index < 100; index++)
{
gridPanel.add(buttonGrid[index]);
}
Create an ArrayList
Add 20 TreasureButton instances to the ArrayList
Add 80 EmptyButton instances to the ArrayList
Use Collections.shuffle(...) to randomize the buttons.
Iterate through the ArrayList and add each button to the panel

Java - Create grid of buttons with array, all with unique ID [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am making a game-board which requires a grid of buttons. I have a method where I can put in the width and height of the board and draw it like this:
for (int i = 0; i < gameBoardWidth; i++) {
for (int j = 0; j < gameBoardHeight; j++) {
gameLayout.add(tiles[j], j, i);
}
}
The code above works perfectly fine but the problem is, I have an array of buttons. the size of the array is equal to the width * height, Each button within that array needs to have a unique ID incremented from 1 to n. Previously I made the board with this method
for(int i = 0; i < gameBoardDimension; i++) {
tiles[i] = new Button("");
tiles[i].setMinSize(gameButtonWidth, gameButtonHeight);
tiles[i].setId(Integer.toString(i));
Button btn = tiles[i];
btn.setOnAction(e -> {
turn = 1;
int ID = Integer.parseInt(btn.getId());
setMove(ID, turn, btn);
setAIMove();
});
}
But with the method above it is impossible to show them in a grid. How can I show the buttons in a grid so every button in the array has an ID of 1 to n with n being the size of the array?
Create an id as row (i) times width plus column (j) (plus 1 to start from 1 instead of 0) in the loop
for (int i = 0; i < gameBoardWidth; i++) {
for (int j = 0; j < gameBoardHeight; j++) {
Button b = new Button("");
//... other stuff for button
int id = i * gameBoardWidth + j + 1;
b.setId(Integer.toString(id));
//...
}
}

Shifting elements in an array a particular way

The goal of this method is that I have a 2D array filled with Bubble objects and I am trying to shift everything in the array that does not have a color value of 0 down and leave the color 0 at the top of the column.
At the moment it turns every spot into a bubble with a value of 0. I'm thinking its a small logic error that im missing but I have been trying for 3 days now and cant see my issue. *Clarification: myBoard is initialized as new Bubble [15][15]; and the Bubble Constructor is (int color, int row, int col)
public void shiftBoardDown() {
int currentC = 0;
while(currentC < 15){
Bubble [] temp = new Bubble [15];
int hits = 14;
for(int i = 14; i <= 0; i--){
if(this.myBoard[i][currentC].getColor() != 0){
temp[hits] = new Bubble(this.myBoard[i][currentC].getColor(), hits, currentC);
hits--;
}
}
while(hits >= 0){
temp[hits] = new Bubble(0, hits, currentC);
hits--;
}
for(int r = 0; r < 15; r++){
this.myBoard[r][currentC] = temp[r];
}
currentC++;
}
}
I'm guessing
if(this.myBoard[i][currentC].getColor() != 0)
Never gets triggered and the following loop is entered with hits==14.
while(hits >= 0){
temp[hits] = new Bubble(0, hits, currentC);
hits--;
}
In that case hits runs from 14 to 0 inclusive setting the corresponding entry in temp to a color 0 Bubble.
Set a break point on `hits--' in the first loop to confirm if it ever gets triggered.
I can't tell because I can how the state of this.myBoard[i] entering the function.

Chutes and Ladders Game Random Placement Issue

I'm a student, working on a Chutes and Ladders game. I'm using methods to determine how many chutes and ladders should be placed on the game board. I'm specifying 10 for each in main using parameters but I keep getting anywhere from 6 to 11 placed across the board.
Is there something going on with the two methods interfering with each other?
Or is there a problem with the way I set up the for loops for random placement?
I'm new to this site, please let me know if you need more clarification, I didn't want to place the whole program in here. Thanks.
//main
ChutesAndLadders cl = new ChutesAndLadders();
cl.setBoard(new String[100]);
cl.makeChutes(10);
cl.makeLadders(10);
//methods
public String [] board;
private int chutes, ladders;
public int position;
public Random rand = new Random();
//set board
public void setBoard(String [] n){
board = n;
for(int i = 0; i < board.length; i++)
board[i] = " ";
}
//set and place chutes
public void makeChutes(int n){
chutes = n;
for(int i = 0; i <= chutes; i++)
board[rand.nextInt(board.length)] = "C" + chutes;
}
//set and place ladders
public void makeLadders(int n){
ladders = n;
int lcell = 0;
for(int i = 0; i <= ladders; i++)
board[rand.nextInt(board.length)] = "L" + ladders;
Firstly, you wrote:
for(int i = 0; i <= chutes; i++)
board[rand.nextInt(board.length)] = "C" + chutes;
The assignment statement in the loop will run chutes+1 times. (Eleven times in your case.) [Use i < chutes instead.] This is the same in your ladders code. This explains why you might have up to 11 chutes or ladders when the code is done running.
Secondly, you do not take care to prevent the same space being assigned a chute or ladder multiple times. rand.nextInt(board.length) is not guaranteed to generate unique values each time it is run (otherwise it wouldn't really be random.) This explains why you may not see as many as 11 chutes and ladders when the code is done running.
To make this clearer, put a constant value in there:
for(int i = 0; i < chutes; i++)
board[11] = "C" + chutes;
and notice that you end up with one chute (at space eleven)--unless the ladder code overwrites it with a ladder.
Hope that helps.
Good luck!
At first glance my guess is that you are winding up with overlapping entries. Because you generate a random placement and don't check to see if there is already a chute or ladder there, you are likely winding up with overlaps.
It should be fairly straightforward to generate the random position and then check if there is something there prior to placement. If a collision is found, just generate another random and repeat until you can place it.
Also, as an aside, it is always a good practice to avoid for loops and if statements without curly braces. It is very easy to add a second like to the block and wonder why it is not executing as part of the block.
Your for loops have an inclusive upper limit check, 0 .. 10 yields 11 entries.
Like Mike said, the lower number of results are due to collisions, you can prevent those by setting up the board by filling it with the elements needed and then shuffling the board to get the end result, something like:
public void setupBoard(String [] n, int nrLadders, int nrChutes){
board = n;
int index = 0;
while (index < board.length && 0 < nrLadders--) {
board[index++] = "L" + nrLadders;
}
while (index < board.length && 0 < nrChutes--) {
board[index++] = "C" + nrChutes;
}
while (index < board.length) {
board[index++] = " ";
}
board = Collections.shuffle(Arrays.asList(board)).toArray(new String[board.length]);
}
This is like creating a deck of cards containing a number of ladder cards, a number of chute cards, a larger number of empty spot cards and shuffling that deck to get the game board.

java add items to arraylist at random time intervals

trying to add an item at random time intervals.
I was thinking I need to start when i is equal to arriveTime, once that is met I need to create a new random arrival and add i (otherwise it will not happen again as i is already past arrival. So I add another if, once that is met create new arrival time and add i again. pseudocode seems to make sense, code not so much, any help is appreciated.
ArrayList<Integer> q = new ArrayList<Integer>();
Random r = new Random();
int arrivals = 0;
for (int i = 1; i <= 720; i++) {
int arrive = r.nextInt(4)+1;
if (i == arrive) {
q.add(i);
arrivals ++;
arrive = r.nextInt(4)+1+i;
}
else if (i == arrive) {
q.add(i);
arrivals ++;
arrive = r.nextInt(4)+1+i;
}
}
sorry, arriveTime should be just arrive. ArriveTime does not exist.
edit: To expand from comments. 'i' represents time and I dont want to add a random integer to the list. Rather add the same object at random intervals of 'i'. I was adding the value of 'i' to the list to see at what times the algorithm was adding an item because it didnt seem to be working. Results vary, but it seems to be always single digits that get added to list. Also made updates to code.
Your algorithm is lacking a pause - ie a call to Thread.sleep(), otherwise it will spin.
I'd be trying to keep it simple, matching your code to the problem: ie wait a random time between adding to the queue, simply:
ArrayList<Integer> q = new ArrayList<Integer>();
Random r = new Random();
for (int i = 1; i <= 720; i++) { // loop as many times as you want
Thread.sleep(r.nextLong() % 1000); // wait a random time up to 1 second
q.add(r.nextInt()); // add a random number to the queue
}
You can adjust the numbers to suit your requirements.
you should be comparing time to 1-4 in your if statements, then adding that value to i (as i is representative of time) Something like this
ArrayList<Integer> q = new ArrayList<Integer>();
Random r = new Random();
int arrivals = 0;
for (int i = 1; i < 100 ; i++) { //loop as many times as you want.
int time = r.nextInt(4)+1; //choose a random time of arrival, 1-4
//now compare time to your random time intervals (1-4, not i
//if it matches add that value to i
if (time == 1) {
//add your object to the list
i += 1;
}
else if (time == 2) {
//add your object to the list
i += 2;
}
else if (time == 3) {
//add your object to the list
i += 3;
}
else if (time == 4) {
//add your object to the list
i += 4;
}
}
The code as posted doesn't make much sense.
It depends on an undeclared variable.
The statements that update arrive have no effect ... because it it local to the loop.

Categories