尝试在 Processing 中创建一个骰子,但点击不会触发它

Trying to create a dice in Processing but clicking is not triggering it

我想制作一个程序,在您单击显示 "Roll" 的矩形后显示骰子的面,但是当我单击时,没有任何反应。

谁能解释一下我做错了什么?

import java.util.Random;

public Random random = new Random();

public color purple = #B507F5;
public int diceChoose = random.nextInt(6);
public int x = mouseX;
public int y = mouseY;


public void setup() {
  size(750, 900);
  background(255);

}

public void draw() {
  strokeWeight(3);

  //dice roll button
  rect(100, 700, 550, 150);
  textSize(100);
  fill(purple);
  text("Roll", 280, 815);
  noFill();

  //dice face
  rect(100, 100, 550, 550);

  roll();
}

public void one() {
  fill(0);
  ellipse(375, 375, 100, 100);
  noFill();
}

public void two() {
  fill(0);
  ellipse(525, 225, 100, 100);
  ellipse(225, 525, 100, 100);
  noFill();
}

public void three() {
  fill(0);
  ellipse(375, 375, 100, 100);
  ellipse(525, 225, 100, 100);
  ellipse(225, 525, 100, 100);
  noFill();
}

public void four() {
  fill(0);
  ellipse(525, 225, 100, 100);
  ellipse(225, 525, 100, 100);
  ellipse(525, 525, 100, 100);
  ellipse(225, 225, 100, 100);
  noFill();
}

public void five() {
  fill(0);
  ellipse(375, 375, 100, 100);
  ellipse(525, 225, 100, 100);
  ellipse(225, 525, 100, 100);
  ellipse(525, 525, 100, 100);
  ellipse(225, 225, 100, 100);
  noFill();
}

public void six() {
  fill(0);
  ellipse(525, 225, 100, 100);
  ellipse(225, 525, 100, 100);
  ellipse(525, 525, 100, 100);
  ellipse(225, 225, 100, 100);
  ellipse(525, 375, 100, 100);
  ellipse(225, 375, 100, 100);
  noFill();
}

public void roll() {
  if (mousePressed && x > 100 && x < 650 && y > 700 && y < 850) {
    diceChoose = random.nextInt(6);
    if (diceChoose == 0) {
      one();
    }
    else if (diceChoose == 1) {
      two();
    }
    else if (diceChoose == 2) {
      three();
    }
    else if (diceChoose == 3) {
      four();
    }
    else if (diceChoose == 4) {
      five();
    }
    else if (diceChoose == 5) {
      six();
    }
  }
}

您在程序的最开始将 xy 变量设置为等于 mouseXmouseY。但这 而不是 意味着当 mouseXmouseY 发生变化时,您的 xy 变量也会发生变化。考虑一下:

float x = 100;
float y = x;
x = 200;
println(y); //prints 100!

因此,您需要在这个 if 语句中使用 mouseXmouseY,而不是引用 xy(永远不会改变):

  if (mouseX > 100 && mouseX < 650 && mouseY > 700 && mouseY < 850) {

然后你有一些其他问题(你实际上没有检测到点击),但这是你第一个问题的答案。

顺便说一句,我想出来的方法是简单地添加 println() 语句。我在你的 if 语句之前放了一个,在里面放了一个:

  println("here 1");
  if (x > 100 && x < 650 && y > 700 && y < 850) {
    println("here 2"); 

"here 1" 打印出来了,但是 "here 2" 没有打印出来,所以我知道要仔细看看你的 if 语句中的逻辑。以后你可以自己试试这种调试方式,省去自己搞post!

的麻烦