wondering if there is an easy way to get dice rolls. not just six sided but all of them.
Could you provide a little more information? Are you simply looking to get a random number as if you were rolling dice?
If so, it is just generating a random number with [icode]rnd.nextInt(numberOfSides - 1) + 1;[/icode]…
as long as I can choose number of sides I’m good.
no I’m kind of teaching myself. I dug out my old D&D books and I’ve been brainstorming on ideas for a command line game.
You can also use Math.random()
public static int random(int x)
{
return (int) (Math.floor(Math.random() * x));
}
x is the no. of sides here.
thanks!
So I tinkered with it for a while and came up with this.
package com.dungeon.java;
public class Dungeon {
public static void main(String[] args) {
int sides = 20;
int AC = 12;
System.out.println("Armor class of enemy: " + AC);
System.out.println("Your roll: " + Math.floor(Math.random() * sides));
if(Math.floor(Math.random() * sides) >= AC)
System.out.println("HIT!");
else
System.out.println("MISS!");
}
}
The problem is when I roll a hit it sometimes says “MISS!” and vice versa.
or this:
package com.dungeon.java;
public class Dungeon {
public static void main(String[] args) {
int sides = 20;
double AC = 12;
System.out.println("Armor class of enemy: " + AC);
// System.out.println("Your roll: " + Math.floor(Math.random() * sides));
if(Math.floor(Math.random() * sides) >= AC)
System.out.println(Math.floor(Math.random() * sides) + " HIT!");
else
System.out.println(Math.floor(Math.random() * sides) + " MISS!");
}
}
Because you are generating a new value each time you call it.
store the value of the roll into a variable
int roll = Math.floor(Math.random() * sides);
package com.dungeon.java;
public class Dungeon {
public static void main(String[] args) {
int sides = 20;
double AC = 12;
double roll = Math.floor(Math.random() * sides);
System.out.println("Armor class of enemy: " + AC);
System.out.println("Your roll: " + roll);
if(roll >= AC)
System.out.println("HIT!");
else
System.out.println("MISS!");
}
}
Brilliant. thanks again.