用javascript为骰子游戏制作点数计数器



我正在尝试制作一个骰子游戏点数计数器,根据你对数字的猜测与滚动的数字的接近程度,你可以获得点数。我当前的代码看起来像这个

function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}

function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}

但它只显示最终结果,无论你的猜测是什么,还是滚动的数字。

编辑:evorod是一个全局变量

evorod需要全局作用域,目前它只存在于continueL()函数中,因此当您尝试在contin()中使用它时,它将是未定义的。通过在函数外声明它来解决这个问题。

同时,if语句可以简化为这样,而不是一堆单独的嵌套条件:

if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent 
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}

请改用switch语句。每次投掷有6种可能的结果。如果你猜得比实际结果少或多,那么你离真实结果每位数就会损失20分。

首先,让我们来看看你的预测有多离谱。我们做减法(原谅我数学不好(。

int outcome = ...
int guess   = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}

以此类推,差5分是最低分,因为这意味着你离结果还有5个数字。

最新更新