有没有办法跟踪单击的对象,并在程序结束处理java时将它们显示为消息?

问题描述 投票:0回答:1

我正在尝试创建一个小游戏,用户点击随机生成的硬币,我希望它能够跟踪他们点击的数量。另外,我希望当我单击处理窗口上的停止按钮时打印出此消息。

我尝试使用 exit() 命令作为 public void,但这不起作用。

java processing
1个回答
0
投票

您走在正确的道路上。您可以检查对象是否位于

mouseClicked()
事件处理程序中的矩形上方以增加计数器。

应该能够覆盖

exit()
草图功能,但是我注意到当您在处理IDE中使用停止按钮时它不会触发。当您使用 ESCAPE 键关闭草图时,它
确实有效
。如果您计划将草图导出为应用程序(通过“文件”>“导出应用程序”),这实际上可能会更好。

这是一个超级基本的草图来说明上述想法:

int[][] coinBoundingBoxes = {
  {30, 30, 30, 30},
  {135, 30, 30, 30},
  {250, 30, 30, 30},
  {30, 150, 30, 30},
  {135, 150, 30, 30},
  {250, 150, 30, 30},
  {30, 250, 30, 30},
  {135, 250, 30, 30},
  {250, 250, 30, 30},
};

int numClicks = 0;

void setup(){
  size(300, 300);
}

void draw(){
  background(0);
  // draw coins
  fill(255, 192, 0);
  for(int[] bbox : coinBoundingBoxes)
    ellipse(bbox[0] + bbox[2] * 0.5, bbox[1] + bbox[3] * 0.5, bbox[2], bbox[3]);
  // draw text
  fill(255);
  text(numClicks, 10, 15);
}

void mouseClicked(){
  for(int[] bbox : coinBoundingBoxes){
    if(isInRect(mouseX, mouseY, bbox)){
      numClicks++;
    }
  }
}

boolean isInRect(int x, int y, int[] r){
  return (x >= r[0] && x <= r[0] + r[2]) &&
         (y >= r[1] && y <= r[1] + r[3]);
}

// override exit to print clicks first
void exit(){
  println("total clicks: ", numClicks);
  super.exit();
}
© www.soinside.com 2019 - 2024. All rights reserved.