簡體   English   中英

二次點擊僅Android按鈕的啟動方法

[英]Android button only initiating method on second click

我有一個由按鈕制成的井字游戲板。 每個按鈕都鏈接到啟動邏輯的方法。 我遇到的問題是,當人類玩家(noughts)下他們的回合時,邏輯是跳過該回合,運行AI轉向,然后只回到人類玩家,這一次正在按預期工作。

在單擊時,按鈕是否有問題,應該調用setText方法並將其標記為人類玩家的“ O”或AI的“ X”。 此后,該按鈕將設置為非活動狀態,並且跟蹤板的陣列也會更改。

我正在打印日志,從我所看到的來看,人類用戶的點擊是觸發移動AI的原因,而不是自動完成的。 但是我不能說為什么會這樣。 我認為我的邏輯存在缺陷,但是我無法找出問題所在。 編輯:第一次人為點擊就可以正常工作,這就是問題所在。

碼:

package com.example.richardcurteis.connect3;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.Random;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    boolean noughtsTurn;
    ArrayList board;
    Players player;
    int aiPickedButton;
    int buttonPressed;
    int targetIndex;

    public void receiveClick(View view) {
        String takeButton = String.valueOf(view.getTag());
        buttonPressed = Integer.parseInt(takeButton);
        playNow(view);
        //checkForWin; Check winning conditions. Not yet implemented
    }

    public void playNow(View view) {
        if (noughtsTurn) {
            System.out.println("Player picked: " + buttonPressed);
            playerClick(view);
        } else {
            if (aiValidPick()) {
                playerClick(view);
            } else {
                playNow(view);
            }
        }
    }

    public void setTurn(boolean trueOrFalse) {
        if (trueOrFalse) {
            noughtsTurn = false;
        } else {
            noughtsTurn = true;
        }
    }

    public void playerClick(View view) {
        Button B;
        int boardSetIndex;
        int boardSetValue;

        if (view instanceof Button) {
            B = (Button) view;
            if ( noughtsTurn ) {
                B.setText(player.noughtsPlayer());
            } else {
                B = aiPlayerPick();
                System.out.println("AI picked: " + targetIndex);
                B.setText(player.crossesPlayer());
            }
            board.set(boardSetIndex(), boardSetValue());
            System.out.println("Board: " + board);
            B.setEnabled(false);
            setTurn(noughtsTurn);
        }
    }

    public int boardSetIndex() {
       int index;
        if (noughtsTurn) {
            index = buttonPressed;
        } else {
            index = targetIndex;
        }
        return  index;
    }

    public int boardSetValue() {
        int value;
        if (noughtsTurn) {
            value = player.humanTurnValue();
        } else {
            value = player.aiTurnValue();
        }
        return  value;
    }

    public Integer randomButtonPick() {
        Random randomNumber = new Random();
        int randomInt = randomNumber.nextInt(board.size());
        return randomInt;
    }

    public boolean aiValidPick() {
        aiPickedButton = randomButtonPick();
        if (board.get(aiPickedButton).equals(player.boardArrayDefaultValue())
                && !board.get(aiPickedButton).equals(player.humanTurnValue())
                && !board.get(aiPickedButton).equals(player.aiTurnValue())){
            return true;
        } else {
            return false;
        }
    }

    public Button aiPlayerPick() {
        Button btn = null;
        TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
        for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
            View tableLayoutChild = tableLayout.getChildAt(rowIndex);
            if (tableLayoutChild instanceof TableRow) {
                for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
                    View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
                    String targetButton = String.valueOf(aiPickedButton);
                    if (view instanceof Button && view.getTag().equals(targetButton) ) {
                        targetIndex = Integer.parseInt(targetButton);
                        View btn_v = view.findViewWithTag(targetButton);
                        btn = (Button) btn_v;
                        break;
                    }
                }
            }
        }
        return btn;
    }

    public class Players {
        public String noughtsPlayer() { return "O"; }
        public String crossesPlayer() { return "X"; }
        //public String blankButton() { return ""; }

        public int humanTurnValue() { return 0;}
        public int aiTurnValue() { return 1;}
        public int boardArrayDefaultValue() { return 2;}
    }

    public int getBoardSize() {
        int buttonCount = 0;
        TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
        for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
            View tableLayoutChild = tableLayout.getChildAt(rowIndex);
            if (tableLayoutChild instanceof TableRow) {
                for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
                    View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
                    if (view instanceof Button) {
                        buttonCount++;
                    }
                }
            }
        }
        return buttonCount;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        noughtsTurn = true;
        player = new Players();
        board = new ArrayList();
        int boardSize = getBoardSize();
        for (int boardIndex = 0; boardIndex < boardSize; boardIndex++) {
            board.add(player.boardArrayDefaultValue());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.richardcurteis.connect3.MainActivity"
    tools:showIn="@layout/activity_main"
    android:background="#070000">

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="false"
        android:layout_alignParentEnd="false"
        android:layout_alignParentStart="false"
        android:layout_centerInParent="true"
        android:id="@+id/tableLayout"
        android:background="#000000">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton1"
                android:layout_column="4"
                android:onClick="receiveClick"
                android:tag="0" />
                android:nestedScrollingEnabled="false" />

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton2"
                android:layout_column="12"
                android:onClick="receiveClick"
                android:tag="1" />

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton3"
                android:layout_column="19"
                android:onClick="receiveClick"
                android:tag="2" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton4"
                android:layout_column="4"
                android:onClick="receiveClick"
                android:tag="3"/>

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton5"
                android:layout_column="12"
                android:onClick="receiveClick"
                android:tag="4"/>

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton6"
                android:layout_column="19"
                android:onClick="receiveClick"
                android:tag="5"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"></TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton7"
                android:layout_column="4"
                android:onClick="receiveClick"
                android:tag="6"/>

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton8"
                android:layout_column="12"
                android:onClick="receiveClick"
                android:tag="7"/>

            <Button
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:id="@+id/gridButton9"
                android:layout_column="19"
                android:onClick="receiveClick"
                android:tag="8" />
        </TableRow>
    </TableLayout>

    <Button

        android:layout_width="200dp"
        android:layout_height="120dp"
        android:text="New Game"
        android:id="@+id/newGameButton"
        android:layout_below="@+id/tableLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="61dp" />
</RelativeLayout>

問題不屬於您的邏輯。 問題是如何實施。

當前,您已經有一個逐步的邏輯系統,其中的每個邏輯步驟都由receiveClick(View)方法觸發。 問題在於沒有自動觸發AI轉向。

  1. noughtsTurn =真
  2. receiveClick(View)可以在玩家回合時正常工作。
  3. 轉牌邏輯在playerClick(View)中完成,其中noughtsTurn的值被反轉。
  4. 問題是什么都不會觸發AI旋轉,並且下次單擊按鈕時它將調用receiveClick(View),但是noughtsTurn值為false。
  5. 因此,即使玩家剛剛單擊,它也會模擬一個AI回合。

您需要在playerClick(View)的末尾添加某種邏輯,以便如果玩家剛剛轉身,它將重新運行AI轉身的邏輯。

例:

public void playerClick(View view) {
    Button B;
    int boardSetIndex;
    int boardSetValue;

    if (view instanceof Button) {
        B = (Button) view;
        if ( noughtsTurn ) {
            B.setText(player.noughtsPlayer());
        } else {
            B = aiPlayerPick();
            System.out.println("AI picked: " + targetIndex);
            B.setText(player.crossesPlayer());
        }
        board.set(boardSetIndex(), boardSetValue());
        System.out.println("Board: " + board);
        B.setEnabled(false);
        //
        if(setTurn(noughtsTurn) == false){
            playNow(findViewByTag(randomButtonPick()))
        }
        //
    }
}

在上面的示例中,缺少一些關鍵的東西,例如,檢查randomButtonPick()是否尚未被占用,以及setTurn(boolean)返回void而不是布爾值的事實。 您只需要某種方式來檢查玩家是否剛剛轉過彎,如果是,就讓AI轉彎。

好的,這是我解決此問題的最終解決方案。 我保持相同的邏輯,但是將人工和AI分離為單獨的方法,而AI仍然基於noughtsTurn方法。

碼:

public void receiveClick(View view) {
        String takeButton = String.valueOf(view.getTag());
        buttonPressed = Integer.parseInt(takeButton);
        humanPlayerTurn(view);
        aiPlayerTurn(view);
    }

    public void humanPlayerTurn(View view) {
        if (noughtsTurn) {
            System.out.println("Player picked: " + buttonPressed);
            playerClick(view);
        }
    }

    public void aiPlayerTurn(View view) {
        if (aiValidPick()) {
            playerClick(view);
        } else {
            aiPlayerTurn(view);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM