How do you randomize Java strings? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So i've began coding a small game and need the 'enemys' to spawn from two points.
Heres my code for the enemy spawn;
public void createEnemy(int enemy_count){
for(int i = 0; i < enemy_count; i++){
addEntity(new Enemy((200), -10, tex, this, game));
}
}
As you can see the '(new Enemy((200)' is the point where one enemy would spawn. The other would be at 450.
so how do i alternate between these two point where the enemy spawns each time they are killed?
********************EDIT
// For respawn enemy
if(y > (Game.HEIGHT * Game.SCALE)){
x = 450;
y = -10;
}
Okay im pretty sure ive got to randomize that as well for it to work? ideas? (x needs to be random 450 or 200).
Thanks,
Max

If you want to alternate between 200 and 450 on every other iteration:
addEntity(new Enemy((i % 2 == 1 ? 200 : 450), -10, tex, this, game));
This uses the modulo operator % to determine whether the loop counter i is odd or even and uses the ternary operator to select either 200 or 450.
If you want to pseudorandomly choose one or the other, you can use Math.Random() instead, as #Chrisky expounded in a comment:
addEntity(new Enemy((Math.Random() > 0.5 ? 200 : 450), -10, tex, this, game));
Edit: You can apply the same patterns to the second block of code you've added to your question.
if (y > (Game.HEIGHT * Game.SCALE)) {
x = (Math.Random() > 0.5 ? 200 : 450);
y = -10;
}

If you want the monster to spawn at a random undetermined location each time, you should generate a random value, in your case you only have two random points so you want 0 or 1.
Once you create a random number (either 0 or 1) check the value of the random number, and then turns it into either 250 or 400. This can be done using an associate array, or (much simpler) an if else statement.
See:
Generating a Random Number between 1 and 10 Java
Also, you should know there's no such thing as truly random. Some people insist on calling it psuedorandom but I find that somewhat pedantic.

Select a location at random:
Random random = new Random(); // Somewhere at the top of your code
addEntity(new Enemy((random.nextBoolean() ? 200 : 450), -10, tex, this, game));
Alternating locations, without dependency on the loop counter variable. This is useful if you spawn enemies outside of the loop as well. (For example, other loops for other types of enemies.)
bool flag = false; // Somewhere at the top of your method for spawning enemies.
addEntity(new Enemy((flag = !flag ? 200 : 450), -10, tex, this, game));

Related

DMX-values using sine and cosine. From 8bit (1 channel) to 16bit (two channels)

The bounty expires in 5 days. Answers to this question are eligible for a +50 reputation bounty.
droid is looking for a more detailed answer to this question.
I’m (still) working on a small project controlling DMX-lights (using Art-Net).
At the moment I’m working on the “Movement-generator” and what I basically do is to use sine and cosine to calculate the DMX values (0-255) for the pan- and tilt-channel, like with this method:
public void runSineMovement() {
double degrees = x;
double radians = Math.toRadians(degrees);
double sine = Math.sin(radians);
double dmxValue = (int) ((sine * 127) + 127);
dmxValuesOBJ.setDmxValuesInArray(1, (int) dmxValue);
SendArtnet.SendArtnetNow();
x = x + 1;
if (x > 360) {
x = 1;
}
}
x = 1
I then have a ScheduledExecutorService that will call that method on a regular interval, like this:
int speed = 100;
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(SineMovement::runSineMovement, 0, 100000 * speed, TimeUnit.NANOSECONDS);
Above is working just fine, moving head (tilt-channel in this example) is moving perfectly. Now I want to use the “fine-channel”, that is, go from 8bit to 16bit (from 1 channel to 2 channels controlling the tilt-channel) so I can get smooth movement even at very slow speed. Remember, "fine-channel" have to go from 0 to 255 first and then "coarse-channel" can go to 1, then "fine-channel" from 0 to 255 and then "coarse-channel" to 2, and so on.
Earlier I build a movement-generator with “triangle-effect” where I looped from 0 to 65.536 and back to 0 and so on, and on every run I calculated the “coarse-channel” (counter/256) and the “fine-channel” (counter % 256) and that approach is working just fine.
Any ideas on how to approach this when using sine and cosine when generating the effect? Can I use the approach from the triangle-generator calculating “coarse” and “fine” using division and modulus?
EDIT: When thinking about it, I don't think the "fine" should have the form as a sine-wave, I mean, the "fine" will (if using sine) go very, very, fast, both up and down, and that will mess things up if the "coarse" is still going "up". I guess the correct is that the "fine" will always have the sawtooth-shape -> sawtooth from zero to max when coarse is going up, and sawtooth from max to zero when coarse is going down. Does that makes sense?
Thanks 😊

how to get Math.random() with a unit step

I am trying to create a snake game where i have 400x400 pane and the snake moves by 20 at X and Y axis. By doing this i have created a grid that has step of 20 at X and Y axis.
I want to randomly spawn a fruit at the pane but i want the width and height to be in grid so it should spawn at steps of 20 (0, 20, 40, 60 , 80, ... , 400).
I can use Math.random()*400 to get range but i cant give it unit step.
I found this question which is exactly what i asked but the solution is for lua based math.random():
math.random function with step option?
Here is how i translate the snakes position:
if (input.equals(KeyCode.W.toString()) || input.equals(KeyCode.UP.toString()))
if (snakes.get(0).getY() == 0)
movement.stop();
else
snakes.get(0).setY(snakes.get(0).getY() - 20);
*Snakes is an Arraylist of rectangles that expand as it eats food and i want only the head to eat the food
*Food is a circle that spawns at random location
And here is how i check if they come in contact:
if (food.getCenterX() == snakes.get(0).getX() && food.getCenterY() == snakes.get(0).getY())
score++;
setScore();
I move my snake over the food but the x and y position don't ever match unless i spawn food myself at the grid (say [20,40] or [60, 200]).
Is there another alternative or random with unit step or some other question that i couldn't find here at stackoverflow that can help me?
if you need integer values you can use Random.nextInt(int bound). This will produce coordinates inside your 20x20 matrix.
Random r = new Random();
int x = r.nextInt(20)*20; // values from 0 to 19 inclusively
int y = r.nextInt(20)*20;
If you want a random number out of 0, 20, 40, 60 , 80, ... , 400, then first realize that there are 21 values in that list.
Which means you want a random integer value 0, 1, 2, ..., 20, and then multiply that by 20, to get the step of 20 you want.
Don't use Math.random() for this. Sure it's convenient, but mostly is you want double values. Instead, use one of the following:
new Random() - Use in single-threaded code. Recommended.
You should generally only allocate one, then share it throughout your code.
new SplittableRandom() - Use for parallel computations.
ThreadLocalRandom.current() - Use in multi-threaded code, e.g. web servers.
All 3 have a nextInt(int bound) which returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
Example
Random rnd = new Random();
// in some loop generating fruits:
int fruitX = rnd.nextInt(21) * 20;
int fruitY = rnd.nextInt(21) * 20;

Scanning through 2d boolean array to find closest true coordinate

I am using a 2 dimensional boolean array to check where an entity is inside of my 2D side scroller as well as for collision. I know I am not looking for how high or low an entity away is and that is intentional. When I run this code it says the closest entity is 15 cells away. However, when I run my code it says the closest entity away is 15 blocks. Also when I print out distanceX it prints out the following:
9
0
0
2
2
15
9
0
0
2
2
15. I don't know why it won't register 9 as the closest even though that's is the first closest distance it recieves.
I can't post pictures yet however the reason 0,0,2, and 2 get printed is because I have 4 rectangles in all four corners of my player that are considered true in the grid so it detects the two on top of eachother and the other 2 or 2 spots away in the grid. Since I cant upload pictures try to see what I mean with this image i made. https://lh3.googleusercontent.com/OLSDPshjeU0YMahcmc0MDk-NocBMoG-7iN2xFTeFsQ8mAfF-sEPD8NBqXP4ENoN4YWmfUQ=s114
Thanks for any help!!
//Loop through my grid of booleans
for (int x = 0; x < map.getMapGrid().length; x++) {
for (int y = 0; y < map.getMapGrid().length; y++) {
//For comparison
Long distance = Long.MAX_VALUE;
// The second part of the if statement is to make sure it is checking for
// entities that arent the floor, therefor one above the grid position of the player
if (map.getMapGrid()[x][y] && y > ((Player) player).getGridPositionLeft().y - 1){
// distanceX = where something true was found (x) - where the player is in the grid
// Ex: 1 - 4 = |-3|, there is an entity 3 away
distanceX = Math.abs((int)(x - ((Player) player).getGridPositionLeft().x));
// if the distance of the entity from the player is less then the comparison variable,
// the closest entity x coordinate is distanceX
if(distanceX < distance){
closestCoord.x = distanceX;
closestCoord.y = 0;
}
}
}
}
return closestCoord;
}
Long distance = Long.MAX_VALUE;
This variable is never re-assigned, so it will always have the value Long.MAX_VALUE.
Also it is declared inside the innermost loop, so it will reset on each iteration. If you want the value of a variable to be remembered between iterations you need to declare and initialize it outside the loops.

Mathematical issue (Increasing and deceasing two variables inside one loop)

I have a for loop and inside that integer x will increase from 533 to 813. That means 280 increments. In side the same loop I want to decrease y's value from 300 to 200 when above happens. Which means when x is 533 y must be 300 and when x is 813 y must be 200. I know this can do by decrease y's value by 100/280 in each iteration. But both are integers.
Here are some code sample i used but it is not working.:
for(int i = 0; i < b.getSize(); i++) {
x = b.getCar(i).getPosX();
b.getCar(i).setPosX(++x);
if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){
y = b.getCar(i).getPosY();
y = (double)(y - (10.0f / 28.0f));
b.getCar(i).setPosY((int)y);
}
}
How can I possibly do this. Thanks!
There are two solutions, a simple and a complex one. The simple one:
y = yoff + (int)( (double) height * x / width )
where yoff = 300, height = -100, width = 813-533. Basically, you do a floating point operation and then you round the result.
Alternatively, the same can be done using pure integer math using the Bresenham line algorithm but that would take a lot more code.
y must be a double or a float and you need to round its value when you want to use it.
If you wanna do animation, just have a look at interpolators. You can abstract the logic of computing the values in between your extremas.
Basically at the beginning, you give your interpolator the start and end values.
Then, you give the interpolator a time and it gives you back the value between start and end for that time value.
Bonus: it will allow you to change your animation look & feel without touching the rest of the code. (what you are trying to do is in fact a linear interpolation, but it will look much nicer using a sine function for instance, or some other algorithm such as bouncing, quadratic, ...)
It looks like the logic for drawing a line. The Bresenham's algorithm should be the best option.
Keep a helping variable double dy that keeps track of the precise value for y. At each iteration, update dy using your formula, then update y by taking the rounded/truncated value of dy.
NOt sure what you like to do, but your current solution sufers from rounding of floats to integers. To avoid this, calculate with floats / doubles and convert them to integer whensetting positions.

Confused with a piece of code form a tetris game controling the speed of the block

if(loopCount % (20 - loopCount / 100) == 0) {
if(dropBlock() == false) {
mode = -1;
loopCount = 1;
}
if(loopCount == 1900)
loopCount--;
}
loopCount++;
A tetris program from a book written by java. I just can't understand why using such a piece of code to control the droping speed of a block and how it works.
Thank you !
The initial value of loopCount is 1 and dropBlock will return false if the game ends. This piece is contained in the main loop. And the mode is not relevant. I am sorry but I just can't gvie the whole program here.
It appears that it is set to have loopcount start at one, and lets use a table to examine the effect of if(loopCount % (20 - loopCount / 100) == 0) {
loopCount < 100, loopCount/100 = 0, so loopCount % 20 returns true for 20, 40, 60 and 80. Lets say loopCount is 100 - 199. Now we're checking if it's divisible by 19, for 200-300 divisible by 18. I'm not sure what exactly he is trying to achieve with this though. Then it checks if it fails to drop the block maybe, (dropBlock possibly tried to drop the block, and returns true for success, false for failure. Then if it fails it sets mode to -1 (maybe exits?). Then once loopCount reaches 1900, it prevents it from going up (by decreasing to 1899 right before the loopCount++;, which essentially decreased then increases, so does nothing (holding it at 1900)
The code is a good example of how not to write good code. It's full of magic numbers (1900, 20, 100) which make it hard to reason why you are doing what you are doing.
But implementing this, and printing out the value shows that the value of loopCount just keeps growing from 1 to 1900 and once it hits 1900, it stays there.
So it looks to me that what the logic does is decrement to 1899 and increment to 1900 every iteration once 1900 is reached.

Categories