(Processing) The code isn't returning what I want it to. Basically, there are two players, and each player takes turn rolling a die. The values should be stored in the variable "p1diceroll" and "p2diceroll" respectively. It will compare the two values, and release who will be going first based on who rolled higher.
void setup(){
size (100,100);
background(200,200,200);
println("press l to roll the die!");
}
void draw() {
if(keyPressed)
keyPressed();
noLoop();
}
void keyPressed(){
int p1diceroll=0;
int p2diceroll=0;
if (key == 'l') {
double rand1 = Math.random();
double rand2 = rand1*6;
double rand3 = rand2 +1;
p1diceroll = (int)rand3;
println("You rolled a " + p1diceroll + "!");
println("player 1! press 'a' to roll");
}
if (key == 'a') {
double rand11 = Math.random();
double rand22 = rand11*6;
double rand33 = rand22 +1;
p2diceroll = (int)rand33;
println("You rolled a " + p2diceroll + "!");
if (p2diceroll>p1diceroll) {
System.out.println("player 2 rolled higher!. They go first. ");
} else if (p2diceroll==p1diceroll) {
System.out.println("It's a tie! player 1 goes first by default." );
} else {
println("player 1 rolled higher! They go first.");
}
}
}
I expect the output to be either, "player 2 rolled higher!. They go first.", "It's a tie! player 1 goes first by default.", or "player 1 rolled higher. They go first."
I addition to A.A's answer here are few Processing options:
random()
(e.g. println((int)random(1,7));
(casting to int
is equivalent to println(floor(random(1,7)));
which would drop the floating point number to a floored into between 1-6.randomGaussian()
might be fun to play with the distribution is closer to a dice rollnoise()
will give you a lot of options, especially in tandem with noiseSeed()
and noiseDetail()
I've also noticed the diceroll values per player are reset each time the key is pressed. I'm not 100% sure that is what you intended as one of the two values will always be 0.
Here's a tweaked version of your code using random()
and debug text:
int p1diceroll=0;
int p2diceroll=0;
String result = "";
void setup(){
size (120,120);
background(200,200,200);
println("press l to roll the die!");
}
void draw() {
background(0);
text("press 'l' for p1"
+"\npress 'a' for p2"
+"\n\np1diceroll: " + p1diceroll
+"\np2diceroll: " + p2diceroll
+"\n\n"+result,5,15);
}
void keyPressed(){
if (key == 'l') {
p1diceroll = (int)random(1,7);
println("You(p1) rolled a " + p1diceroll + "!");
println("player 2! press 'a' to roll");
}
if (key == 'a') {
p2diceroll = (int)random(1,7);
println("You(p2) rolled a " + p2diceroll + "!");
if (p2diceroll > p1diceroll) {
println("player 2 rolled higher(" + p2diceroll + " > " + p1diceroll + ")!. They go first. ");
result = "player 2\ngoes first";
} else if (p2diceroll == p1diceroll) {
println("It's a tie! player 1 goes first by default." );
result = "tie! player 1\ngoes first";
} else {
println("player 1 rolled higher(" + p1diceroll + " > " + p2diceroll + ")! They go first.");
result = "player 1\ngoes first";
}
}
}