【问题标题】:Clicking an Image only once with an input listener使用输入侦听器仅单击一次图像
【发布时间】:2025-12-10 15:25:01
【问题描述】:

您好,我正在开发一个刽子手游戏,几乎完成了。我的最后一个问题是让我的虚拟键盘只能点击一次。我要么在 if 检查字母 true 或 false 之后打破循环,但它只返回一个字母,即使这个词必须是相同的字母。或者让循环保持打开状态,如果你知道我的意思,它会根据鼠标点击的次数返回 4 - 5 次尝试。我可以让 Inputlistner 只注册一次吗??.. 这是图像及其列表

    a = new Image(new Texture("Sprites/Keyboard/a.png"));
    a.addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            apressed = true;
            return true;

        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            apressed = false;
        }

    });

然后这是我的播放状态中的调用方法...我试图在循环之后返回一个错误的布尔值,但在结束循环之前它仍然注册了太多的点击...

     if (tries < 100) {

        if (keyboard.apressed && abpressed == true) {
            for (int i = 0; i < randomWordtoGuess.length; i++) {
                if (a == randomWordtoGuess[i] ) {
                    playerGuess[i] = a;
                    currentWord = new String(playerGuess);
                    keyboard.a.setColor(0, 1, 0, 1);
                    abpressed = false;

                }

                if (a != randomWordtoGuess[i]) {
                    keyboard.a.setColor(1, 0, 0, 1);
                    tries++;
                    System.out.print(tries);
                    abpressed = false;
                }
                else{

                }
                // if i place a break; here it solves the problem 
                // but doesnt return more than one letter in the word.. 
                // for example Concrete it will only show first C.
            }

        }

}

解决问题的另一种方法是在 int "tries" 中添加 1 而不是 try++.. 但我认为这不能完成??

【问题讨论】:

    标签: java image loops break


    【解决方案1】:

    您可以创建一个新的布尔值来检查键盘是否已被点击。假设我们声明了一个全局布尔值keyClicked。然后,只需将其添加到您的InputListener

    a.addListener(new InputListener(){    
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            if (!keyClicked) {
                apressed = true;
                keyClicked = true;
                return true;
            }
        }
    
        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            if (!keyClicked) {
                apressed = false;
                keyClicked = true;
            }
        }
    
    });
    

    【讨论】:

    • 不起作用 :(.. 但我明白你想做什么.. 它也减慢了应用程序的速度