package edu.compsci;
import cs1.android.*;
// Fling the bird so that it flies on top of the pig.
public class AngryBirdApp extends AndroidApp
{
// for 320x480 screen in landscape mode
final int WIDTH = 480;
final int HEIGHT = 320;
// distance considered a hit
final double HIT_DIST = 5.0;
// computes the distance between the given points
public double distance(double x1, double y1, double x2, double y2)
{
double dx = x1 - x2;
double dy = y1 - y2;
return Math.sqrt(dx*dx + dy*dy);
}
// check if the bird is visible
public boolean isVisible(double birdX, double birdY)
{
if (birdX > 0 && birdX < WIDTH && birdY > 0 && birdY < HEIGHT) {
return true;
}
else {
return false;
}
}
public void run()
{
// position pig and bird at opposite corners
double birdX = 60, birdY = 60;
double pigX = 420, pigY = 260;
// draw the scene
canvas.drawImage(240, 169, "background.png");
canvas.drawImage(pigX, pigY, "pig.png");
canvas.drawImage(birdX, birdY, "bird.png");
// get the fling direction
Fling fling = canvas.waitForFling();
double dx = fling.getDx();
double dy = fling.getDy();
// use the speed to update position as long as bird in view and away from pig
double speedX = 3, speedY = 6;
while (distance(birdX, birdY, pigX, pigY) > HIT_DIST && isVisible(birdX, birdY)) {
birdX = birdX + speedX*dx;
birdY = birdY + speedY*dy;
canvas.sleep(.01);
// redraw the scene
canvas.clear();
canvas.drawImage(240, 169, "background.png");
canvas.drawImage(pigX, pigY, "pig.png");
canvas.drawImage(birdX, birdY, "bird.png");
}
}
}
|
package edu.compsci;
import cs1.android.*;
// Fling the bird so that it flies on top of the pig.
public class AngryBirdObjectsApp extends AndroidApp
{
// for 320x480 screen in landscape mode
final int WIDTH = 480;
final int HEIGHT = 320;
// distance considered a hit
final double HIT_DIST = 40.0;
// Use the methods distance(Shape s1, Shape s2) and contains(Point p)
// see the while loop
public void run()
{
// position pig and bird at opposite corners
double birdX = 60, birdY = 60;
double pigX = 420, pigY = 260;
// draw the scene
Shape field = new Image(240, 169, "background.png");
Shape pig = new Image(pigX, pigY, "pig.png");
Shape bird = new Image(birdX, birdY, "bird.png");
field.draw();
pig.draw();
bird.draw();
// get the fling direction
Fling fling = canvas.waitForFling();
double dx = fling.getDx();
double dy = fling.getDy();
// use the speed to update position as long as bird in view and away from pig
double speedX = 3, speedY = 6;
while (Shape.distance(bird, pig) > HIT_DIST && field.contains(bird.getCenter())) {
bird.move(speedX*dx, speedY*dy);
canvas.sleep(.01);
}
}
}
|