You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在我的点击类游戏中重新绘制生命值计数

问题分析与修复

核心问题

  • 调用noLoop()导致draw()仅执行一次,生命值文本无法实时更新
  • drawCircles()中的clear()会清空整个画布,且未重新绘制生命值
  • 点击错误圆圈时,仅在生命值归0时触发死亡逻辑,未处理生命值减少后的重绘
  • 正确点击生成新圆圈后,未重新绘制生命值

修复方案

  1. 移除noLoop(),让draw()持续运行以更新画面
  2. 将背景刷新、生命值绘制、圆圈绘制统一放到draw()中,避免局部清空丢失关键元素
  3. 点击错误圆圈时,先减少生命值再判断是否触发死亡,保证生命值变化能被实时渲染
  4. 完善死亡界面的文本显示逻辑

修复后的完整代码

const circlesToMake = 50;
let circles, r, g, b, lives;

function setup() {
  createCanvas(600, 450);
  noStroke();
  textSize(16);
  fill(255);
  setupCircles();
}

function setupCircles() {
  circles = []
  lives = 3;
  r = random(20, 255)
  g = random(20, 255)
  b = random(20, 255)

  while (circles.length < circlesToMake) {
    const circle = {
      x: random(width),
      y: random(height),
      r: 20,
      d: 40
    };

    let overlapping = false;
    for (let j = 0; j < circles.length; j++) {
      const other = circles[j];
      const d = dist(circle.x, circle.y, other.x, other.y);

      if (d < circle.r + other.r) {
        overlapping = true;
        break;
      } else if (circle.x < 0 + circle.d 
        || circle.x > width - circle.d) {
        overlapping = true;
        break;
      } else if (circle.y < 0 + circle.d || circle.y > height - circle.d) {
        overlapping = true;
        break;
      }
    }

    if (!overlapping) {
      circles.push(circle);
    }
  }
}

function drawCircles() {
  circles.forEach(c => {
    fill(r, g, b, 200);
    ellipse(c.x, c.y, c.r * 2, c.r * 2);
  });

  fill(r, g, b, 220);
  const target = circles[0];
  ellipse(target.x, target.y, target.r * 2, target.r * 2);
}

function youDied() {
  clear();
  fill(255);
  textSize(32);
  text("你已死亡", width/2 - 60, height/2);
}

function draw() {
  background(32);
  fill(255);
  text(`lives: ${lives}`, 20, 20);
  drawCircles();
}

function mousePressed() {
  if (lives <= 0) return;

  const target = circles[0];
  if (dist(mouseX, mouseY, target.x, target.y) < target.r) {
    setupCircles();
  } else {
    const anyClicked = circles.some(c => dist(mouseX, mouseY, c.x, c.y) < c.r);
    if (anyClicked) {
      lives--;
      if (lives === 0) {
        youDied();
      }
    }
  }
}

关键修复点说明

  • 移除noLoop(),让draw()循环执行,实时同步生命值和画面状态
  • 用background(32)替代clear(),确保每次绘制都有干净的背景基底
  • 点击错误圆圈时先更新生命值,再判断死亡条件,保证数值变化能被draw()捕获并显示
  • 死亡后添加"你已死亡"文本,完善结束界面
  • 统一文本样式,提升显示清晰度

内容的提问来源于stack exchange,提问作者armput

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:07:50