This script draws the map and other stuff:
public void render(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
Drawable myImage;
int tileWidth = 50;
int tileHeight = 50;
int mapWidth = 3;
int mapHeight = 3;
int rowBaseX = 0;
int rowBaseY = 0;
int[][] board = new int[][] {
{0,0,0},
{0,0,0},
{0,0,2}
};
for (int row = 0; row < mapHeight; row++)
{
for (int col = 0; col < mapWidth; col++)
{
Resources res = this.getContext().getResources();
switch(board[row][col])
{
case 0:
myImage = res.getDrawable(R.drawable.tile1);
break;
case 1:
myImage = res.getDrawable(R.drawable.tile2);
break;
default:
myImage = res.getDrawable(R.drawable.tile3);
break;
}
int curL;
int curU;
int curR;
int curD;
curL = rowBaseX + (col * tileWidth);
curU = rowBaseY + (row * tileHeight);
curR = curL + tileWidth;
curD = curU + tileHeight;
if (droid.x - decentreX < curR & droid.x + decentreX > curL) {
if (droid.y - decentreY < curD & droid.y + decentreY > curU) {
myImage.setBounds(curL,curU,curR,curD);
myImage.draw(canvas);
}
}
}
}
droid.draw(canvas);
butt.draw(canvas);
butt1.draw(canvas);
butt2.draw(canvas);
butt3.draw(canvas);
buttz.draw(canvas);
buttz1.draw(canvas);
buttz2.draw(canvas);
buttz3.draw(canvas);
buttx.draw(canvas);
}
The render(Canvas canvas) methos is called on every frame. How can i scroll the map tiles? I tried this:
public void render(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
Drawable myImage;
int tileWidth = 50;
int tileHeight = 50;
int mapWidth = 3;
int mapHeight = 3;
int rowBaseX = 0;
int rowBaseY = 0;
int[][] board = new int[][] {
{0,0,0},
{0,0,0},
{0,0,2}
};
for (int row = 0; row < mapHeight; row++)
{
for (int col = 0; col < mapWidth; col++)
{
Resources res = this.getContext().getResources();
switch(board[row][col])
{
case 0:
myImage = res.getDrawable(R.drawable.tile1);
break;
case 1:
myImage = res.getDrawable(R.drawable.tile2);
break;
default:
myImage = res.getDrawable(R.drawable.tile3);
break;
}
int curL;
int curU;
int curR;
int curD;
curL = rowBaseX + (col * tileWidth);
curU = rowBaseY + (row * tileHeight);
if (droid.touched & !droid.touched1 & !droid.touched3) {
curL -= 1;
}else if (droid.touched1 & !droid.touched & !droid.touched2){
curU += 1;
}else if (droid.touched2 & !droid.touched1 & !droid.touched3){
curL += 1;
}else if (droid.touched3 & !droid.touched2 & !droid.touched){
curU -= 1;
}else if (droid.touched & droid.touched1){
curL -= 1;
curU += 1;
}else if (droid.touched1 & droid.touched2){
curL += 1;
curU += 1;
}else if (droid.touched2 & droid.touched3){
curL += 1;
curU -= 1;
}else if (droid.touched3 & droid.touched){
curL -= 1;
curU -= 1;
}
curR = curL + tileWidth;
curD = curU + tileHeight;
if (droid.x - decentreX < curR & droid.x + decentreX > curL) {
if (droid.y - decentreY < curD & droid.y + decentreY > curU) {
myImage.setBounds(curL,curU,curR,curD);
myImage.draw(canvas);
}
}
}
}
droid.draw(canvas);
butt.draw(canvas);
butt1.draw(canvas);
butt2.draw(canvas);
butt3.draw(canvas);
buttz.draw(canvas);
buttz1.draw(canvas);
buttz2.draw(canvas);
buttz3.draw(canvas);
buttx.draw(canvas);
}
but it didn't worked. Everything that is not in this method is not important. Help me! :)
Seems that you are changing lcal vars curL and curU. Thore are recalculates from rowBase on each call restricting the movement to the 1-increment you use when checking droid.touched.
You should change the global position of the tiles by changing the rowBase variables.
Related
public void draw(Graphics g, Graphics g2d, double theta, int NEWY){
g.setColor(Color.orange);
int drawLocationX = character.x;
int drawLocationY = character.y-47;
double rotationRequired = Math.toRadians (theta);
double locationX = this.getWidth()/2;
double locationY = this.getHeight()/2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g2d.drawImage(op.filter(image, null), drawLocationX, NEWY, null);
}
public int getHeightWorld(int x){
//meant to find height of land at specified location
int highest = 0;
int checked = 0;
for(int c = panel.HEIGHT-1; c >= 0; c--){
if(this.inColRange(x)&& this.inRowRange(c))
if(LandList[c][x] == 2){
highest = c;
checked++;
}
}
return (1000 - highest);
}
public double getAngleWorldT1(){
//meant to find angle tank needs to be rotated at
int g = this.getHeightWorld(tank1.getNEWX());
int h = this.getHeightWorld((tank1.getWidth()+ tank1.getNEWX()));
double trythis = this.NewEquation();
int newg = tank1.getWidth()+ tank1.getNEWX();
int newh = tank2.getWidth()+ tank2.getNEWX();
double newery = (trythis*newg);
double newery2 = (trythis*tank1.getNEWX());
double newval = newery - newery2;
double u = 5;
double width = tank1.getWidth();
if(Math.abs(h-g) > tank1.getWidth()){
u = width/(g-h);
}
else{
u = (g-h)/width;
}
double p = 57.6846779*Math.asin(Math.toRadians(u));
return p;
}
public double NewEquation(){
int dividethis = 0;
int subtractthis = 0;
int numnegative = 0;
for(int what = 0; what < tank1.getWidth(); what++){
if(Math.abs(this.getHeightWorld(what)-this.getHeightWorld(what-1)) < 2){
dividethis += this.getHeightWorld(what);
if(this.getHeightWorld(what)-this.getHeightWorld(what-1) < 0){
numnegative++;
}
}
else{
subtractthis++;
}
}
dividethis = dividethis/(tank1.getWidth()-subtractthis);
if((numnegative - tank1.getWidth()) > tank1.getWidth()/2){
dividethis = dividethis*-1;
}
return dividethis;
}
public void draw(Graphics g) {
//MOVE TO DIFF METHOD
int newy = this.getHeightWorld(tank1.getNEWX()) - tank1.getHeight();
int newy2 = this.getHeightWorld(tank2.getNEWX()) - tank2.getHeight();
if( LandList[newy][tank1.getNEWX()] == 2){
while (LandList[newy][tank1.getNEWX()] == 2){
newy--;
// System.out.println("FIRST HERE");
// System.out.println(newy);
}
// System.out.println("FIRST");
}
if( LandList[newy+1][tank1.getNEWX()] != 2){
while (LandList[newy+1][tank1.getNEWX()] != 2){
newy++;
// System.out.println("SECOND HERE");
}
// System.out.println("SECOND");
}
//System.out.println("YESSSSS" +Math.toDegrees(this.getAngleWorldT1()) );
tank1.draw(g, g, Math.toDegrees(this.getAngleWorldT1()), newy - tank1.getHeight()-50);
tank2.draw(g, g, Math.toDegrees(this.getAngleWorldT2()), newy2 - tank2.getHeight());
// System.out.println("2");
for(int x = 0; x < platforms.size(); x++){
platforms.get(x).draw(g);
}
}
}
(Sorry for the messy code.)
These are two classes I am using to design a tank shooter game. In this portion, I am attempting to make the image rotate according to the land it is over(to appear traveling uphill or downhill) and I don't want any piece inside of the land. "LandList" is a 2D array that has a value of 2 if there is land and 1 if there is no land. Two issues is A) rotating at incorrect heights and not rotating at all points
B)Image cuts off at a certain height
Thank you for your help.
BOTH CLASSES IN FULL
public class World {
Land[][] land;
List<Land> platforms = new ArrayList<Land>();
private GraphicsPanel panel;
int[][] LandList = new int[800][1500];
private int delay = 30;
private Timer timer;
private Random r;
Tank tank1;
Tank tank2;
public World(GraphicsPanel marioPanel) {
panel = marioPanel;
land = new Land[panel.WIDTH][panel.HEIGHT-500-3];
setUpWorld();
setUpTimer();
}
private void setUpWorld() {
for(int r = 0; r < panel.WIDTH; r++){
for(int c = 0; c < panel.HEIGHT; c++){
LandList[c][r] = 1;
}
}
//tank not displaying
//a lot of stuff copied over
tank1 = new Tank(25,442,100,60,1);
tank2 = new Tank(700,442,100,60,2);
r = new Random();
int w = 0;
int n = 0;
for(int x = 0; x < panel.WIDTH; x+=5){
if(x > 0 && x < panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(x+r) && inColRange(y+c))
LandList[y+r][x+c] = 2;
}
}
}
}
if(x > panel.WIDTH/6 && x < 2*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*w; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
w--;
}
if(x > 2*panel.WIDTH/6 && x < 3*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*w; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
w++;
}
if(x > 3*panel.WIDTH/6 && x < 4*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*n; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
n--;
}
if(x > 4*panel.WIDTH/6 && x < 5*panel.WIDTH/6 +1){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500+ 4*n; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
}
}
}
n++;
}
if(x > 5*panel.WIDTH/6){
//for(int y = (int) (500+(-(100*Math.random())*((x%2)+1))); y < panel.HEIGHT; y+=5){
for(int y = 500; y < panel.HEIGHT; y+=5){
Land creating = new Land(x, y, 5, 5);
platforms.add(creating);
for(int r = 0; r < 5; r++){
for(int c = 0; c < 5; c++){
if(inRowRange(y+r) && inColRange(x+c))
LandList[y+r][x+c] = 2;
// System.out.println(LandList[x+r][y+c]);
}
}
}
}
// else{
// for(int y = 500; y < panel.HEIGHT; y+=5){
// Land creating = new Land(x, y, 5, 5);
// platforms.add(creating);
// }
//
// }
}
for(int r = 0; r < panel.WIDTH; r++){
for(int c = 0; c < panel.HEIGHT; c++){
//System.out.println(LandList[r][c]);
}
}
for(int checked = 0; checked < panel.WIDTH; checked++){
System.out.println(this.getHeightWorld(checked));
}
// System.out.println(LandList);
}
private boolean inColRange(int i) {
// TODO Auto-generated method stub
return i>=0 && i<LandList[0].length;
}
private boolean inRowRange(int i) {
// TODO Auto-generated method stub
return i>=0 && i<LandList.length;
}
private void setUpTimer() {
timer = new Timer(delay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// what should happen each time the timer goes off?
panel.repaint();
moveStuff();
checkHitBoxes();
//System.out.println(mario.getY());
}
});
timer.start();
}
protected void checkHitBoxes() {
}
protected void moveStuff() {
tank1.move();
panel.repaint();
}
public int getHeightWorld(int x){
//meant to find height of land at specified location
int highest = 0;
int checked = 0;
for(int c = panel.HEIGHT-1; c >= 0; c--){
if(this.inColRange(x)&& this.inRowRange(c))
if(LandList[c][x] == 2){
highest = c;
checked++;
}
}
return (1000 - highest);
}
public double getAngleWorldT1(){
//meant to find angle tank needs to be rotated at
int g = this.getHeightWorld(tank1.getNEWX());
int h = this.getHeightWorld((tank1.getWidth()+ tank1.getNEWX()));
double trythis = this.NewEquation();
int newg = tank1.getWidth()+ tank1.getNEWX();
int newh = tank2.getWidth()+ tank2.getNEWX();
double newery = (trythis*newg);
double newery2 = (trythis*tank1.getNEWX());
double newval = newery - newery2;
double u = 5;
double width = tank1.getWidth();
if(Math.abs(h-g) > tank1.getWidth()){
u = width/(g-h);
}
else{
u = (g-h)/width;
}
double p = 57.6846779*Math.asin(Math.toRadians(u));
return p;
}
public double getAngleWorldT2(){
int a = this.getHeightWorld(tank2.getNEWX());
int s = this.getHeightWorld((tank2.getWidth() + tank2.getNEWX() + 100) );
// a = 100;
// s = 700;
int o = (a-s)/tank2.getWidth();
//System.out.println(o);
double p = -57.6846779*(Math.asin(Math.toRadians(o)));
//System.out.println(p);
return p;
}
public double NewEquation(){
int dividethis = 0;
int subtractthis = 0;
int numnegative = 0;
for(int what = 0; what < tank1.getWidth(); what++){
if(Math.abs(this.getHeightWorld(what)-this.getHeightWorld(what-1)) < 2){
dividethis += this.getHeightWorld(what);
if(this.getHeightWorld(what)-this.getHeightWorld(what-1) < 0){
numnegative++;
}
}
else{
subtractthis++;
}
}
dividethis = dividethis/(tank1.getWidth()-subtractthis);
if((numnegative - tank1.getWidth()) > tank1.getWidth()/2){
dividethis = dividethis*-1;
}
return dividethis;
}
public void draw(Graphics g) {
//MOVE TO DIFF METHOD
int newy = this.getHeightWorld(tank1.getNEWX()) - tank1.getHeight();
int newy2 = this.getHeightWorld(tank2.getNEWX()) - tank2.getHeight();
if( LandList[newy][tank1.getNEWX()] == 2){
while (LandList[newy][tank1.getNEWX()] == 2){
newy--;
// System.out.println("FIRST HERE");
// System.out.println(newy);
}
// System.out.println("FIRST");
}
if( LandList[newy+1][tank1.getNEWX()] != 2){
while (LandList[newy+1][tank1.getNEWX()] != 2){
newy++;
// System.out.println("SECOND HERE");
}
// System.out.println("SECOND");
}
//System.out.println("YESSSSS" +Math.toDegrees(this.getAngleWorldT1()) );
tank1.draw(g, g, Math.toDegrees(this.getAngleWorldT1()), newy - tank1.getHeight()-50);
tank2.draw(g, g, Math.toDegrees(this.getAngleWorldT2()), newy2 - tank2.getHeight());
// System.out.println("2");
for(int x = 0; x < platforms.size(); x++){
platforms.get(x).draw(g);
}
}
}
public class Tank extends Moveable{
private boolean moveRight,moveLeft;
private String direction = "NONE";
private int dx =5;
//graphics
BufferedImage image = null;
private URL file;
private Rectangle character;
private Rectangle hitBox;
JLabel label = new JLabel();
private int NEWX;
public Tank(int x, int y, int w, int h, int color){
character = new Rectangle(x,y,w,h);
this.create(null,x,y,w,h);
NEWX = character.x;
BufferedImage img =null;
if(color == 1){
// file= getClass().getResource("pictures\\green_tank1");
try {
img = ImageIO.read(new File("green_tank1.png"));
image = img;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
// file = getClass().getResource("pictures\\blue_tank1");
try {
img = ImageIO.read(new File("blue_tank1.png"));
image = img;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void draw(Graphics g, Graphics g2d, double theta, int NEWY){
g.setColor(Color.orange);
int drawLocationX = character.x;
int drawLocationY = character.y-47;
double rotationRequired = Math.toRadians (theta);
double locationX = this.getWidth()/2;
double locationY = this.getHeight()/2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g2d.drawImage(op.filter(image, null), drawLocationX, NEWY, null);
//System.out.println("This is new X " + NEWX);
// label.setVisible(true);
// label.isOpaque();
// label.setBounds(character.x, character.y, character.width, character.height);
// label.repaint();
//g.drawImage(image, 0, 0, null);
// int centerx = character.x + character.width/2;
// int centery = character.y + character.height/2;
//
// int point1 = (int) (centerx + (character.width/2)*Math.cos(Math.toRadians(theta)) - (character.height/2)* Math.sin(Math.toRadians(theta)));
// int point2 = (int) (centery + (character.height/2)*Math.cos(Math.toRadians(theta))+(character.width/2)*Math.sin(Math.toRadians(theta)));
// int point3 =(int) (centerx - (character.width/2)*Math.cos(Math.toRadians(theta)) + (character.height/2)* Math.sin(Math.toRadians(theta)));
// int point4 = (int) (centery - (character.height/2)*Math.cos(Math.toRadians(theta))-(character.width/2)*Math.sin(Math.toRadians(theta)));
// //System.out.println(theta);
// g.drawImage(image, point1,point2,point3,point4, null);
//// System.out.println("3");
// Rotation information
// AffineTransform tx = AffineTransform.getRotateInstance(Math.toRadians (theta), character.x, character.y);
// AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
//
// // Drawing the rotated image at the required drawing locations
// g.drawImage(op.filter((BufferedImage) image, null), character.x, character.y, null);
// System.out.println(this.getX());
// System.out.println(this.getY());
// System.out.println(this.getWidth());
// System.out.println(this.getHeight());
// g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
// this.setBounds(this.getX(), this.getY(), this.getWidth(), this.getHeight());
//
}
public Rectangle getRect(){
return this.character;
}
public void move(){
if(moveLeft == true){
character.setBounds(character.x -2, character.y, character.width, character.height);
character.x = character.x -2;
NEWX += -2;
}
if(moveRight == true){
character.setBounds(character.x +2, character.y, character.width, character.height);
character.x = character.x +2;
NEWX += 2;
}
}
public void setDirection(String s){
this.direction = s;
String x = s.toUpperCase().substring(0, 1);
if(x.equals("L")){
//System.out.println(x);
moveLeft = true;
moveRight = false;
}
if(x.equals("R")){
moveRight = true;
moveLeft = false;
// System.out.println("im here");
}
else if(x.equals("N")){
moveRight = false;
moveLeft =false;
// System.out.println("I Got Here #2");
}
}
public String getDirection(){
return this.direction;
}
public int getNEWX(){
return this.NEWX;
}
}
I made two methods for a class called Picture, the name is self explanatory. The getAverageColor() method gets the average color of all the pixels in a certain area of the image specified by the parameters passed in. In the pixelate() method, it uses getAverageColor() to pixelate the image. The whole thing works, however it takes upwards of 2 minutes to pixelate a single image. It takes even longer if the pixelSize parameter is made smaller and the image is larger. So I was wondering if there is a better algorithm for doing this by manipulating the pixels.
/**
* NOTE: The smaller the pixelSize the longer the pixelation process takes
*/
public void pixelate(int pixelSize)
{
Pixel[][] pixels = this.getPixels2D();
int blockSize = pixelSize;
Color averageColor = null;
for(int row = 0; row < pixels.length; row += blockSize)
{
for (int col = 0; col < pixels[row].length; col += blockSize)
{
if (!((col + blockSize > pixels[0].length) || (row + blockSize > pixels.length)))
{
averageColor = getAverageColor(row, col, row+blockSize, col+blockSize);
}
for (int row_2 = row; (row_2 < row + blockSize) && (row_2 < pixels.length); row_2++)
{
for (int col_2 = col; (col_2 < col + blockSize) && (col_2 < pixels[0].length); col_2++)
{
pixels[row_2][col_2].setColor(averageColor);
}
}
}
}
}
public Color getAverageColor(int startRow, int startCol, int endRow, int endCol)
{
Pixel[][] pixels = this.getPixels2D();
Color averageColor = null;
int totalPixels = (endRow - startRow)*(endCol - startCol);
int totalRed = 0;
int averageRed = 0;
int totalGreen = 0;
int averageGreen = 0;
int totalBlue = 0;
int averageBlue = 0;
for (int row = startRow; row < endRow; row++)
{
for (int col = startCol; col < endCol; col++)
{
totalRed += pixels[row][col].getRed();
totalGreen += pixels[row][col].getGreen();
totalBlue += pixels[row][col].getBlue();
}
}
averageRed = totalRed / totalPixels;
averageGreen = totalGreen / totalPixels;
averageBlue = totalBlue / totalPixels;
averageColor = new Color(averageRed, averageGreen, averageBlue);
return averageColor;
}
I am currently making a game in Java and I am trying to draw an image on my screen, but nothing show up ( only a black screen but no errors ) :(
Here is the code to import the image:
public static Bitmap loadBitmap(String fileName) {
try {
BufferedImage img = ImageIO.read(Art.class.getResource(fileName));
int w = img.getWidth();
int h = img.getHeight();
Bitmap result = new Bitmap(w, h);
img.getRGB(0, 0, w, h, result.pixels, 0, w);
for (int I = 0; I < result.pixels.length; i++) {
int in = result.pixels[i];
int col = (in & 0xf) >> 2;
if (in == 0xffff00ff) col = -1;
result.pixels[i] = col;
}
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
And the Bitmap class:
public void draw(Bitmap bitmap, int xOffs, int yOffs)
{
for(int y = 0; y < bitmap.height; y++)
{
int yPix = y + yOffs;
if(yPix < 0 || yPix >= height) continue;
for(int x = 0; x < bitmap.width; x++)
{
int xPix = x + xOffs;
if(xPix < 0 || xPix >= width) continue;
int alpha = bitmap.pixels[x + y * bitmap.width];
if(alpha > 0)
pixels[xPix + yPix * width] = bitmap.pixels[x + y * bitmap.width];
}
}
}
And to draw all of this :
public void render(Game game)
{
for(int y = 0; y < height; y++)
{
float yd = ((y + 0.5f) - height / 2.0f) / height;
if(yd < 0) yd *= -1;
float z = 10 / yd;
for(int x = 0; x < width; x++)
{
float xd = (x - width / 2.0f) / height;
xd *= z;
int xx = (int) (xd) & 7;
int yy = (int) (z + game.time * 0.1f) & 7;
pixels[x + y * width] = Art.floors.pixels[xx + yy * 64];
}
}
}
I have no errors! I don't really understand.. is this a bug caused by alpha or something? Ho and my image.png is 64x64 made in paint.net
i am new to android developing.
I am developing a game called 2048.
Is it possible that cells motion animation done? If yes, how?
its my code:
public class GameView extends ImageView {
private Paint paint;
private Paint textPaint;
private int width;
private int height;
public GameView(Context context) {
super(context);
initialize();
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initialize();
}
private void initialize() {
paint = new Paint();
paint.setColor(Color.parseColor("#aaaaaa"));
paint.setStyle(Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
textPaint = new Paint();
textPaint.setColor(Color.parseColor("#000000"));
textPaint.setStyle(Style.FILL);
textPaint.setAntiAlias(true);
textPaint.setTextSize(G.convertDpToPixel(48));
textPaint.setTextAlign(Align.CENTER);
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (getWidth() < getHeight()) {
width = getWidth();
} else {
width = getHeight();
}
}
public void resetGame() {
G.score = 0;
G.updateScore();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
G.cells[i][j] = 0;
}
}
dropNextNumber();
dropNextNumber();
}
private void dropNextNumber() {
boolean gameFinished = true;
int freeCells = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (G.cells[i][j] == 0) {
freeCells++;
if (freeCells > 1) {
gameFinished = false;
break;
}
}
}
}
if (gameFinished) {
Toast.makeText(getContext(), "You Lose!", Toast.LENGTH_SHORT).show();
} else {
while (true) {
int randomX = (int) Math.floor(Math.random() * 4);
int randomY = (int) Math.floor(Math.random() * 4);
if (G.cells[randomX][randomY] == 0) {
G.cells[randomX][randomY] = 2;
break;
}
}
invalidate();
}
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float size = width / 4.0f;
float padding = 4;
float halfSize = size / 2.0f - padding;
float offset = getWidth() - 4.0f * size;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
paint.setColor(Color.parseColor(getNumberColor(G.cells[i][j])));
float centerX = (j + 0.5f) * size + offset / 2.0f;
float centerY = (i + 0.5f) * size;
RectF rect = new RectF(centerX - halfSize, centerY - halfSize, centerX + halfSize, centerY + halfSize);
canvas.drawRoundRect(rect, G.convertDpToPixel(8), G.convertDpToPixel(8), paint);
if (G.cells[i][j] != 0) {
String textToDraw = new String("" + G.cells[i][j]);
Rect bounds = new Rect();
textPaint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds);
canvas.drawText(textToDraw, centerX, centerY + (bounds.bottom - bounds.top) / 2, textPaint);
}
}
}
}
private void goToUp() {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 4; i++) {
if (i > 0) {
int k = i;
while (k > 0 && G.cells[k - 1][j] == 0) {
G.cells[k - 1][j] = G.cells[k][j];
G.cells[k][j] = 0;
k--;
}
if (k > 0) {
if (G.cells[k - 1][j] == G.cells[k][j]) {
power(k - 1, j);
G.cells[k][j] = 0;
}
}
}
}
}
invalidate();
}
public void power(int i, int j) {
G.cells[i][j] *= 2;
G.score += G.cells[i][j];
G.updateScore();
}
*/
private void goToDown() {
for (int j = 3; j >= 0; j--) {
for (int i = 3; i >= 0; i--) {
if (i < 3) {
int k = i;
while (k < 3 && G.cells[k + 1][j] == 0) {
G.cells[k + 1][j] = G.cells[k][j];
G.cells[k][j] = 0;
k++;
}
if (k < 3) {
if (G.cells[k + 1][j] == G.cells[k][j]) {
power(k + 1, j);
G.cells[k][j] = 0;
}
}
}
}
}
invalidate();
}
*/
private void goToLeft() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0) {
int k = j;
while (k > 0 && G.cells[i][k - 1] == 0) {
G.cells[i][k - 1] = G.cells[i][k];
G.cells[i][k] = 0;
k--;
}
if (k > 0) {
if (G.cells[i][k - 1] == G.cells[i][k]) {
power(i, k - 1);
G.cells[i][k] = 0;
}
}
}
}
}
invalidate();
}
private void goToRight() {
for (int i = 3; i >= 0; i--) {
for (int j = 3; j >= 0; j--) {
if (j < 3) {
int k = j;
while (k < 3 && G.cells[i][k + 1] == 0) {
G.cells[i][k + 1] = G.cells[i][k];
G.cells[i][k] = 0;
k++;
}
if (k < 3) {
if (G.cells[i][k + 1] == G.cells[i][k]) {
power(i, k + 1);
G.cells[i][k] = 0;
}
}
}
}
}
invalidate();
}
private float lastDownX;
private float lastDownY;
private boolean movePending;
private static final int MODE_LEFT = 1;
private static final int MODE_RIGHT = 2;
private static final int MODE_UP = 3;
private static final int MODE_DOWN = 4;
private String getNumberColor(int number) {
switch (number) {
case 0:
return "#ccc0b3";
case 2:
return "#eee4da";
case 4:
return "#ede0c8";
case 8:
return "#f2b179";
case 16:
return "#f59563";
case 32:
return "#f67c5f";
case 64:
return "#f65e3b";
}
return "#ccc0b3";
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastDownX = event.getRawX();
lastDownY = event.getRawY();
movePending = true;
break;
case MotionEvent.ACTION_MOVE:
if ( !movePending) {
return true;
}
int mode = 0;
float diffX = lastDownX - event.getRawX();
float diffY = lastDownY - event.getRawY();
if (Math.abs(diffX) > 10 && Math.abs(diffX) > 2 * Math.abs(diffY)) {
if (diffX > 0) {
mode = MODE_LEFT;
} else {
mode = MODE_RIGHT;
}
movePending = false;
}
if (Math.abs(diffY) > 10 && Math.abs(diffY) > 2 * Math.abs(diffX)) {
if (diffY > 0) {
mode = MODE_UP;
} else {
mode = MODE_DOWN;
}
movePending = false;
}
switch (mode) {
case MODE_LEFT:
goToLeft();
dropNextNumber();
break;
case MODE_RIGHT:
goToRight();
dropNextNumber();
break;
case MODE_UP:
goToUp();
dropNextNumber();
break;
case MODE_DOWN:
goToDown();
dropNextNumber();
break;
}
break;
}
return true;
}
}
and this my screenshot.
I tried many ways but not any solution.
I appreciate the patience and explain step by step.
i want to set animation like this.
Thank you my friends.
I'm writing an application to hide animage in another image using LSB. The encoding returns an image that differs from the image that was hidden and after searching the problem for quite some time now, i think i became seriously blind, when it comes to my code.
If somebody could take a look and give me a hint, I would be very thankful. The significant code below and the whole project (if somebody would want to test it) under the link: https://github.com/miassma/Steganography.git
public class SteganographyOperationsUtil {
/*checking if the image to hide can fit the hiding image
it returns the range of shades of gray that can be kept in the hiding image*/
public static int checkImages(ImageModel hiding, ImageModel toHide, ImageModel copyOfToHide){
int hidingSize = hiding.getWidth() * hiding.getHeight();
int toHideSize = toHide.getWidth() * toHide.getHeight();
int header = 40;
int value = 8;
while((toHideSize * value + header) > hidingSize){ //if doesnt fit, reducing one range, checking again
value--;
if(value==0){
break;
}
}
if(value == 0) return -1;
if(value<8) posterize(copyOfToHide, (int)pow(2, value)); //run the posterisation if needed
return (int)pow(2, value);
}
/* preparing the hiding image
we need zero on each LSB
*/
public static void prepareHidingImage(ImageModel imgModel){
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
int temp = 254;
int newColor = color & temp;
int[] newColorPixel = {newColor};
imgModel.getImage().getRaster().setPixel(x, y, newColorPixel);
}
}
imgModel.imageChanged();
}
//fullfill by leading zeros with the lenght of the option
public static String fillString(String toFill, int option){
String zero = "0";
if (toFill.length() < option){
int temp = option - toFill.length();
do{
toFill = zero.concat(toFill);
}while(--temp >0);
}
return toFill;
}
/* fullfill the string to get the color matching the posterisation range
for example 1 will be 11111111 (2 ranges of gray)
101 will become 10110110 (3 ranges of gray)
1011 will become 10111011 (4 ranges of gray)
*/
public static String complete(String toComplete){
while (toComplete.length() < 9){
toComplete = toComplete+toComplete;
}
toComplete = toComplete.substring(0, 8);
return toComplete;
}
//hiding Image
public static void hidingOperation(ImageModel hiding, ImageModel toHide, int value){
prepareHidingImage(hiding);
String posterisation = Integer.toString(value-1, 2);
String hiddenWidth = Integer.toString(toHide.getWidth(), 2);
String hiddenHeight = Integer.toString(toHide.getHeight(), 2);
hiddenWidth = fillString(hiddenWidth, 16);
hiddenHeight = fillString(hiddenHeight, 16);
posterisation = fillString(posterisation, 8);
String header = hiddenWidth;
header = header.concat(hiddenHeight);
header = header.concat(posterisation);
int newColor;
int temp = 0;
int temp2 = 0;
int bitsToCheck = (int)logb(value, 2); //how many bits of each pixel we have to hide for given postarisation
int zero = 0;
int one = 1;
int i = 0;
int j = 0;
String colorOfToHideBinary = "";
outerLoop:
for (int x = 0; x < hiding.getWidth(); ++x) {
for (int y = 0; y < hiding.getHeight(); ++y) {
int color = hiding.getImage().getRaster().getPixel(x, y, new int[1])[0];
//filling header
if(temp < header.length()){
if(header.charAt(temp)== '0'){
newColor = color | zero;
}else{ newColor = color | one;
}temp++;
//hiding image
}else{
/*
getting the value of the next pixel of the image to hide, only if temp ==0,
what means that it is the first pixel or each needed bits by the posterisation range
has been already checked
*/
if(temp2 == 0){
int colorOfToHide = toHide.getImage().getRaster().getPixel(i, j, new int[1]) [0];
colorOfToHideBinary = Integer.toString(colorOfToHide, 2);
colorOfToHideBinary = fillString(colorOfToHideBinary, 8);
}
//i check each value of the color in binary, but only as much as needed by the posterisation range
if (colorOfToHideBinary.charAt(temp2) == '0'){
newColor = color | zero;
}else { newColor = color | one;}
temp2++;
if (temp2 == bitsToCheck){
temp2 = 0;
j++;
if(j == toHide.getHeight()){
j = 0;
i++;
}
}
}
int[] newColorPixel = {newColor};
hiding.getImage().getRaster().setPixel(x, y, newColorPixel);
if(i == toHide.getWidth()){
break outerLoop;
}
}
}
hiding.imageChanged();
}
//decrypting image
public static ImageModel encodingOperation(ImageModel imgModel){
int i = 0;
int j = 0;
String widthB = "";
String heightB = "";
String posterisationB = "";
int temp = 0;
int one = 1;
/* loop for taking values from the header, seems to work pretty fine */
outerLoop:
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
if(temp<16){
if ((color & one) == one) widthB = widthB.concat("1");
else widthB = widthB.concat("0");
}else if(temp < 32){
if ((color & one) == one) heightB = heightB.concat("1");
else heightB = heightB.concat("0");
}else if(temp <40){
if ((color & one) == one) posterisationB = posterisationB.concat("1");
else posterisationB = posterisationB.concat("0");
}else{
break outerLoop;
}temp++; j++;
}i++;
}
int width = Integer.parseInt(widthB, 2);
int height = Integer.parseInt(heightB, 2);
int posterisation = Integer.parseInt(posterisationB, 2);
int bitsToCheck = (int)logb(posterisation+1, 2);
int temp2 = 0;
String colorInBinary = "";
//preparing the canvas for the encoded image, width and height from the header
ImageModel encryptedImage = ImageModel.fromHidden(width, height);
int a = 0;
int b = 0;
/* encoding the image
starting after the point after the header, saved in the variables i,j
*/
outerLoop:
for (int x = i; x < imgModel.getWidth(); ++x) {
for (int y = j; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
/* pixel by pixel reading color of the hidden image
temp2 checks, where to stop - how many LSB of the hiding image keeps information bout one pixel of the hidden img
*/
if ((color & one) == one) colorInBinary = colorInBinary.concat("1");
else colorInBinary= colorInBinary.concat("0");
temp2++;
if (temp2 == bitsToCheck){
temp2 = 0;
//fullfilling the color to the right by the given posterisation range
colorInBinary = complete(colorInBinary);
int newColor = Integer.parseInt(colorInBinary, 2);
colorInBinary = "";
int[] newColorPixel = {newColor};
encryptedImage.getImage().getRaster().setPixel(a, b, newColorPixel);
b++;
if(b == height){
a++;
b=0;
}if (a == width){
break outerLoop;
}
}
}
}
return encryptedImage;
}
public static double logb( double a, double b ){
return Math.log(a) / Math.log(b);
}
public static void posterize(ImageModel imgModel, int value) {
int[] lut = new int[256];
float param1 = 255.0f / (value - 1);
float param2 = 256.0f / (value);
for (int i = 0; i < 256; ++i) {
lut[i] = (int)((int)(i / param2) * param1);
}
useLUT(imgModel, lut);
}
public static void useLUT(ImageModel imgModel, int[] lut) {
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
int[] newColorPixel = {lut[color]};
imgModel.getImage().getRaster().setPixel(x, y, newColorPixel);
}
}
imgModel.imageChanged();
}