gpt4 book ai didi

java - 如何为两个玩家掷骰子编程

转载 作者:行者123 更新时间:2023-11-30 01:50:48 25 4
gpt4 key购买 nike

(处理)代码没有返回我想要的结果。基本上,有两个玩家,每个玩家轮流掷骰子。这些值应分别存储在变量“p1diceroll”和“p2diceroll”中。它将比较两个值,并根据谁滚得更高来发布谁将先进行。

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.");
}
}
}

我希望输出是“玩家 2 滚得更高!他们先走。”、“平局!默认情况下,玩家 1 走在前面。”或“玩家 1 滚得更高。他们先走。”

最佳答案

除了 A.A 的回答之外,我还提供了一些处理选项:

  1. random() (例如 println((int)random(1,7)); (转换为 int 相当于 println(floor(random(1,7)) ); 这会将 float 降至 1-6 之间。
  2. randomGaussian()distribution is closer to a dice roll 可能会很有趣
  3. noise()会给你很多选择,特别是与 noiseSeed() 一起使用和 noiseDetail()

我还注意到每次按下该键时每个玩家的骰子值都会重置。我不能 100% 确定这就是您的意图,因为这两个值之一始终为 0。

这是使用 random() 和调试文本的代码调整版本:

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";
}
}
}

关于java - 如何为两个玩家掷骰子编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com