【问题标题】:Having trouble getting my Tic Tac Toe app in android studio to work correctly无法让我在 android studio 中的井字游戏应用程序正常工作
【发布时间】:2018-07-11 00:31:45
【问题描述】:

本学期我在 android studio 上为我的应用开发课程设计了一个井字游戏应用程序。我首先遇到了由于 OnClickListener 导致代码崩溃的问题,我通过使用正确的值修复 buttonMatrix 来解决该问题。我的代码现在可以打开并运行,但在让我的游戏进入下一个回合时遇到问题。基本上我的应用程序会运行,然后我按下想要放置“X”或“O”值的按钮,具体取决于轮到玩家 1 还是玩家 2。我当前的代码只放置 X 并且不会进入玩家 2 的回合,当我连续获得 3 个 X 时,它也不会应用我的获胜条件。我目前的代码如下:

MainActivity.Java:

package com.example.corey.tictactoegame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;




class MainActivity extends AppCompatActivity implements View.OnClickListener 
{


    private Button[][] buttonMatrix = new Button[3][3];




    private boolean p1Turn = true;

    private int turnAdvance;
    private int player1Score;
    private int player2Score;


    TextView textViewP1;
    TextView textViewP2;
    TextView gameStatus;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //IDs the TextViews containing player scores//
        textViewP1 = findViewById(R.id.p1Score);
        textViewP2 = findViewById(R.id.p2Score);




        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {



                String buttonID = "button_" + i + j;
                int resourceID = getResources().getIdentifier(buttonID, "id", 
                    getPackageName());
                buttonMatrix[i][j] = findViewById(resourceID);
                buttonMatrix[i][j].setOnClickListener(this);

            }
        }


        // creating the click functionality for the New Game Button//
        Button newGameButton = findViewById(R.id.buttonNewGame);
        newGameButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                newGameReset();

            }
        });


    }


    @Override
    //Checks to see if button pressed is an empty button or a
    // previously used button and returns a value if
    // empty depending on player turn//

    public void onClick(View view) {
        if (!((Button) view).getText().toString().equals("")) {
            return;
        }
        turnAdvance = 0;
        // Creates text values for the buttons with either "X" or "O" depending on player turn//
        if (p1Turn) {
            ((Button) view).setText("X");
            turnAdvance++;


        }

        else {
            ((Button) view).setText("O");
            turnAdvance++;
        }


        //advances the round after a turn from both players//
        turnAdvance++;


    }

    // creating the win method based on conditions within the matrix as stated below//
    private boolean winConditions() {
        String[][] matrix = new String[3][3];


        if (winConditions()) {
            if (p1Turn) {
                p1Wins();
            } else {
                p2Wins();
            }
            //ends game in a draw if 9 turns are made//
            if (turnAdvance == 9) {
                gameDraw();
            }
            //ends the turnAdvance function//
            else {
                p1Turn = !p1Turn;
            }

        }

        //creating the win conditions for the game covering all
        // horizontal, vertical, and diagonal possibilities//


        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = buttonMatrix[i][j].getText().toString();
            }
        }
        for (int i = 0; i < 3; i++) {
            if (matrix[i][0].equals(matrix[i][1])
                    && matrix[i][0].equals(matrix[i][2])
                    && !matrix[i][0].equals("")) {
                return true;
            }
        }
        for (int i = 0; i < 3; i++) {
            if (matrix[0][i].equals(matrix[1][i])
                    && matrix[0][i].equals(matrix[1][i])
                    && !matrix[0][i].equals("")) {
                return true;
            }
        }
        if (matrix[0][0].equals(matrix[1][1])
                && matrix[0][0].equals(matrix[2][2])
                && !matrix[0][0].equals("")) {
            return true;
        }
        if (matrix[0][2].equals(matrix[1][1])
                && matrix[0][2].equals(matrix[2][0])
                && !matrix[0][2].equals("")) {
            return true;
        }
        return false;


    }

    //creating a method to clear the board when a game ends//
    private void boardClear() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                buttonMatrix[i][j].setText("");
            }
        }

        turnAdvance = 0;
        p1Turn = true;

    }

    //creating a method to set the score text for each player//
    private void updateScoreText() {
        textViewP1.setText("Player One (X): " + player1Score);
        textViewP2.setText("Player Two (O): " + player2Score);
    }

    //creating a method to reset all score values and clear board//
    private void newGameReset() {
        player1Score = 0;
        player2Score = 0;
        updateScoreText();
        boardClear();
    }

    //creating a method for player one winning//
    private void p1Wins() {
        player1Score++;
        gameStatus.setText("Player One (X) Wins!");
        updateScoreText();
        boardClear();
    }

    //creating a method for player two winning//
    private void p2Wins() {
        player2Score++;
        gameStatus.setText("Player Two (O) Wins!");
        updateScoreText();
        boardClear();
    }

    //creating a method for the game ending in a draw//
    private void gameDraw() {
        gameStatus.setText("Game Draw!");
        boardClear();
    }


    protected void savedState(Bundle currentState) {
        super.onSaveInstanceState(currentState);

        currentState.putInt("turnAdvance", turnAdvance);
        currentState.putInt("player1Score", player1Score);
        currentState.putInt("player2Score", player2Score);
        currentState.putBoolean("p1Turn", p1Turn);
    }

    protected void restoredState(Bundle newState) {
        super.onRestoreInstanceState(newState);

        turnAdvance = newState.getInt("turnAdvance");
        player1Score = newState.getInt("player1Score");
        player2Score = newState.getInt("player2Score");
        p1Turn = newState.getBoolean("p1Turn");
    }

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="136dp">


    <TextView
        android:id="@+id/p1Score"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:text="Player One (X): 0"
        android:textSize="24sp"
        android:freezesText="true"/>

    <TextView
        android:id="@+id/p2Score"
        android:layout_width="187dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/p1Score"
        android:text="Player Two (O): 0"
        android:textSize="24sp"
        android:freezesText="true"/>

    <TextView
        android:id="@+id/gameOutcome"
        android:layout_width="329dp"
        android:layout_height="28dp"
        android:layout_below="@+id/buttonNewGame"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text=""
        android:textAlignment="center"
        android:textSize="28sp" />

    <Button
        android:id="@+id/buttonNewGame"
        android:layout_width="141dp"
        android:layout_height="82dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:text="New Game"
        android:textSize="24sp" />


</RelativeLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <Button
        android:id="@+id/button_00"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_01"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_02"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>


</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <Button
        android:id="@+id/button_10"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_11"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_12"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>


</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

    <Button
        android:id="@+id/button_20"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_21"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>

    <Button
        android:id="@+id/button_22"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textSize="50sp"
        android:freezesText="true"/>


</LinearLayout>


</LinearLayout>

对此的任何帮助将不胜感激。不是让你为我做家庭作业,但我认为这是一个简单的解决方法,我只是想多了/忽略了,希望在我提交之前能正常工作

谢谢!!

连续波

【问题讨论】:

  • 您可能希望突出显示代码中的一个或多个具体问题,而不是仅仅告诉我们您的代码不起作用。
  • 在我的问题的顶部,我说明了我遇到的问题。抱歉,我没有为您突出显示,但其他人能够在没有势利评论的情况下发表评论并提供帮助。我是堆栈溢出的新手,所以我的问题布局并不完美,正如您从我的 6 名声中看到的那样。还是谢谢。
  • 我并没有对你无礼的意思。我只是觉得你的问题有点笼统,如果你把它缩小范围会更容易帮助你。
  • 对不起,我刚刚在这里看到了许多其他粗鲁的帖子,而且我经常看到粗鲁的 cmets。感谢您帮助我解决我可能遇到的未来问题:)

标签: java android android-studio


【解决方案1】:

首先,在您的onClick 函数中,您正在检查 p1turn 是否为真,但永远不会将 p1turn 更改为假,因此总是轮到他们。其次,您在 winConditions() 内部调用 winConditions() 的唯一位置,因此永远不会使用该函数。

【讨论】:

  • 太棒了。好的,现在我移动了我的声明: if (winConditions()) { if (p1Turn) { p1Wins(); } 其他 { p2Wins(); } //如果进行了 9 个回合,则以平局结束游戏 // if (turnAdvance == 9) { gameDraw(); } //结束turnAdvance函数// else { p1Turn = !p1Turn; } } 这样函数就被使用了。现在,当玩家 1 赢得游戏而不是显示胜利时,它会终止应用程序。我会在哪里
  • 添加在 p1Turn = false;声明?
  • 我会将p1Turn = !p1Turn; 的行从winConditions() 移到onClick 的底部,这样每次点击时都会交换。
  • 好的,现在允许轮换。现在的问题是它从 p2Turn 而不是 p1Turn 开始,因为它首先放置“O” - 并且在满足 winConditions 时,它终止应用程序。 (如果您需要查看更新的布局,我可以重新链接新的 .java 和 .xml)
  • 我一直在摆弄我的代码,我得到了正确的轮次顺序。现在我唯一的问题是应用程序在有人获胜或偶尔在游戏中间没有结果时随机终止。关于可能导致这种情况的任何想法?
【解决方案2】:

这是我更新的代码。此时我遇到的唯一问题是在实际满足 winConditions 之前满足 winConditions 。 IE 2 连续在水平和垂直方向获胜。对角线胜利似乎与连续 3 次合作。

MainActivity.java:

package com.example.corey.tictactoegame;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;



//implementing OnClickListener for Buttons//
class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //I decided to use a matrix instead of just calling all buttons
    // individually and creating a long list of winConditions.
    // I did do a little more in depth research on using 2D arrays
    // and it took a while to figure this out but I'm glad I did//
    private Button[][] buttonMatrix = new Button[3][3];




    private boolean p1Turn = true;

    private int turnAdvance;
    private int player1Score;
    private int player2Score;


    TextView textViewP1;
    TextView textViewP2;
    TextView gameStatus;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //IDs the TextViews containing player scores and the game outcomes//
        textViewP1 = findViewById(R.id.p1Score);
        textViewP2 = findViewById(R.id.p2Score);
        gameStatus = findViewById(R.id.gameOutcome);




        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {



                String buttonID = "button_" + i + j;
                int resourceID = getResources().getIdentifier(buttonID, "id", getPackageName());
                buttonMatrix[i][j] = findViewById(resourceID);
                buttonMatrix[i][j].setOnClickListener(this);

            }
        }


        // creating the click functionality for the New Game Button//
        Button newGameButton = findViewById(R.id.buttonNewGame);
        newGameButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                newGameReset();

            }
        });


    }


    @Override
    //Checks to see if button pressed is an empty button or a
    // previously used button and returns a value if
    // empty depending on player turn//

    public void onClick(View view) {
        if (!((Button) view).getText().toString().equals("")) {
            return;
        }

        // Creates text values for the buttons with either "X" or "O" depending on player turn//
        if (p1Turn) {
            ((Button) view).setText("X");
        }
        else {
            ((Button) view).setText("O");
        }
        //advances turns//
        turnAdvance++;

        //ends game in a draw if 9 turns are made//
        if (turnAdvance == 9) {
                gameDraw();
            }
            else {
                p1Turn = !p1Turn;
            }







        if (winConditions()) {
            if (p1Turn) {
                p2Wins();
            } else {
                p1Wins();
            }




        }





    }

    // creating the win method based on conditions within the matrix as stated below//
    private boolean winConditions() {
        String[][] matrix = new String[3][3];




        //creating the win conditions for the game covering all
        // horizontal, vertical, and diagonal possibilities//


        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix[i][j] = buttonMatrix[i][j].getText().toString();
            }  
        }
        for (int i = 0; i < 3; i++) {
            if (matrix[i][0].equals(matrix[i][1])
                    && matrix[i][0].equals(matrix[i][2])
                    && !matrix[i][0].equals("")) {
                return true;
            }
        }
        for (int i = 0; i < 3; i++) {
            if (matrix[0][i].equals(matrix[1][i])
                    && matrix[0][i].equals(matrix[1][i])
                    && !matrix[0][i].equals("")) {
                return true;
            }
        }
        if (matrix[0][0].equals(matrix[1][1])
                && matrix[0][0].equals(matrix[2][2])
                && !matrix[0][0].equals("")) {
            return true;
        }
        if (matrix[0][2].equals(matrix[1][1])
                && matrix[0][2].equals(matrix[2][0])
                && !matrix[0][2].equals("")) {
            return true;
        }

        return false;
    }



    //creating a method to clear the board when a game ends//
    private void boardClear() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                buttonMatrix[i][j].setText("");
            }
        }
        //starts game at 0 turns and player 1's turn//
        turnAdvance = 0;
        p1Turn = true;

    }

    //creating a method to set the score text for each player//
    private void updateScoreText() {
        textViewP1.setText("Player One (X): " + player1Score);
        textViewP2.setText("Player Two (O): " + player2Score);
    }

    //creating a method to reset all score values and clear
    // board when the New Game button is pressed//
    private void newGameReset() {
        player1Score = 0;
        player2Score = 0;
        updateScoreText();
        boardClear();
    }

    //creating a method for player one winning//
    private void p1Wins() {
        player1Score++;
        gameStatus.setText("Player One (X) Wins!");
        updateScoreText();
        boardClear();
    }

    //creating a method for player two winning//
    private void p2Wins() {
        player2Score++;
        gameStatus.setText("Player Two (O) Wins!");
        updateScoreText();
        boardClear();
    }

    //creating a method for the game ending in a draw//
    private void gameDraw() {
        gameStatus.setText("Game Draw!");
        boardClear();
    }


    protected void onSaveInstanceState(Bundle currentState) {
        super.onSaveInstanceState(currentState);

        currentState.putInt("turnAdvance", turnAdvance);
        currentState.putInt("player1Score", player1Score);
        currentState.putInt("player2Score", player2Score);
        currentState.putBoolean("p1Turn", p1Turn);
    }

    protected void onRestoreInstanceState(Bundle newState) {
        super.onRestoreInstanceState(newState);

        turnAdvance = newState.getInt("turnAdvance");
        player1Score = newState.getInt("player1Score");
        player2Score = newState.getInt("player2Score");
        p1Turn = newState.getBoolean("p1Turn");
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="136dp">


        <TextView
            android:id="@+id/p1Score"
            android:layout_width="187dp"
            android:layout_height="wrap_content"
            android:text="Player One (X): 0"
            android:textSize="24sp"
            android:freezesText="true"/>

        <TextView
            android:id="@+id/p2Score"
            android:layout_width="187dp"
            android:layout_height="wrap_content"
            android:layout_below="@id/p1Score"
            android:text="Player Two (O): 0"
            android:textSize="24sp"
            android:freezesText="true"/>

        <TextView
            android:id="@+id/gameOutcome"
            android:layout_width="329dp"
            android:layout_height="28dp"
            android:layout_below="@+id/buttonNewGame"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:text=""
            android:textAlignment="center"
            android:textSize="20sp" />

        <Button
            android:id="@+id/buttonNewGame"
            android:layout_width="141dp"
            android:layout_height="82dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentTop="true"
            android:text="New Game by Corey Whitlow"
            android:textSize="16sp" />


    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/button_00"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_01"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_02"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/button_10"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_11"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_12"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/button_20"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_21"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>

        <Button
            android:id="@+id/button_22"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textSize="40sp"
            android:freezesText="true"/>


    </LinearLayout>








</LinearLayout>

我还必须更改 winConditions 上面写的:

if (winConditions()) {
    if (p1Turn) {
        p2Wins();
    } else {
        p1Wins();
    }

}

基本上我觉得当你读到这篇文章时,它说如果轮到玩家 2 获胜,这在大声朗读时没有意义吗?不知道为什么我不得不交换它。再次感谢您提供如此巨大的帮助!我喜欢安卓,这是我这个学期第一次学习它,哈哈! :D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    相关资源
    最近更新 更多