猿问

带有数组列表的“if”和“else”

我正在 Android Studio 上开发游戏。


游戏有 12 个块和 12 个符号(在本例中为“0”个零)。当您按下新游戏按钮时,将启动第一级。总共有12个级别。(curLevel)。几秒钟后,屏幕上会随机显示一个符号,然后消失。(根据每个级别输入的数量增加1,例如,级别1:必须猜测1个符号,级别2:必须猜测2个符号)直到级别12。


到目前为止,它的工作没有问题。


现在我需要解决我的代码来接收用户的输入,检查是否与显示的正确块预览匹配。如果是,则进入下一个级别(重复清除块的循环,显示随机符号,再次清除,等待用户输入)直到第 12 级。如果不是,则显示失败消息并再次显示新游戏按钮。


我创建了这个 Arraylist 但它不能正常工作,现在它的条件总是负面的(即使它按下了正确的块)“失败!再试一次!” 它正在显示的消息。


我运行调试器并显示: List tempList = new ArrayList<> ();


tempList:size 12

for (int i = 0; i < curLevel; i++) { curLevel size:13

tempList.add ( buttons.get ( i ) ); buttons size:12

if (tempList.contains ( v.getTag () )) { tempList size 12

Its not matching the condition. –

这是值:


static int MAXLEVELS = 12;

        static String SUCCESS_SYMBOL = "0";

curLevel = 1;

        curGuess = 0;

有什么建议可以让它工作吗?甚至让这段代码更整洁?


private void buttonLogic(View v) {

        List<Button> tempList = new ArrayList<> ();

        for (int i = 0; i <= curLevel; i++) {

            if (i!= MAXLEVELS)

                tempList.add ( buttons.get ( i ) );

            else

                break;

        }

        if (tempList.contains ( v.getTag () )) {

            curGuess++;

            checkWin ();

        } else {

            lostGame ();

        }

    }


    private void lostGame () {

        Toast.makeText(this, "Fail! Try Again", Toast.LENGTH_SHORT).show();

        disableButtons();

        b_new.setVisibility(View.VISIBLE);

    }


        private void checkWin() {

            if (curGuess == curLevel) {

                disableButtons ();

                if (curLevel == 12) {

                    Toast.makeText ( this, "Congratulations! You Won", Toast.LENGTH_SHORT ).show ();

                    b_new.setVisibility ( View.VISIBLE );

                } else {

                    curGuess = 0;

                    curLevel++;

                    generateButtons ( curLevel );

                }

            }

        }

还有一个来自之前代码的图像。干杯。

跃然一笑
浏览 211回答 2
2回答

慕哥6287543

ArrayList<Button> tempList = new ArrayList<>();改为使用,因为否则您将缺少方法(尽管将变量从ArrayListto转换为List不会引起任何投诉)。该if情况可能是(i+1) < MAXLEVELS因为,i是0基础,curLevel是1基础。最简单的可能是初始化curLevel = 0并仅将其显示为curLevel + 1...否则您将始终必须考虑业务逻辑中的+1/-1偏移量,我认为这是“无用的复杂性”...以便游戏开始在 level&nbsp;0,同时 level1显示在 GUI 上。

海绵宝宝撒

看起来您正在尝试为buttons已执行点击事件的按钮查找可用的任何匹配项。为此,我建议您使用 找到完全匹配viewId,您可以更改您的方法,如下所示。private void buttonLogic(View v) {&nbsp; &nbsp; boolean hasAnyMatch = false;&nbsp; &nbsp; // Assumption is curLevel will always be less than MAXLEVELS&nbsp; &nbsp; for (int i = 0; i <= curLevel; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (v.getId() == buttons.get(i).getId()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hasAnyMatch = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if (hasAnyMatch) {&nbsp; &nbsp; &nbsp; &nbsp; curGuess++;&nbsp; &nbsp; &nbsp; &nbsp; checkWin ();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; lostGame ();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答