как получить доступ к случайному элементу в виде сетки кнопок - PullRequest
0 голосов
/ 22 декабря 2018

Im Building линкор игра для Android.в моей игровой деятельности у меня есть два вида сетки: один - доска игрока, а другой - доска компьютера.В игровом поле я встроил адаптер, который на каждой кнопке, который я нажимаю, окрашивает его в черный или красный цвет, в зависимости от того, есть ли корабль.Теперь моя проблема после того, как игрок выбирает кнопку, которую я хочу, чтобы компьютер выбирал случайным образом кнопку из своего вида сетки и выполнял эту логику, но я не знаю, как получить доступ к случайной кнопке из вида сетки компьютера.это моя игровая активность:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.GridView;

import java.util.ArrayList;


public class GameActivity extends AppCompatActivity {
    // private TextView textView;
    private boolean turn;
    protected static gameBoard player;
    protected static gameBoard opponent;

    public GridView getOpponentBoard() {
        return opponentBoard;
    }

    public void setOpponentBoard(GridView opponentBoard) {
        this.opponentBoard = opponentBoard;
    }

    public GridView getPlayerBoard() {
        return playerBoard;
    }

    public void setPlayerBoard(GridView playerBoard) {
        this.playerBoard = playerBoard;
    }

    private GridView opponentBoard;
    private GridView playerBoard;
    ArrayList<String> data = new ArrayList<>();
    ArrayList<String> opData = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        Bundle extras = getIntent().getExtras();
        int numberOfButtons = extras.getInt("numOfButtons", 0);
        int numberOfShips = extras.getInt("numOfShips", 0);




        for (int i = 0; i < numberOfButtons; i++) {
            for (int j = 0; j < numberOfButtons; j++) {
                data.add(i + "-" + j);
            }
        }
        for (int i = 0; i < numberOfButtons; i++) {
            for (int j = 0; j < numberOfButtons; j++) {
                opData.add(i + "-" + j);
            }
        }

        player = new gameBoard(numberOfButtons, numberOfShips);
        opponent = new gameBoard(numberOfButtons, numberOfShips);

        opponentBoard = findViewById(R.id.opponent);
        playerBoard = findViewById(R.id.player);

        playerBoard.setNumColumns(numberOfButtons);
        opponentBoard.setNumColumns(numberOfButtons);

        final GridViewCustomAdapter adapter = new GridViewCustomAdapter(this, data);
        playerBoard.setAdapter(adapter);
        final GridViewCustomAdapterCom adapterComputer = new GridViewCustomAdapterCom(this, opData);
        opponentBoard.setAdapter(adapterComputer);


    }
} 

, и это мой специальный адаптер для доски игроков с списком кликов:

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import static com.avrahamzilberblat.battleshipver1.GameActivity.opponent;
import static com.avrahamzilberblat.battleshipver1.GameActivity.player;

public class GridViewCustomAdapter extends BaseAdapter {

    ArrayList<String> items;

    static Activity mActivity;

    private static LayoutInflater inflater = null;

    public GridViewCustomAdapter(Activity activity, ArrayList<String> tempTitle) {
        mActivity = activity;
        items = tempTitle;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public final int getCount() {

        return items.size();

    }

    @Override
    public final Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public final long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = null;

        v = inflater.inflate(R.layout.item, null);

        Button tv = v.findViewById(R.id.button);
        tv.setText(items.get(position));
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // view.setBackgroundColor(Color.BLACK);
                Button b = (Button) view;
                String text = b.getText().toString();
                int column = Character.getNumericValue(text.charAt(0));
                int row = Character.getNumericValue(text.charAt(2));
                Log.d("an",String.valueOf(player.getBoardStatus()[row][column]));

                if(player.getBoardStatus()[row][column] == 1 ) {
                    b.setBackgroundColor(Color.RED);


                }
                    else
                    b.setBackgroundColor(Color.BLACK);


            }
        });

        return v;
    }

}

, и это адаптер, который я пытаюсь сделать для платы компьютера.что я не знаю, как получить доступ к случайной кнопке:

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;



public class GridViewCustomAdapterCom extends BaseAdapter {

    ArrayList<String> items;

    static Activity mActivity;

    private static LayoutInflater inflater = null;

    public GridViewCustomAdapterCom(Activity activity, ArrayList<String> tempTitle) {
        mActivity = activity;
        items = tempTitle;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public final int getCount() {

        return items.size();

    }

    @Override
    public final Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public final long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = null;

        v = inflater.inflate(R.layout.item, null);

        Button tv = v.findViewById(R.id.button);
        tv.setText(items.get(position));
        tv.setClickable(false);







        return v;
    }

}

, и это мой класс доски с логикой расположения доски и кораблей:

import android.util.Log;

import java.util.Random;


public class gameBoard {
    private int rows;



    private int[][] boardStatus=null;//0 indicates empty spot and 1 indicates theres a ship in the cell
    private int numOfShips;
    // private ArrayList<String> buttonsArray;
   // Random r = new Random();


    public gameBoard(int rows, int ships) {
        int r1,r2,direction;

        this.rows = rows;
        this.numOfShips = ships;
        this.boardStatus = new int[this.rows][this.rows];
        for (int i = 0; i < this.rows; i++) {
            for (int j = 0; j < this.rows; j++) {
                boardStatus[i][j] = 0;
            }

        }


        switch (this.numOfShips) {
            case 1:
                do{

                    r1 = (int)(Math.random()*++rows);
                    r2 = (int)(Math.random()*++rows);
                    direction=(int)(Math.random()*5);
                }while (canPlace(0,r1,r2,direction)==false);
                    place(0,r1,r2,direction);



            case 3:

                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(0,r1,r2,direction)==false);
                place(0,r1,r2,direction);
                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(1,r1,r2,direction)==false);
                place(1,r1,r2,direction);
                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(2,r1,r2,direction)==false);
                place(2,r1,r2,direction);
            case 4:
                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(0,r1,r2,direction)==false);
                place(0,r1,r2,direction);do{

                r1 = (int)(Math.random()*rows);
                r2 = (int)(Math.random()*rows);
                direction=(int)(Math.random()*4);
            }while (canPlace(0,r1,r2,direction)==false);
                place(0,r1,r2,direction);
                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(1,r1,r2,direction)==false);
                place(1,r1,r2,direction);
                do{

                    r1 = (int)(Math.random()*rows);
                    r2 = (int)(Math.random()*rows);
                    direction=(int)(Math.random()*4);
                }while (canPlace(2,r1,r2,direction)==false);
                place(2,r1,r2,direction);



        }


    }

    public boolean checkCell(int num1, int num2) {
        if (this.boardStatus[num1][num2] == 0)
            return true;
        else
            return false;
    }




    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int[][] getBoardStatus() {
        return boardStatus;
    }

    public void setBoardStatus(int[][] boardStatus) {
        this.boardStatus = boardStatus;
    }

    private void place(int ship, int row, int col, int direction) {
        int size = ship;
        switch (direction) {
            case 0: // North
                for (int  i = row; i >= row - (size - 1); i--)
                    getBoardStatus()[i][col] = 1;
                break;

            case 1: // East
                for (int i = col; i <= col + (size - 1); i++)
                    getBoardStatus()[row][i] = 1;
                break;

            case 2: // South
                for (int i = row; i <= row + (size - 1); i++)
                    getBoardStatus()[i][col] = 1;
                break;

            default: // West
                for (int i = col; i >= col - (size - 1); i--)
                    getBoardStatus()[row][i] = 1;
                break;
        }
    }

    private boolean canPlace(int ship, int row, int col, int direction) {
        int size = ship;
        boolean thereIsRoom = true;
        switch (direction) {
            case 0: // North
                if (row - (size - 1) < 0)
                    thereIsRoom = false;
                else
                    for (int  i = row; i >= row - (size - 1) && thereIsRoom; i--)
                        thereIsRoom = thereIsRoom & (getBoardStatus()[i][col] == 0);
                break;

            case 1: // East
                if (col + (size - 1) >= col)
                    thereIsRoom = false;
                else
                    for (int i = col; i <= col + (size - 1) && thereIsRoom; i++)
                        thereIsRoom = thereIsRoom & (getBoardStatus()[row][i] == 0);
                break;

            case 2: // South
                if (row + (size - 1) >= rows)
                    thereIsRoom = false;
                else
                    for (int i = row; i <= row + (size - 1) && thereIsRoom; i++)
                        thereIsRoom  = thereIsRoom & (getBoardStatus()[i][col] == 0);
                break;

            default: // West
                if (col - (size - 1) < 0)
                    thereIsRoom = false;
                else
                    for (int i = col; i >= col - (size - 1) && thereIsRoom; i--)
                        thereIsRoom = thereIsRoom & (getBoardStatus()[row][i] == '-');
                break;
        }
        return thereIsRoom;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...