Question

I am trying to make a simple snake and ladder game. I have a main Rectangle which is being drawn like this (all the codes are inside onDraw method of View:

//Main BOX rectangle
RectMainBox = new Rect();
RectMainBox.set(getLeft() + 25, getTop() + 25, getRight() - 25, getBottom() - 25);
canvas.drawRect(RectMainBox, PaintMainBox);

So that will take care of drawing a black box with padding of 25 from each corner of the parent for this view.

Now I want to have squares (game cells which can have snake or ladder) inside the main box. I am looking for something like this(Never mind the unequality of squares, its drawn in paint for reference):

enter image description here

So I am trying to have a m by n equal squares in the main box:

//initiate Cell map
_mapCell = new HashMap<Integer, Cell>();


int cols = 6;
int rows = 8;

//Start and End points of main game box
float left = RectMainBox.left;
float top = RectMainBox.top;
float right = RectMainBox.right / 2f;
float bottom = RectMainBox.bottom / 2f;


float boxWidth = RectMainBox.width() / (float)cols;
float boxHeight = RectMainBox.height() / (float) rows;

PointF start = new PointF(left, top);
PointF end = new PointF(right, bottom);

int id = 0;
for(int r = 1; r <= rows; r++){
    for(int c = 1; c <= cols; c++){
        RectF rect = new RectF();
        rect.set(start.x, start.y, boxWidth - end.x, boxHeight - end.y);
        canvas.drawRect(rect, PaintCell);

        if(id == 0){
            Cell cell = new Cell(id, CellType.START);
            cell.setRectangle(rect);
            _mapCell.put(id, cell);
        } else if(id == rows*cols){
            Cell cell = new Cell(id, CellType.END);
            cell.setRectangle(rect);
            _mapCell.put(id, cell);
        }else{
            Cell cell = new Cell(id, CellType.NORMAL);
            cell.setRectangle(rect);
            _mapCell.put(id, cell);
        }

        id++;
    }

    start.y += boxHeight;
}

But unfortunately that code is not bringing me anywhere. Please give me some advice how can I achive such result above.

Was it helpful?

Solution

Maybe you can use grid view as a special layout. This also gives you the advantage to add special listeners to each cell. Additionally the dimension justification is made by the layoutmanager and you don't have to do it on your onw.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top