Sunday, June 9, 2013

[android help] Drawing on Canvas and refresginh (Sea Battle)


Drawing on Canvas and refresginh (Sea Battle)



I'm new to Android programming and now I'm trying to make a simple Sea Battle game for one person. Ships are places, player hits the field and see whether the shot hit or not. Basically, the field looks like this:


the field


The code is:



public void onDraw(Canvas canvas) {

if (getWidth() > getHeight()) {
rebro = getHeight();
} else {
rebro = getWidth(); // the smaller size of screen is "rebro"
}
rebro_piece = rebro / 10; // divide the screen by 10 (to get 10x10 field)

Paint background = new Paint();
background.setColor(getResources().getColor(R.color.game_background));
canvas.drawRect(0, 0, rebro, rebro, background); // draw background

Paint divider = new Paint();
divider.setColor(getResources().getColor(R.color.divider_black));

// drawing divider lines
for (int i=0; i<11; i++) {
canvas.drawLine(0, i*rebro_piece, rebro, i*rebro_piece, divider); // horizontal
canvas.drawLine(i*rebro_piece, 0, i*rebro_piece, rebro, divider); // vertical
}

canvas.drawLine(rebro-1, 0, rebro-1, rebro, divider);
}


That's how I make the "field."


In another class I have a method that collects numbers x and y of a 10×10 array that represents where the ships are placed. For debugging, I need to draw them on my field. Ship coordinates are retrieved in a cycle.


So I wrote a drawShip(int x, int y) method.


On Stack Overflow I've founded a question about "Why I can't paint outside onDraw()?" and I've changed my method to this:



public void drawShip(int x, int y) {
myX = x; //global
myY = y; //global
needToPaintShip = true; //boolean
invalidate(); // refreshibg?
needToPaintShip = false;
}


Here needToPaintShip decides whether the redrawing of canvas is needed or not.


Also I've edited the onDraw(Canvas canvas) method:



if(needToPaintShip == true) {
Paint ship = new Paint();
ship.setColor(getResources().getColor(R.color.ship_color));
Log.d(TAG, "onDraw(): rebro_piece = " + rebro_piece + " , myX = "+ myX + " , myY = " + myY); // I only get the last coordinates!
Rect r = new Rect(myX*(rebro_piece),myY*rebro_piece, myX*(rebro_piece+1), myY*(rebro_piece+1));
canvas.drawRect(r, ship);
}


but the result is awful:


the awful result


Guys, I'm desperate. How can I fix this and make "ships" be drawn on the field?



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...