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

可汗学院高级JS记忆Tile游戏Hover效果异常问题求助

问题诊断与解决方案

我一眼就看出了问题所在——你的hover效果失效是因为翻牌延迟结束后调用了noLoop(),导致draw()函数停止循环,Tile.hover()方法再也不会被执行。让我给你拆解清楚:

问题根源分析

  1. 初始状态下(或者单张牌翻起时):mouseClicked()会调用loop(),让draw()函数持续循环,每帧都会执行Tile.draw()和里面的hover()方法,所以鼠标移动时描边颜色能实时更新。
  2. 当你翻起两张不匹配的牌后:延迟30帧的逻辑会触发,执行noLoop()停止draw()循环。这时候即使鼠标移动,hover()方法再也不会被调用,描边颜色停留在最后一次的状态,看起来就像hover完全失效了。

另外,你的isMouseInside()方法里的条件也有逻辑瑕疵:

return mouseX > this.x && mouseX < (this.x + this.size) && mouseY > this.y && mouseY < (this.y + this.size) && this.isFaceUp === false;

这里强制要求isFaceUp === false才允许hover,但实际上对于未匹配的牌,即使它暂时翻起(等待判断是否匹配),也应该允许hover反馈;而已经匹配的牌(isMatch === true)才应该禁用hover。

修复步骤

1. 移除不必要的noLoop(),让draw()持续循环

你的小游戏渲染开销极低,完全不需要停止draw循环。把代码末尾的noLoop()删掉,同时把延迟逻辑里的noLoop()也去掉:

draw = function() {
    background(255, 255, 255);
    if (delayStartFC && (frameCount - delayStartFC) > 30) {
        for (var i = 0; i < tiles.length; i++) {
            var tile = tiles[i];
            if (!tile.isMatch) {
                tile.isFaceUp = false;
            }
        }
        flippedTiles = [];
        delayStartFC = null;
        // 删掉这里的noLoop()
    }
    for (var i = 0; i < tiles.length; i++) {
        tiles[i].draw();
    }
    if (numMatches === tiles.length/2) {
        fill(0, 0, 0);
        textSize(20);
        text("You found them all in " + numTries + " tries!", 20, 375);
    }
};
// 删掉代码末尾的noLoop()

2. 修正isMouseInside()的条件逻辑

把条件从限制isFaceUp === false改成限制!this.isMatch,这样只有已经匹配成功的牌才会禁用hover,其他状态的牌(不管是否翻起)都能正常显示hover效果,同时把坐标判断改成和isUnderMouse()一致的>=和<=,避免边缘位置的hover失效:

Tile.prototype.isMouseInside = function() {
    return mouseX >= this.x && mouseX <= this.x + this.size && 
           mouseY >= this.y && mouseY <= this.y + this.size && 
           !this.isMatch;
};

3. 优化hover方法的执行顺序(可选)

把hover()的调用放在rect()绘制之前,确保stroke颜色在绘制rect前生效,逻辑更清晰:

Tile.prototype.draw = function() {
    fill(214, 247, 202);
    strokeWeight(2);
    this.hover(); // 先设置stroke颜色,再绘制rect
    rect(this.x, this.y, this.size, this.size, 10);
    if (this.isFaceUp) {
        image(this.face, this.x, this.y, this.size, this.size);
    } else {
        image(getImage("avatars/leaf-green"), this.x, this.y, this.size, this.size);
    }
};

为什么这样修复有效?

  • 持续的draw()循环保证了每帧都会检测鼠标位置并更新描边颜色,hover效果就能实时响应鼠标移动。
  • 修正后的isMouseInside()逻辑更合理:匹配成功的牌不需要再交互,所以禁用hover;其他牌不管是正面还是背面,都能给用户hover反馈。

按照这些步骤修改后,你的hover效果应该就能在所有非匹配牌上正常工作了,不管是初始状态、单张翻起还是翻回之后。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:03:15