I'm trying to draw a line, I managed to do it before but the first point somehow was always 0, 0. Now my logic is, there are two Vectors, one to store each point that is clicked, and another to store the Line, which is made by two points clicked by the user. I do the verifications to see if the Vector is not empty and only then I draw the line. I don't really know what's going on, I've tried everything, hope some of you can help, I'm in real need. Thank you.
Here it goes the code from MyView.java:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Vector;
public class MyView extends View {
Paint paint = null;
int figure;
int lados_poly;
int cor;
int deletar;
int CursorX, CursorY;
int nrCliques;
Vector<Ponto2D> ptsReta = new Vector<Ponto2D>();
Vector<Reta> guardaRetas = new Vector<Reta>();
public MyView(Context context) {
super(context);
paint = new Paint();
figure = 0;
cor = 0;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setStrokeWidth(10);
figure = 0;
cor = 0;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
cor = 0;
}
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 2){
Ponto2D ptReta = new Ponto2D();
ptReta.x = CursorX;
ptReta.y = CursorY;
ptsReta.add(ptReta);
if (ptsReta.size()> 0) {
for (int c = 0; c < ptsReta.size(); c++)
System.out.println("ptRetaX: " + ptsReta.get(c).x + " ptRetaY: " + ptsReta.get(c).y + " size " + ptsReta.size());
}
invalidate();
}
default:
return false;
}
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
clickEcra();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#3F5866"));
//cores
if (cor == 1) {
paint.setColor(Color.parseColor("#393E46"));
} else if (cor == 2){
paint.setColor(Color.parseColor("#00ADB5"));
} else if (cor == 3) {
paint.setColor(Color.parseColor("#F8B500"));
} else if (cor == 4) {
paint.setColor(Color.parseColor("#FC3C3C"));
}
if (figure == 2) {
if (ptsReta.size() >= 2) {
for (int b = 0; b < ptsReta.size(); b = b + 2) {
Reta retinha = new Reta(ptsReta.get(b), ptsReta.get(b + 1));
guardaRetas.add(retinha);
System.out.println("pts: " + ptsReta.get(b) + ptsReta.get(b + 1));
}
}
if (guardaRetas.size() > 0) {
for (int r = 0; r < guardaRetas.size(); r++) {
canvas.drawLine(guardaRetas.get(r).pinicial.x, guardaRetas.get(r).pinicial.y, guardaRetas.get(r).pfinal.x, guardaRetas.get(r).pfinal.y, paint);
}
}
}
//clear canvas
if (deletar == 2){
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
nrCliques = 0;
ptsCirc.removeAllElements();
ptsReta.removeAllElements();
}
}
public void setfigure(int a) {
this.figure = a;
}
public void Cor1_mudar(int text_cor) {
this.cor = text_cor;
}
public void Resetar(int delete){
this.deletar = delete;
}
}
And now the code from Line.java:
public class Reta {
Ponto2D pinicial;
Ponto2D pfinal;
public Reta(){
pinicial = new Ponto2D();
pfinal = new Ponto2D();
}
public Reta(Ponto2D a, Ponto2D b) {
pinicial = a;
pfinal = b;
}
}
Update: It draws one line, and when I try to do another one, on the third click, it closes and I need to draw multiple lines in my canvas.
This were my changes, the following inside onDraw() method:
if (figure == 2) {
if (ptsReta.size() %2 == 0) {
for (int b = 0; b < ptsReta.size(); b = b + 2) {
Reta retinha = new Reta(ptsReta.get(b), ptsReta.get(b + 1));
guardaRetas.add(retinha);
}
if (guardaRetas.size() > 0) {
for (int r = 0; r < guardaRetas.size(); r++) {
canvas.drawLine(guardaRetas.get(r).pinicial.x, guardaRetas.get(r).pinicial.y, guardaRetas.get(r).pfinal.x, guardaRetas.get(r).pfinal.y, paint);
}
}
}
}
And this ones inside the click method:
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 2){
Ponto2D ptReta = new Ponto2D();
ptReta.x = CursorX;
ptReta.y = CursorY;
ptsReta.add(ptReta);
invalidate();
}
default:
return false;
}
}
});
}
Related
I wanted to create a game in which one could move a ball in a labyrinth using accelerometer sensor. In one of the classes extending from View I have the labyrinth, the ball, the goal and a method which draws them, a method which controls the movement of the ball.
package pl.wsiz.greatlabyrinth;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
public class GameView extends View {
private enum Direction{
up, down, left, right
}
private Cell[][] cells;
private Cell player, exit;
private static final int columns = 11, rows = 20;
private static final float wallThickness = 5;
private float cellSize, hMargin, vMargin;
private Paint wallPaint, playerPaint, exitPaint;
private Random random;
public GameView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
wallPaint = new Paint();
wallPaint.setColor(Color.BLACK);
wallPaint.setStrokeWidth(wallThickness);
playerPaint = new Paint();
playerPaint.setColor(Color.RED);
exitPaint = new Paint();
exitPaint.setColor(Color.BLUE);
random = new Random();
createLabyrinth();
}
private Cell getNeighbour(Cell cell){
ArrayList<Cell> neighbours = new ArrayList<>();
//left neighbour
if(cell.column > 0) {
if (!cells[cell.column - 1][cell.row].visited) {
neighbours.add(cells[cell.column - 1][cell.row]);
}
}
//right neighbour
if(cell.column < columns-1) {
if (!cells[cell.column + 1][cell.row].visited) {
neighbours.add(cells[cell.column + 1][cell.row]);
}
}
//top neighbour
if(cell.row > 0) {
if (!cells[cell.column][cell.row - 1].visited) {
neighbours.add(cells[cell.column][cell.row - 1]);
}
}
//bottom neighbour
if(cell.row < rows-1) {
if (!cells[cell.column][cell.row + 1].visited) {
neighbours.add(cells[cell.column][cell.row + 1]);
}
}
if(neighbours.size() > 0) {
int index = random.nextInt(neighbours.size());
return neighbours.get(index);
}
return null;
}
private void removeWall(Cell current, Cell next){
if(current.column == next.column && current.row == next.row+1) {
current.topWall = false;
next.bottomWall = false;
}
if(current.column == next.column && current.row == next.row-1) {
current.bottomWall = false;
next.topWall = false;
}
if(current.column == next.column+1 && current.row == next.row) {
current.leftWall = false;
next.rightWall = false;
}
if(current.column == next.column-1 && current.row == next.row) {
current.rightWall = false;
next.leftWall = false;
}
}
private void createLabyrinth(){
Stack<Cell> stack = new Stack<>();
Cell current, next;
cells = new Cell[columns][rows];
for(int i=0; i<columns; i++){
for(int j=0; j<rows;j++){
cells[i][j] = new Cell(i, j);
}
}
player = cells[0][0];
exit = cells[columns-1][rows-1];
current = cells[0][0];
current.visited = true;
do {
next = getNeighbour(current);
if (next != null) {
removeWall(current, next);
stack.push(current);
current = next;
current.visited = true;
} else
current = stack.pop();
}while(!stack.empty());
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
int width = getWidth();
int height = getHeight();
if(width/height < columns/rows) {
cellSize = width/(columns+3);
}
else {
cellSize = height/(rows+3);
}
hMargin = (width-columns*cellSize)/2;
vMargin = (height-rows*cellSize)/2;
canvas.translate(hMargin, vMargin);
for(int i=0; i<columns; i++){
for(int j=0; j<rows;j++){
if(cells[i][j].topWall)
canvas.drawLine(i*cellSize, j*cellSize, (i+1)*cellSize,j*cellSize, wallPaint);
if(cells[i][j].leftWall)
canvas.drawLine(i*cellSize, j*cellSize, i*cellSize,(j+1)*cellSize, wallPaint);
if(cells[i][j].bottomWall)
canvas.drawLine(i*cellSize, (j+1)*cellSize, (i+1)*cellSize,(j+1)*cellSize, wallPaint);
if(cells[i][j].rightWall)
canvas.drawLine((i+1)*cellSize, j*cellSize, (i+1)*cellSize,(j+1)*cellSize, wallPaint);
}
}
float margin = cellSize/2;
canvas.drawCircle(player.column*cellSize+margin, player.row*cellSize+margin,(cellSize/2)-5, playerPaint);
canvas.drawCircle(exit.column*cellSize+margin, exit.row*cellSize+margin,(cellSize/2)-5, exitPaint);
}
private void movePlayer(Direction direction){
switch (direction){
case up:
if(!player.topWall)
player = cells[player.column][player.row-1];
break;
case down:
if(!player.bottomWall)
player = cells[player.column][player.row+1];
break;
case left:
if(!player.leftWall)
player = cells[player.column-1][player.row];
break;
case right:
if(!player.rightWall)
player = cells[player.column+1][player.row];
break;
}
checkExit();
invalidate();
}
private void checkExit(){
if(player == exit)
createLabyrinth();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
return true;
if(event.getAction() == MotionEvent.ACTION_MOVE){
float x = event.getX();
float y = event.getY();
float playerCenterX = hMargin + (player.column+0.5f)*cellSize;
float playerCenterY = vMargin + (player.row+0.5f)*cellSize;
float xDirection = x - playerCenterX;
float yDirection = y - playerCenterY;
float absXD = Math.abs(xDirection);
float absYD = Math.abs(yDirection);
if(absXD > cellSize || absYD > cellSize){
if(absXD>absYD){
//move in x-direction
if(xDirection>0){
movePlayer(Direction.right);
}
else{
movePlayer(Direction.left);
}
}
else {
//move in y-direction
if (yDirection > 0) {
movePlayer(Direction.down);
} else {
movePlayer(Direction.up);
}
}
}
return true;
}
return super.onTouchEvent(event);
}
private class Cell {
boolean leftWall = true;
boolean rightWall = true;
boolean topWall = true;
boolean bottomWall = true;
boolean visited = false;
int column, row;
public Cell(int column, int row) {
this.column = column;
this.row = row;
}
}
}
In the second class extending AppCompatActivity I have the code of accelerometer to be used in moving the ball.
package pl.wsiz.greatlabyrinth;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
public class GameActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometr = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometr, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
I do not know how to join accelerometer with the first quoted code so that the ball moves using sensor and not onTouchEvent method. I would be grateful for some code with a little explanation.
I can draw one circle but my problem is to know how can I draw multiple circles every time I clicked.
The center of the circle has to be the X and the Y coordinates that are clicked and I need to store that point on my Vector, and the vector cannot be destroyed everytime I click the View.
If I don't have the invalidate on the end of if (figure == 1) it doesn't draw the circle at all.
My center is a Point2D which has int x, int y stored.
package com.example.soalr.myapplication;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.Vector;
public class MyView extends View {
Paint paint = null;
int figure;
int lados_poly;
int cor;
int deletar;
Circulo cir;
Circulo raio;
int CursorX, CursorY;
int nrCliques;
Vector<Ponto2D> ptsCirc = new Vector<Ponto2D>();
public MyView(Context context) {
super(context);
paint = new Paint();
figure = 0;
cor = 0;
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setStrokeWidth(10);
figure = 0;
cor = 0;
Ponto2D centroCirc = new Ponto2D();
centroCirc.x = CursorX;
centroCirc.y = CursorY;
cir = new Circulo(centroCirc);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
cor = 0;
}
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
nrCliques++;
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 1) {
Ponto2D centroCirc = new Ponto2D();
centroCirc.x = CursorX;
centroCirc.y = CursorY;
ptsCirc.add(centroCirc);
invalidate();
}
default:
return false;
}
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
clickEcra();
Ponto2D p3 = new Ponto2D();
p3.x = 600;
p3.y = 150;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#3F5866"));
//cores
if (cor == 1) {
paint.setColor(Color.parseColor("#393E46"));
} else if (cor == 2){
paint.setColor(Color.parseColor("#00ADB5"));
} else if (cor == 3) {
paint.setColor(Color.parseColor("#F8B500"));
} else if (cor == 4) {
paint.setColor(Color.parseColor("#FC3C3C"));
}
//figuras
if (figure == 1) {
if (ptsCirc.size() > 0) {
for (int a = 0; a <= ptsCirc.size(); a++) {
Circulo raio = new Circulo(ptsCirc.get(a));
raio.radius = 100;
canvas.drawCircle(ptsCirc.get(a).x, ptsCirc.get(a).y, raio.radius, paint);
}
}
}
else if (figure == 2) {
clickEcra();
Ponto2D p1 = new Ponto2D();
Ponto2D p2 = new Ponto2D();
Reta retinha = new Reta(p1, p2);
if (nrCliques == 1) {
p1.x = CursorX;
p1.y = CursorY;
System.out.println("x1: " + p1.x + " y1: " + p1.y);
} else if (nrCliques == 2) {
p2.x = CursorX;
p2.y = CursorY;
System.out.println("x2: " + p2.x + " y2: " + p2.y);
}
System.out.println("x2_: " + retinha.pfinal.x + " y2_: " + retinha.pfinal.y);
System.out.println("x1_: " + retinha.pinicial.x + " y1_: " + retinha.pinicial.y);
canvas.drawLine(retinha.pinicial.x, retinha.pinicial.y, retinha.pfinal.x, retinha.pfinal.y, paint);
} else if (figure == 3) {
Poligono poly = new Poligono(lados_poly);
if (lados_poly >= 3) {
for (int i = 0; i <= lados_poly - 1; i++) {
Ponto2D ponto4 = new Ponto2D(poly.pontosPolig.get(i).x, poly.pontosPolig.get(i).y);
Ponto2D ponto5 = new Ponto2D();
if (i < lados_poly) {
ponto5.x = poly.pontosPolig.get(i + 1).x;
ponto5.y = poly.pontosPolig.get(i + 1).y;
Reta retaPoli = new Reta(ponto4, ponto5);
int var_lados = lados_poly - 1;
if (i != var_lados) {
canvas.drawLine(retaPoli.pinicial.x, retaPoli.pinicial.y, retaPoli.pfinal.x, retaPoli.pfinal.y, paint);
} else {
canvas.drawLine(poly.pontosPolig.firstElement().x, poly.pontosPolig.firstElement().y, retaPoli.pinicial.x, retaPoli.pinicial.y, paint);
}
}
}
}
}
if (deletar == 2){
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
nrCliques = 0;
}
}
public void setfigure(int a) {
this.figure = a;
}
public void Cor1_mudar(int text_cor) {
this.cor = text_cor;
}
public void verLados (int lados){
this.lados_poly = lados;
}
public void Resetar(int delete){
this.deletar = delete;
}
}
This is Circle.java:
package com.example.soalr.myapplication;
public class Circulo {
int radius;
Ponto2D centro;
public Circulo(Ponto2D c) {
radius = 0;
centro = c;
}
}
You have two problems here:
You only see 1 circle. This is probably because nrCliques is not the value you expect. Instead of iterating from 0 to nrCliques, consider iterating from 0 to ptsCirc.size(), or using a for..each loop. For problems like this, the debugger is your friend.
You don't see any circles unless you have that invalidate() call in onDraw(). Calling invalidate() from onDraw() causes the framework to call onDraw() repeatedly, as fast as it can. This doesn't hurt anything but it uses a lot of processor power for no good reason. It's better to "cue" your View to redraw at the moment that its attendant data changes. In this case, this means putting the invalidate() call after that call to ptsCirc.add(). Then, you'll only get roughly 1 call to onDraw() each time you tap the screen.
This is working code, the problem was I wasn't verifying if the Vector had anything inside him.
public class MyView extends View {
Paint paint = null;
int figure;
int lados_poly;
int cor;
int deletar;
int CursorX, CursorY;
int nrCliques;
Vector<Ponto2D> ptsCirc = new Vector<Ponto2D>();
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
figure = 0;
cor = 0;
}
public void clickEcra() {
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
CursorX = (int)event.getX();
CursorY = (int)event.getY();
if (figure == 1) {
Ponto2D centroCirc = new Ponto2D();
centroCirc.x = CursorX;
centroCirc.y = CursorY;
ptsCirc.add(centroCirc);
invalidate();
}
default:
return false;
}
}
});
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
clickEcra();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
paint.setColor(Color.parseColor("#3F5866"));
//cores
if (cor == 1) {
paint.setColor(Color.parseColor("#393E46"));
} else if (cor == 2){
paint.setColor(Color.parseColor("#00ADB5"));
} else if (cor == 3) {
paint.setColor(Color.parseColor("#F8B500"));
} else if (cor == 4) {
paint.setColor(Color.parseColor("#FC3C3C"));
}
//figuras
if (figure == 1) {
if (ptsCirc.size() > 0) {
for (int a = 0; a < ptsCirc.size(); a++) {
Circulo raio = new Circulo(ptsCirc.get(a));
raio.radius = 100;
canvas.drawCircle(ptsCirc.get(a).x, ptsCirc.get(a).y, raio.radius, paint);
}
}
}
if (deletar == 2){
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#F5F1E0"));
canvas.drawPaint(paint);
nrCliques = 0;
ptsCirc.removeAllElements();
ptsReta.removeAllElements();
}
}
public void setfigure(int a) {
this.figure = a;
}
public void Cor1_mudar(int text_cor) {
this.cor = text_cor;
}
public void Resetar(int delete){
this.deletar = delete;
}
}
Okay, so I need to start another activity on collision detection, I am a beginner trying to make this simple game and I just cannot figure this out ... It is marked by //This is the place I am trying to start another activity, where I want to start it, the current code gives me error
GameView.java file where I need to start the activity
package fi.itsn.jetfighter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import static android.support.v4.app.ActivityCompat.startActivity;
/**
* Created by h on 21.9.2016.
*/
public class GameView extends SurfaceView implements Runnable {
volatile boolean playing;
private Thread gameThread = null;
private Player player;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private Enemy[] enemies;
private Broccoli[] broccolis;
private int enemyCount = 3;
private int broccoliCount = 1;
private ArrayList<Star> stars = new
ArrayList<Star>();
//defining a boom object to display blast
private Boom boom;
public GameView(Context context, int screenX, int screenY) {
super(context);
player = new Player(context, screenX, screenY);
surfaceHolder = getHolder();
paint = new Paint();
int starNums = 100;
for (int i = 0; i < starNums; i++) {
Star s = new Star(screenX, screenY);
stars.add(s);
}
enemies = new Enemy[enemyCount];
for (int i = 0; i < enemyCount; i++) {
enemies[i] = new Enemy(context, screenX, screenY);
}
//initializing boom object
boom = new Boom(context);
broccolis = new Broccoli[broccoliCount];
for (int i = 0; i < broccoliCount; i++) {
broccolis[i] = new Broccoli(context, screenX, screenY);
}
}
#Override
public void run() {
while (playing) {
update();
draw();
control();
}
}
private void update() {
player.update();
//setting boom outside the screen
boom.setX(-250);
boom.setY(-250);
for (Star s : stars) {
s.update(player.getSpeed());
}
for (int i = 0; i < enemyCount; i++) {
enemies[i].update(player.getSpeed());
//if collision occurrs with player
if (Rect.intersects(player.getDetectCollision(), enemies[i].getDetectCollision())) {
//displaying boom at that location
boom.setX(enemies[i].getX());
boom.setY(enemies[i].getY());
enemies[i].setX(-200);
}
}
for (int i = 0; i < broccoliCount; i++) {
broccolis[i].update(player.getSpeed());
if (Rect.intersects(player.getDetectCollision(), broccolis[i].getDetectCollision())) {
startActivity(new Intent(this, end.class));
//This is the place I am trying to start another activity
}
}
}
private void draw() {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLUE);
paint.setColor(Color.WHITE);
for (Star s : stars) {
paint.setStrokeWidth(s.getStarWidth());
canvas.drawPoint(s.getX(), s.getY(), paint);
}
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
for (int i = 0; i < enemyCount; i++) {
canvas.drawBitmap(
enemies[i].getBitmap(),
enemies[i].getX(),
enemies[i].getY(),
paint
);
}
for (int i = 0; i < broccoliCount; i++) {
canvas.drawBitmap(
broccolis[i].getBitmap(),
broccolis[i].getX(),
broccolis[i].getY(),
paint
);
}
//drawing boom image
canvas.drawBitmap(
boom.getBitmap(),
boom.getX(),
boom.getY(),
paint
);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void control() {
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
return true;
}
}
And here is the Broccoli.java file
package fi.itsn.jetfighter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import java.util.Random;
/**
* Created by h on 22.9.2016.
*/
public class Broccoli {
//bitmap for the enemy
//we have already pasted the bitmap in the drawable folder
private Bitmap bitmap;
private int x;
private int y;
private int speed = 1;
private int maxX;
private int minX;
private int maxY;
private int minY;
//creating a rect object
private Rect detectCollision;
public Broccoli(Context context, int screenX, int screenY) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.broccoli);
maxX = screenX;
maxY = screenY;
minX = 0;
minY = 0;
Random generator = new Random();
speed = generator.nextInt(6) + 10;
x = screenX;
y = generator.nextInt(maxY) - bitmap.getHeight();
//initializing rect object
detectCollision = new Rect(x, y, bitmap.getWidth(), bitmap.getHeight());
}
public void update(int playerSpeed) {
x -= playerSpeed;
x -= speed;
if (x < minX - bitmap.getWidth()) {
Random generator = new Random();
speed = generator.nextInt(10) + 10;
x = maxX;
y = generator.nextInt(maxY) - bitmap.getHeight();
}
//Adding the top, left, bottom and right to the rect object
detectCollision.left = x;
detectCollision.top = y;
detectCollision.right = x + bitmap.getWidth();
detectCollision.bottom = y + bitmap.getHeight();
}
//adding a setter to x coordinate so that we can change it after collision
public void setX(int x){
this.x = x;
}
//one more getter for getting the rect object
public Rect getDetectCollision() {
return detectCollision;
}
//getters
public Bitmap getBitmap() {
return bitmap;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeed() {
return speed;
}
}
Try with
startActivity(new Intent(getContext(), end.class));
You need to pass context not this. Here you are extending a class with SurfaceView not Activity so this won't give you context like it gives in Activity
OR
Because you are passing context in constructor so you can also do it like
public GameView(Context context, int screenX, int screenY) {{
super(context);
this.mContext = context;
}
and pass this mContext in Intent
startActivity(new Intent(mContext, end.class));
OK, So Im drawing a bitmap beneath everything else for my background. Whenever the player moves it moves the enemy array 1 px and its supposed to do the same for the background. But whenever I move the background goes way faster and farther than everything else in the game. Can anyone tell me whats causing this? Heres the code. The code that moves everything is at the bottom in the set direction method.
package com.gametest;
import java.util.concurrent.CopyOnWriteArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class GameSurfaceView extends Activity implements OnTouchListener {
double ran;
int touchX, touchY, screenWidth, screenHeight, objX, objY;
static int bgx, bgy, bgW, bgH, enemyCount, score, playerHealth;
static boolean canUpdate;
static MyView v;
static Bitmap orb, orb2, explosion, bg;
static CopyOnWriteArrayList<Sprite> copy = new CopyOnWriteArrayList<Sprite>();
static String hpString;
static Player player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
v = new MyView(this);
v.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent me) {
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
return true;
case MotionEvent.ACTION_UP:
touchX = (int) me.getX();
touchY = (int) me.getY();
for (Sprite sprite : copy) {
sprite.checkTouch(touchX, touchY);
return true;
}
}
return true;
}
});
canUpdate = true;
screenWidth = v.getWidth();
screenHeight = v.getHeight();
playerHealth = 250;
hpString = "Health " + playerHealth;
ran = 0;
score = 0;
orb = BitmapFactory.decodeResource(getResources(), R.drawable.blue_orb);
orb2 = BitmapFactory.decodeResource(getResources(), R.drawable.red_orb);
bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg1);
bgx = bg.getHeight()/2;
bgy = bg.getHeight()/2;
bgH = bg.getHeight();
bgW = bg.getWidth();
explosion = BitmapFactory.decodeResource(getResources(), R.drawable.explosion);
player = new Player(v, orb2, explosion, screenWidth, screenHeight);
createEnemies();
setContentView(v);
}
private void createEnemies() {
if (enemyCount < 5) {
screenWidth = v.getWidth();
screenHeight = v.getHeight();
copy.add(new Sprite(v, orb, explosion, screenWidth, screenHeight, copy.size()));
enemyCount++;
}
}
public static void checkECount(int id) {
canUpdate = false;
copy.remove(id);
enemyCount--;
CopyOnWriteArrayList<Sprite> c = new CopyOnWriteArrayList<Sprite>();
int index = 0;
for (Sprite s : copy) {
s.ID = index;
c.add(s);
index++;
}
score = score + 10;
copy = c;
canUpdate = true;
}
#Override
protected void onPause() {
super.onPause();
v.pause();
}
#Override
protected void onResume() {
super.onResume();
v.resume();
}
public class MyView extends SurfaceView implements Runnable {
Thread t = null;
SurfaceHolder holder;
boolean isItOk = false;
public MyView(Context context) {
super(context);
holder = getHolder();
}
#Override
public void run() {
while (isItOk == true) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
if (canUpdate) {
canvas_draw(c);
}
holder.unlockCanvasAndPost(c);
try {
t.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected void canvas_draw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Rect bgRec = new Rect(bgx, bgy, bgx+bgW, bgy+bgH);
canvas.drawBitmap(bg, null, bgRec, null);
ran = Math.random() * 5;
if (ran > 4.5) {
createEnemies();
}
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(15);
canvas.drawText(hpString, 10, 25, paint);
for (Sprite sprite : copy) {
sprite.sprite_draw(canvas);
}
Player.sprite_draw(canvas, copy);
}
public void pause() {
isItOk = false;
while (true) {
try {
t.join();
} catch (InterruptedException e) {
}
break;
}
t = null;
}
public void resume() {
isItOk = true;
t = new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return false;
}
public static void damagePlayer() {
hpString = "Health " + playerHealth;
playerHealth = playerHealth - 5;
if (playerHealth < 0) {
hpString = "game over";
}
}
public static void setDirection(int i, int j) {
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
bgy++;
}
}
if (i == 0 && j == 1) {
for (Sprite s : copy) {
s.y--;
bgy--;
}
}
if (i == -1 && j == 0) {
for (Sprite s : copy) {
s.x++;
bgx++;
}
}
if (i == 1 && j == 0) {
for (Sprite s : copy) {
s.x--;
bgx--;
}
}
}
}
You are changing bgx based on the number of sprites you have in your copy Iterable. in your setDirection method, please move the bgy, bgx outside of the enhanced for loops, like in:
if (i == 0 && j == -1) {
for (Sprite s : copy) {
s.y++;
}
bgy++;
}
Please help with the following code - I need a dialog box with a button to appear when the game puzzle is completed. Thank you!
Here's the code:
Sudoku.java
package org.example.sudoku;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class Sudoku extends Activity implements OnClickListener {
private static final String TAG = "Sudoku";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up click listeners for all the buttons
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.main);
}
#Override
protected void onPause() {
super.onPause();
Music.stop(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.continue_button:
startGame(Game.DIFFICULTY_CONTINUE);
break;
// ...
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
// More buttons go here (if any) ...
case R.id.new_button:
openNewGameDialog();
break;
case R.id.exit_button:
finish();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, Prefs.class));
return true;
// More items go here (if any) ...
}
return false;
}
/** Ask the user what difficulty level they want */
private void openNewGameDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.new_game_title)
.setItems(R.array.difficulty,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,
int i) {
startGame(i);
}
})
.show();
}
/** Start a new game with the given difficulty level */
private void startGame(int i) {
Log.d(TAG, "clicked on " + i);
Intent intent = new Intent(Sudoku.this, Game.class);
intent.putExtra(Game.KEY_DIFFICULTY, i);
startActivity(intent);
}
}
Game.Java
package org.example.sudoku;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class Game extends Activity {
private static final String TAG = "Sudoku";
public static final String KEY_DIFFICULTY =
"org.example.sudoku.difficulty";
private static final String PREF_PUZZLE = "puzzle" ;
public static final int DIFFICULTY_EASY = 0;
public static final int DIFFICULTY_MEDIUM = 1;
public static final int DIFFICULTY_HARD = 2;
protected static final int DIFFICULTY_CONTINUE = -1;
private int puzzle[] = new int[9 * 9];
private final String easyPuzzle =
"360000000004230800000004200" +
"070460003820000014500013020" +
"001900000007048300000000045";
private final String mediumPuzzle =
"650000070000506000014000005" +
"007009000002314700000700800" +
"500000630000201000030000097";
private final String hardPuzzle =
"009000000080605020501078000" +
"000000700706040102004000000" +
"000720903090301080000000600";
private PuzzleView puzzleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
int diff = getIntent().getIntExtra(KEY_DIFFICULTY,
DIFFICULTY_EASY);
puzzle = getPuzzle(diff);
calculateUsedTiles();
puzzleView = new PuzzleView(this);
setContentView(puzzleView);
puzzleView.requestFocus();
// ...
// If the activity is restarted, do a continue next time
getIntent().putExtra(KEY_DIFFICULTY, DIFFICULTY_CONTINUE);
}
#Override
protected void onResume() {
super.onResume();
Music.play(this, R.raw.game);
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
Music.stop(this);
// Save the current puzzle
getPreferences(MODE_PRIVATE).edit().putString(PREF_PUZZLE,
toPuzzleString(puzzle)).commit();
}
/** Given a difficulty level, come up with a new puzzle */
private int[] getPuzzle(int diff) {
String puz;
switch (diff) {
case DIFFICULTY_CONTINUE:
puz = getPreferences(MODE_PRIVATE).getString(PREF_PUZZLE,
easyPuzzle);
break;
// ...
case DIFFICULTY_HARD:
puz = hardPuzzle;
break;
case DIFFICULTY_MEDIUM:
puz = mediumPuzzle;
break;
case DIFFICULTY_EASY:
default:
puz = easyPuzzle;
break;
}
return fromPuzzleString(puz);
}
/** Convert an array into a puzzle string */
static private String toPuzzleString(int[] puz) {
StringBuilder buf = new StringBuilder();
for (int element : puz) {
buf.append(element);
}
return buf.toString();
}
/** Convert a puzzle string into an array */
static protected int[] fromPuzzleString(String string) {
int[] puz = new int[string.length()];
for (int i = 0; i < puz.length; i++) {
puz[i] = string.charAt(i) - '0';
}
return puz;
}
/** Return the tile at the given coordinates */
private int getTile(int x, int y) {
return puzzle[y * 9 + x];
}
/** Change the tile at the given coordinates */
private void setTile(int x, int y, int value) {
puzzle[y * 9 + x] = value;
}
/** Return a string for the tile at the given coordinates */
protected String getTileString(int x, int y) {
int v = getTile(x, y);
if (v == 0)
return "";
else
return String.valueOf(v);
}
/** Change the tile only if it's a valid move */
protected boolean setTileIfValid(int x, int y, int value) {
int tiles[] = getUsedTiles(x, y);
if (value != 0) {
for (int tile : tiles) {
if (tile == value)
return false;
}
}
setTile(x, y, value);
calculateUsedTiles();
return true;
}
/** Open the keypad if there are any valid moves */
protected void showKeypadOrError(int x, int y) {
int tiles[] = getUsedTiles(x, y);
if (tiles.length == 9) {
Toast toast = Toast.makeText(this,
R.string.no_moves_label, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
Log.d(TAG, "showKeypad: used=" + toPuzzleString(tiles));
Dialog v = new Keypad(this, tiles, puzzleView);
v.show();
}
}
/** Cache of used tiles */
private final int used[][][] = new int[9][9][];
/** Return cached used tiles visible from the given coords */
protected int[] getUsedTiles(int x, int y) {
return used[x][y];
}
/** Compute the two dimensional array of used tiles */
private void calculateUsedTiles() {
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
used[x][y] = calculateUsedTiles(x, y);
// Log.d(TAG, "used[" + x + "][" + y + "] = "
// + toPuzzleString(used[x][y]));
}
}
}
/** Compute the used tiles visible from this position */
private int[] calculateUsedTiles(int x, int y) {
int c[] = new int[9];
// horizontal
for (int i = 0; i < 9; i++) {
if (i == y)
continue;
int t = getTile(x, i);
if (t != 0)
c[t - 1] = t;
}
// vertical
for (int i = 0; i < 9; i++) {
if (i == x)
continue;
int t = getTile(i, y);
if (t != 0)
c[t - 1] = t;
}
// same cell block
int startx = (x / 3) * 3;
int starty = (y / 3) * 3;
for (int i = startx; i < startx + 3; i++) {
for (int j = starty; j < starty + 3; j++) {
if (i == x && j == y)
continue;
int t = getTile(i, j);
if (t != 0)
c[t - 1] = t;
}
}
// compress
int nused = 0;
for (int t : c) {
if (t != 0)
nused++;
}
int c1[] = new int[nused];
nused = 0;
for (int t : c) {
if (t != 0)
c1[nused++] = t;
}
return c1;
}
}
PuzzleView.java
package org.example.sudoku;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
public class PuzzleView extends View {
private static final String TAG = "Sudoku";
private static final String SELX = "selX";
private static final String SELY = "selY";
private static final String VIEW_STATE = "viewState";
private static final int ID = 42;
private float width; // width of one tile
private float height; // height of one tile
private int selX; // X index of selection
private int selY; // Y index of selection
private final Rect selRect = new Rect();
private final Game game;
public PuzzleView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
// ...
setId(ID);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable p = super.onSaveInstanceState();
Log.d(TAG, "onSaveInstanceState");
Bundle bundle = new Bundle();
bundle.putInt(SELX, selX);
bundle.putInt(SELY, selY);
bundle.putParcelable(VIEW_STATE, p);
return bundle;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
Log.d(TAG, "onRestoreInstanceState");
Bundle bundle = (Bundle) state;
select(bundle.getInt(SELX), bundle.getInt(SELY));
super.onRestoreInstanceState(bundle.getParcelable(VIEW_STATE));
return;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
width = w / 9f;
height = h / 9f;
getRect(selX, selY, selRect);
Log.d(TAG, "onSizeChanged: width " + width + ", height "
+ height);
super.onSizeChanged(w, h, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
// Draw the background...
Paint background = new Paint();
background.setColor(getResources().getColor(
R.color.puzzle_background));
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
// Draw the board...
// Define colors for the grid lines
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.puzzle_dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.puzzle_hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.puzzle_light));
// Draw the minor grid lines
for (int i = 0; i < 9; i++) {
canvas.drawLine(0, i * height, getWidth(), i * height,
light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(),
light);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
// Draw the major grid lines
for (int i = 0; i < 9; i++) {
if (i % 3 != 0)
continue;
canvas.drawLine(0, i * height, getWidth(), i * height,
dark);
canvas.drawLine(0, i * height + 1, getWidth(), i * height
+ 1, hilite);
canvas.drawLine(i * width, 0, i * width, getHeight(), dark);
canvas.drawLine(i * width + 1, 0, i * width + 1,
getHeight(), hilite);
}
// Draw the numbers...
// Define color and style for numbers
Paint foreground = new Paint(Paint.ANTI_ALIAS_FLAG);
foreground.setColor(getResources().getColor(
R.color.puzzle_foreground));
foreground.setStyle(Style.FILL);
foreground.setTextSize(height * 0.75f);
foreground.setTextScaleX(width / height);
foreground.setTextAlign(Paint.Align.CENTER);
// Draw the number in the center of the tile
FontMetrics fm = foreground.getFontMetrics();
// Centering in X: use alignment (and X at midpoint)
float x = width / 2;
// Centering in Y: measure ascent/descent first
float y = height / 2 - (fm.ascent + fm.descent) / 2;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
canvas.drawText(this.game.getTileString(i, j), i
* width + x, j * height + y, foreground);
}
}
if (Prefs.getHints(getContext())) {
// Draw the hints...
// Pick a hint color based on #moves left
Paint hint = new Paint();
int c[] = { getResources().getColor(R.color.puzzle_hint_0),
getResources().getColor(R.color.puzzle_hint_1),
getResources().getColor(R.color.puzzle_hint_2), };
Rect r = new Rect();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int movesleft = 9 - game.getUsedTiles(i, j).length;
if (movesleft < c.length) {
getRect(i, j, r);
hint.setColor(c[movesleft]);
canvas.drawRect(r, hint);
}
}
}
}
// Draw the selection...
Log.d(TAG, "selRect=" + selRect);
Paint selected = new Paint();
selected.setColor(getResources().getColor(
R.color.puzzle_selected));
canvas.drawRect(selRect, selected);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN)
return super.onTouchEvent(event);
select((int) (event.getX() / width),
(int) (event.getY() / height));
game.showKeypadOrError(selX, selY);
Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(TAG, "onKeyDown: keycode=" + keyCode + ", event="
+ event);
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
select(selX, selY - 1);
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
select(selX, selY + 1);
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
select(selX - 1, selY);
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
select(selX + 1, selY);
break;
case KeyEvent.KEYCODE_0:
case KeyEvent.KEYCODE_SPACE: setSelectedTile(0); break;
case KeyEvent.KEYCODE_1: setSelectedTile(1); break;
case KeyEvent.KEYCODE_2: setSelectedTile(2); break;
case KeyEvent.KEYCODE_3: setSelectedTile(3); break;
case KeyEvent.KEYCODE_4: setSelectedTile(4); break;
case KeyEvent.KEYCODE_5: setSelectedTile(5); break;
case KeyEvent.KEYCODE_6: setSelectedTile(6); break;
case KeyEvent.KEYCODE_7: setSelectedTile(7); break;
case KeyEvent.KEYCODE_8: setSelectedTile(8); break;
case KeyEvent.KEYCODE_9: setSelectedTile(9); break;
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
game.showKeypadOrError(selX, selY);
break;
default:
return super.onKeyDown(keyCode, event);
}
return true;
}
public void setSelectedTile(int tile) {
if (game.setTileIfValid(selX, selY, tile)) {
invalidate();// may change hints
} else {
// Number is not valid for this tile
Log.d(TAG, "setSelectedTile: invalid: " + tile);
startAnimation(AnimationUtils.loadAnimation(game,
R.anim.shake));
}
}
private void select(int x, int y) {
invalidate(selRect);
selX = Math.min(Math.max(x, 0), 8);
selY = Math.min(Math.max(y, 0), 8);
getRect(selX, selY, selRect);
invalidate(selRect);
}
private void getRect(int x, int y, Rect rect) {
rect.set((int) (x * width), (int) (y * height), (int) (x
* width + width), (int) (y * height + height));
}
// ...
}
Maybe an AlertDialog?http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog