I'm making a small balloon game in java and trying to write my code, so that when I create new 'balloon' objects they don't overlap on the screen.
The code I have so far is:
public void newGame(){
UI.clearGraphics();
this.currentScore = 0;
this.totalPopped = 0;
for (int i = 0; i < this.balloons.length-1; i++) {
this.balloons[i] = new Balloon(50 + Math.random()*400, 50 + Math.random()*400);
for (int j = i + 1; j < this.balloons.length; j++) {
if (this.balloons[i] !=null && this.balloons[j] != null && this.balloons[i].isTouching(balloons[j])) {
this.balloons[j] = new Balloon(50 + Math.random()*400, 50+ Math.random()*400);
}
}
this.balloons[i].draw();
}
UI.printMessage("New game: click on a balloon. High score = "+this.highScore);
}
using the draw and isTouching methods:
public void draw(){
UI.setColor(color);
UI.fillOval(centerX-radius, centerY-radius, radius*2, radius*2);
if (!this.popped){
UI.setColor(Color.black);
UI.drawOval(centerX-radius, centerY-radius, radius*2, radius*2);
}
}
/** Returns true if this Balloon is touching the other balloon, and false otherwise
* Returns false if either balloon is popped. */
public boolean isTouching(Balloon other){
if (this.popped || other.popped) return false;
double dx = other.centerX - this.centerX;
double dy = other.centerY - this.centerY;
double dist = other.radius + this.radius;
return (Math.hypot(dx,dy) < dist);
}
how can I write this, so that when the balloons are created, none of them are touching each other?
Right now you have two loops. In the first loop the balloons are created. In the second loop, every balloon is tested against every other loop. Do this test in the first loop: after creating a new balloon, test it against all already existing balloons.
Related
Hello Stack Overflow people :)
I'm a huge newbie when it comes to coding, and I've just ran into a problem that my brain just won't get over...
Before I start blabbering about this issue, I'll paste my code so as to give a little bit of context (sorry in advance if looking at it makes you wanna puke). The main focus of the issue is commented and should therefore be fairly visible :
Main
ArrayList<Individual> individuals = new ArrayList<Individual>();
void setup()
{
size(500,500);
for(int i = 0; i < 2; i++)
{
individuals.add(new Individual());
}
println(frameRate);
}
void draw()
{
background(230);
for(int i = 0; i < individuals.size(); i++)
{
individuals.get(i).move();
individuals.get(i).increaseTimers();
individuals.get(i).display();
}
}
Individual
class Individual
{
float x;
float y;
int size = 5;
Timer rdyBreed; /* Here is the object that appears to be shared
between individuals of the ArrayList */
float breedRate;
float breedLimit;
Individual()
{
x = random(0, width);
y = random(0, height);
rdyBreed = new Timer("rdyBreed", 0);
breedRate = random(.2, 3);
breedLimit = random(10, 20);
}
void move()
{
int i = (int)random(0, 1.999);
int j = (int)random(0, 1.999);
if (i == 0)
{
x = x + 1;
} else
{
x = x - 1;
}
if (j == 0)
{
y = y + 1;
} else
{
y = y - 1;
}
checkWalls();
}
void checkWalls()
{
if (x < size/2)
{
x = width - size/2;
}
if (x > width - size/2)
{
x = size/2;
}
if (y < size/2)
{
y = width - size/2;
}
if (y > width - size/2)
{
y = size/2;
}
}
void display()
{
noStroke();
if (!rdyBreed.finished)
{
fill(255, 0, 0);
} else
{
fill(0, 255, 0);
}
rect(x - size/2, y - size/2, size, size);
}
void increaseTimers()
{
updateBreedTimer();
}
void updateBreedTimer()
{
rdyBreed.increase(frameRate/1000);
rdyBreed.checkLimit(breedLimit);
rdyBreed.display(x, y);
}
}
Timer
class Timer
{
float t;
String name;
boolean finished = false;
Timer(String name, float t)
{
this.t = t;
this.name = name;
}
void increase(float step)
{
if (!finished)
{
t = t + step;
}
}
void checkLimit(float limit)
{
if (t >= limit)
{
t = 0;
finished = true;
}
}
void display(float x, float y)
{
textAlign(RIGHT);
textSize(12);
text(nf(t, 2, 1), x - 2, y - 2);
}
}
Now that that's done, let's get to my question.
Basically, I'm trying to create some sort of a personal Conway's Game of Life, and I'm encountering a lot of issues right off the bat.
Now my idea when writing this piece of code was that every individual making up the small simulated "society" would have different timers and values for different life events, like mating to have children for example.
Problem is, I'm not a huge pro at object-oriented programming, and I'm therefore quite clueless as to why the objects are not having each their own Timer but both a reference to the same timer.
I would guess making an ArrayList of timers and using polymorphism to my advantage could make a change, but I'm not really certain of it or really how to do it so... yeah, I need help.
Thanks in advance :)
EDIT : Here is a screenshot of the debugger. The values keep being the same with each iteration of the updates.
Screenshot
What makes you think they reference the same Timer object? The values of t displayed in the debugger are going to be the same until one of them reaches the breedLimit and gets set to 0, because they're being initialized at the same time.
Try this and see that the values of t are different.
void setup() {
size(500,500);
}
void mouseClicked() {
individuals.add(new Individual());
}
I'd recommend setting the breakpoint somewhere around here:
t = 0;
finished = true;
They do not share the same timer, you create a new Timer object for each Individual.
class Individual {
// ...
Timer rdyBreed;
Individual() {
// ...
rdyBreed = new Timer("rdyBreed", 0);
//...
The only way they could be sharing the same Timer is if you were setting rdyBreed elsewhere, but since you don't want that I recommend making it final.
If you did want to share the same Timer instance across all individuals then you could declare it static.
I have a object(named frame) on screen,it will move either left or right according to where I move my finger.
public void handleSwipeInput() {
if (MyInputProcessor.isTouchDown) {
float movedir = MyInputProcessor.dist > 0 ? 1 : -1;
float speed = 30;
float actualSpeed = Math.abs(MyInputProcessor.dist) >= speed ? speed : Math.abs(MyInputProcessor.dist);
if (movedir > 0) {
frame.setX(frame.getX() + actualSpeed+2);
MyInputProcessor.dist -= actualSpeed;
} else {
frame.setX(frame.getX() - actualSpeed-2);
MyInputProcessor.dist += actualSpeed;
}
}
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
dist+=screenX-start;
start=screenX;
isTouchDragged=true;
return false;
}
In update() method:
if (MyInputProcessor.isTouchDown && Math.abs(MyInputProcessor.dist)>5.0f)
handleSwipeInput();
This works perfect,and I am adding an array of objects(named circles) below the frame object while moving,so that,those array of elements also moves along with my finger.
So I set positions of circles[] sequentially below frame object:
if(parts.size()!=0)
{
for (int i = 0; i <parts.size(); i++){
if(parts.get(i) instanceof Block){
circles[i].setIndex(parts.get(i).getIndex()) ;
circles[i].setPosition(frame.getX()-frame.getRadius(),
(frame.getY()-(frame.getRadius()*3))-(60*i));
}
This also works fine.Both frame and below objects gets a feel that they are moving along with my finger,and frame objects with mentioned speed.
Now I want to create an effect like,each of the circles objects should follow frame object with some delay,according to their positions.
So that it will appear like a smooth snake movement(As in snake vs block game).
For this,I tried to make use of tweens.
Tween.to(circles[0], Accessor.POS_XY,0.05f)
.target(circles[0].getX()+10,circles[0].getY())
.ease(TweenEquations.easeInSine)
.start(tweenManager);
Tween.to(circles[1], Accessor.POS_XY,0.05f)
.target(circles[1].getX()+20,circles[1].getY())
.ease(TweenEquations.easeInSine)
.start(tweenManager);
Tween.to(circles[2], Accessor.POS_XY,0.05f)
.target(circles[2].getX()+30,circles[2].getY())
.ease(TweenEquations.easeInSine)
.start(tweenManager);
But I am not able to work the logic out with tweens.
Confused of implementing a sequential delay for each circle object,according to the touch input ,with tweens.
I have created an array which contain sequential values to control the movement of circles to look like a snake.
private float delayValue[]={0.03f,0.04f,0.05f,0.06f,0.07f,0.08f,0.09f,0.10f};
Simple tween I used:
if (movedir > 0) {
frame.setX(frame.getX() + actualSpeed);
MyInputProcessor.dist -= actualSpeed;
tweenManager.killAll();
for (int i = 0; i < parts.size(); i++) {
Tween.to(circles[i], Accessor.POS_XY, delayValue[i])
.target(frame.getX() - frame.getRadius(), circles[i].getY()).start(tweenManager);
}
} else if (movedir < 0) {
frame.setX(frame.getX() - actualSpeed);
MyInputProcessor.dist += actualSpeed;
tweenManager.killAll();
for (int i = 0; i < parts.size(); i++) {
Tween.to(circles[i], Accessor.POS_XY, delayValue[i])
.target(frame.getX() - frame.getRadius(),
circles[i].getY()).start(tweenManager);
}
setting positions:
if(parts.size()!=0)
{
for (int i = 0; i <parts.size(); i++){
if(parts.get(i) instanceof Block){
circles[i].setIndex(parts.get(i).getIndex()) ;
circles[i].setPosition(circles[i].getX(), (frame.getY() -
(frame.getRadius() * 3)) - (60 * i));
}
In this way,I managed to make smooth movement as per my requirement.(Though it is not much fine as snake vs block game,but meets my requirement).
I want to code my own version of "game of life", in processing 3, but I've come across an error I don't seem to understand. Whenever the code run, the screen keeps going black and white with a few pixels changing but it does not look like game of life.
Any help?
int windowW, windowH, percentAlive, gen;
//windowW is the width of the window, windowH is the height
//percentVlive is the initial percent of alive pixel
//gen is the counter for the generation
color alive, dead;//alive is white and dead is black to represent their respective colors
boolean[][] cells0, cells1;//two arrays for the state of the cells, either alive or dead
boolean zeroOrOne = true;//this is to check which array should be iterated over
void setup() {
size(700, 700);
int width = 700;
int height = 700;
windowW = width;
windowH = height;
percentAlive = 15;
alive = color(255, 255, 255);
dead = color(0, 0, 0);
cells0 = new boolean[width][height];
cells1 = new boolean[width][height];
frameRate(2);
background(alive);
for (int x=0; x<width; x++) {//set the percent of live pixels according to the precentAlive varriable
for (int y=0; y<height; y++) {
int state = (int)random (100);
if (state > percentAlive)
cells0[x][y] = true;
else
cells0[x][y] = false;
}
}
}
void draw() {
gen += 1;//increases the generation every time it draws
drawLoop(zeroOrOne);
WriteGeneration(gen);
if(zeroOrOne){//changes the zeroOrOne value to change the array being iterated over
zeroOrOne = false;
}
else {
zeroOrOne = true;
}
}
void WriteGeneration(int number) {//changes the label on top
fill(0);
rect(0, 0, windowW, 100);
fill(255);
textFont(loadFont("BerlinSansFB-Reg-100.vlw"));
text("Generation " + number, 10, 90);
}
void drawLoop(boolean check) {
loadPixels();
if (check) {//checks which array to iterate thrgough
for (int x = 0; x < windowW; x++) {//iterates through the array
for (int y = 0; y < windowH; y++) {
if (cells0[x][y]) {//checks wether the pixel is alive or dead
pixels[x * 700 + y] = alive;//gets the current pixel
int lives = lives(x, y, check);//checks how many cells are alive around the current cell
if (lives<2) {//these are supposed to put in place the game of life rules
cells1[x][y] = false;
} else if (lives>4) {
cells1[x][y] = false;
} else {
cells1[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;//gets the current pixel
int lives = lives(x, y, check);//checks how many cells are alive around the current cell
if (lives == 3) {//turns the pixel alive if the condition is met
cells1[x][y] = true;
}
}
}
}
} else {//the same as the top but instead the arrays being updated and read are switched
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells1[x][y]) {
pixels[x * 700 + y] = alive;
int lives = lives(x, y, check);
if (lives<2) {
cells0[x][y] = false;
} else if (lives>4) {
cells0[x][y] = false;
} else {
cells0[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;
int lives = lives(x, y, check);
if (lives == 3) {
cells0[x][y] = true;
}
}
}
}
}
updatePixels();
}
int lives(int x, int y, boolean check) {//this just checks how many live pixels are around a given pixel
int lives = 0;
if (x > 1 && y >1 && x < 699 && y < 699) {
if (check) {
if (cells0[x-1][y-1])
lives++;
if (cells0[x][y-1])
lives++;
if (cells0[x+1][y-1])
lives++;
if (cells0[x-1][y])
lives++;
if (cells0[x+1][y])
lives++;
if (cells0[x-1][y+1])
lives++;
if (cells0[x][y+1])
lives++;
if (cells0[x+1][y+1])
lives++;
} else {
if (cells1[x-1][y-1])
lives++;
if (cells1[x][y-1])
lives++;
if (cells1[x+1][y-1])
lives++;
if (cells1[x-1][y])
lives++;
if (cells1[x+1][y])
lives++;
if (cells1[x-1][y+1])
lives++;
if (cells1[x][y+1])
lives++;
if (cells1[x+1][y+1])
lives++;
}
}
return lives;
}
Please post your code as an MCVE. When I try to run your code, I get an error because I don't have the font file your'e trying to load on line 59. That font has nothing to do with your problem, so you should really get rid of it before posting a question.
You've got a lot going on in this code. I understand why you have two arrays, but having them both at the sketch level is only over-complicating your code. You shouldn't need to constantly switch between arrays like that. Instead, I would organize your code like this:
You should only have one array at the sketch level. You can also get rid of the zeroOrOne variable.
Initialize that array however you want.
Create a nextGeneration() that returns a new array based on the current array. This will probably call other functions for counting neighbors and whatnot. But the point is that you can just create a new array every time instead of switching between two global arrays.
This removes all of your duplicated logic.
General notes:
Having 8 if statements to check the neighbors is a bit of overkill. Why not just use a nested for loop?
You should get into the habit of following proper naming conventions. Functions should start with a lower-case letter, and variables should be descriptive- naming something check doesn't really tell the reader anything.
If you still can't get it working, then you're going to have to do some debugging. Add print() statements, or use the Processing editor's debugger to step through the code. Which line behaves differently from what you expect? Then you can post an MCVE of just that line (and whatever hard-coded variables it needs to show the behavior) and we'll go from there. Good luck.
The issues you are having are twofold:
The two cells arrays that you have interfere and make two separate games, when you only want one.
You are updating the cells in your arrays before you get to the end of checking which ones need to be modified.
The way to solve both problems at once is to repurpose the cells1 array. Instead of checking it every other time, make it an array set entirely to false. Then, whenever you want to modify a square in cells0, set that location in cells1 to true, and after you make a marker of each cell you want to change, change them all at once with a separate for loop at the end of the drawLoop() method. This solves both problems in one fell swoop.
Once you have done this, you can remove the check and zeroAndOne variables, as you won't need them anymore. This is what I got for the drawLoop() method after I made the modifications I recommend:
void drawLoop() {
loadPixels();
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells0[x][y]) {
pixels[x * 700 + y] = alive;
int lives = lives(x, y);
if (lives<2) {
cells1[x][y] = true;
} else if (lives>4) {
cells1[x][y] = true;
}
} else {
pixels[x * 700 + y] = dead;
int lives = lives(x, y);
if (lives == 3) {
cells1[x][y] = true;
}
}
}
}
for (int x = 0; x < windowW; x++) {
for (int y = 0; y < windowH; y++) {
if (cells1[x][y]) {
cells0[x][y] = !cells0[x][y];
cells1[x][y] = false;
}
}
}
updatePixels();
}
I'm sure you can figure out the rest. Good luck!
I'm working on a program that displays circles colliding with the wall and with themselves.
I'm having trouble with the method that will compensate for collisions.
public class bouncyFX extends Application {
public ArrayList<Ball> arr = new ArrayList<Ball>();
public static void main(String[] args) {
launch(args);
}
static Pane pane;
#Override
public void start(final Stage primaryStage) {
pane = new Pane();
final Scene scene = new Scene(pane, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(final MouseEvent event) {
final Ball ball = new Ball(event.getX(), event.getY(), 40, Color.AQUA);
ball.circle.relocate(event.getX(), event.getY());
pane.getChildren().addAll(ball.circle);
arr.add(ball);
final Bounds bounds = pane.getBoundsInLocal();
final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
double deltaX = ball.ballDeltaX;
double deltaY = ball.ballDeltaY;
public void handle(final ActionEvent event) {
ball.circle.setLayoutX(ball.circle.getLayoutX() + deltaX);
ball.circle.setLayoutY(ball.circle.getLayoutY() + deltaY);
final boolean atRightBorder = ball.circle.getLayoutX() >= (bounds.getMaxX()-ball.circle.getRadius());
final boolean atLeftBorder = ball.circle.getLayoutX() <= (bounds.getMinX()+ball.circle.getRadius());
final boolean atBottomBorder = ball.circle.getLayoutY() >= (bounds.getMaxY()-ball.circle.getRadius());
final boolean atTopBorder = ball.circle.getLayoutY() <= (bounds.getMinY()+ball.circle.getRadius());
if(atRightBorder || atLeftBorder)
deltaX *= -1;
if(atBottomBorder || atTopBorder)
deltaY *= -1;
for(int i = 0; i<arr.size(); i++){
for(int j = i+1; j<arr.size()-1; j++){
arr.get(i).collisionMagnitued(arr.get(j));
}
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
});
}
class Ball{
public Circle circle;
public double ballDeltaX = 3;
public double ballDeltaY = 3;
public void AddBall(Ball b){
arr.add(b);
}
public Ball(double X, double Y, double Rad, Color color) {
circle = new Circle(X, Y, Rad);
circle.setFill(color);
}
private boolean defineCollision(Ball b){
double xd = this.circle.getLayoutX() - b.circle.getLayoutX();
double yd = this.circle.getLayoutY() - b.circle.getLayoutY();
double sumRad = this.circle.getRadius() + b.circle.getRadius();
double squareRad = Math.pow(sumRad, 2);
double distSquare = Math.pow(xd, 2) + Math.pow(yd, 2);
if(distSquare <= squareRad){
return true;
}return false;
}
public void collisionMagnitued(Ball b){
if(this.defineCollision(b)){
double tempDeltaX = ballDeltaX;
double tempDeltaY = ballDeltaY;
if((this.ballDeltaX < 0 && b.ballDeltaX > 0) || (this.ballDeltaX >0 && b.ballDeltaX <0)){
this.ballDeltaX *= -this.ballDeltaX;
b.ballDeltaX *= -b.ballDeltaX;
System.out.println("tredje");
}
if((this.ballDeltaY < 0 && b.ballDeltaY > 0) || (this.ballDeltaY > 0 && b.ballDeltaY < 0)){
this.ballDeltaY *= -this.ballDeltaY;
b.ballDeltaY *= -b.ballDeltaY;
System.out.println("fjärde");
}
else{
System.out.println("Knull");
this.ballDeltaX *= -1;
b.ballDeltaX *= -1;
}
}
}
}
}
The Balls (or circles) are created and are bouncing against the Bounds as expected.
The Collision detection method works as I'm getting print statements inside the last method. However, it seems that there's something wrong with either my ArrayList not being filled with objects or the method trying to compare the parameter Ball and the Ball that calls the method.
Am I way off? Not sure how I'm suppossed to go forth from here.
I see a few issues with your logic:
The first problem is that when the balls "bounce" off the boundaries of the pane, you don't change their ballDeltaX or ballDeltaY values (you just change a local value in the animation loop and use the local value to update the position). So the first time two balls collide, both of their ballDeltaX and ballDeltaY values are equal to +3 (the initial value), which may not represent the actual direction the animation loop is moving them in. In fact, you never actually use any updated values of ballDeltaX or ballDeltaY to compute the new positions; you get the initial values of those variables, copy them into deltaX and deltaY, and then just compute the new positions using deltaX and deltaY. So if you change ballDeltaX and ballDeltaY, the animation loop never sees the change.
The for loops look wrong to me; I don't think they compare the last two elements of the list. (When i = arr.size()-2 in the penultimate iteration of the outer loop, your inner loop is for (int j = arr.size() - 1; j < arr.size() -1; j++) {...} which of course never iterates.) I think you want the bounding conditions to be i < arr.size() - 1 and j < arr.size(), i.e. the other way around.
And then your if/else structure in collisionMagnitued(...) is probably not exactly what you want. I'm not sure what you're trying to implement there, but the else clause only kicks in if the second if is false, and no matter what happens in the first if.
Finally, you are starting a new animation on each mouse click. So, for example, if you have three balls bouncing around, you have three animation loops running, each of which is updating values when the balls collide. You need to start just one loop; it shouldn't do any harm if it refers to an empty list.
I am writing a small game where 20 balloons are created on screen and mouse released on them expands them. They are supposed to 'pop' when one balloon touches another, but at present when I click a balloon it pops a random one and throws an 'Array index out of bounds' exception. I've racked my brain to figure out why my code isn't working but just can't get it. Here's some of the code causing the problem:
import comp102.*;
import java.util.*;
import java.awt.Color;
public class BalloonGame implements UIButtonListener, UIMouseListener{
// Fields
private final int numBalloons = 20;
private int currentScore; // the score for the current game
private int highScore = 0; // highest score in all games so far.
private int totalPopped = 0;
Balloon balloons[] = new Balloon[numBalloons];
// Constructor
/** Set up the GUI, start a new game.
*/
public BalloonGame(){
UI.setMouseListener(this);
UI.addButton("New Game", this);
UI.addButton("Lock Score", this);
this.newGame();
}
// GUI Methods to respond to buttons and mouse
/** Respond to button presses, to start a new game and to end the current game */
public void buttonPerformed(String cmd){
if (cmd.equals("New Game")) { this.newGame(); }
else if (cmd.equals("Lock Score")) { this.endGame(); }
}
/** Respond to mouse released with the main action of the game*/
public void mousePerformed(String action, double x, double y) {
if (action.equals("released")) {
this.doAction(x, y);
}
}
/** Start the game:
Clear the graphics pane
Initialise the score information
Make a new set of Balloons at random positions
*/
public void newGame(){
UI.clearGraphics();
this.currentScore = 0;
this.totalPopped = 0;
for (int i = 0; i < this.balloons.length; i++) {
this.balloons[i] = new Balloon(50 + Math.random()*400, 50 + Math.random()*400);
this.balloons[i].draw();
}
UI.printMessage("New game: click on a balloon. High score = "+this.highScore);
}
/** Main game action.
Find the balloon at (x,y) if any,
Expand it
Check whether it is touching another balloon,
If so, update totalPopped, pop both balloons, and remove them from the list
Recalculate the score.
If there are no balloons left, end the game.
*/
public void doAction(double x, double y) {
for (int i = 0; i < this.balloons.length; i++) {
if (this.balloons[i].on(x, y) && !this.balloons[i].isPopped()) {
this.balloons[i].expand();
}
for (int j = 1; j <this.balloons.length; j++) {
if (this.balloons[i].isTouching(this.balloons[j]) && this.balloons[j] != null)
{
this.totalPopped +=2;
this.balloons[i].pop();
this.balloons[j].pop();
this.balloons[i] = null;
this.balloons[j] = null;
}
}
}
this.calculateScore();
if (totalPopped == numBalloons) {
this.endGame();
}
}
/** Find a balloon that the point (x, y) is on.
* Returns null if point is not on any balloon*/
public Balloon findBalloon(double x, double y){
return null;
}
/** Find and return another balloon that is touching this balloon
* Returns null if no such Balloon. */
public Balloon findTouching(Balloon balloon){
return null;
}
/** Calculate the score: sum of the sizes of current ballons, minus
the total of the popped balloons (totalPopped).
Report the score as a message */
public void calculateScore(){
for (Balloon b: balloons) {
this.currentScore += b.size();
}
if (currentScore >= highScore) {
this.highScore = this.currentScore;
}
UI.printMessage("Score = "+this.currentScore+" High score = "+this.highScore);
}
/** Returns true if all the balloons have been popped,
* Returns false if any of the balloons is not popped */
public boolean allPopped(){
for (Balloon b : this.balloons){
if (!b.isPopped()){
return false;
}
}
return true;
}
/** End the current game.
Record the the score as the new high score if it is better
Print a message
Clear the list of balloons (so the player can't keep playing)
*/
public void endGame(){
this.highScore = this.currentScore;
UI.println("High score = " + this.highScore);
Arrays.fill(balloons, null);
}
// Main
public static void main(String[] arguments){
BalloonGame ob = new BalloonGame();
}
}
uses the balloon class also:
import comp102.*;
import java.util.*;
import java.awt.Color;
import java.io.*;
/** Represents a balloon that can grow until it pops.
A Balloon can say whether a particular point is on it, and
whether it is touching another balloon.
It can also return its size.
Once it has popped, no point is on it, and it can't touch another balloon.
Also, its size is reported as a negative value.
*/
public class Balloon{
// Fields
private double radius = 10;
private double centerX, centerY;
private Color color;
private boolean popped = false;
// Constructors
/** Construct a new Balloon object.
Parameters are the coordinates of the center of the balloon
Does NOT draw the balloon yet.
*/
public Balloon(double x, double y){
this.centerX = x;
this.centerY = y;
this.color = Color.getHSBColor((float)Math.random(), 1.0f, 1.0f);
}
public void draw(){
UI.setColor(color);
UI.fillOval(centerX-radius, centerY-radius, radius*2, radius*2);
if (!this.popped){
UI.setColor(Color.black);
UI.drawOval(centerX-radius, centerY-radius, radius*2, radius*2);
}
}
/** Make the balloon larger by a random amount between 4 and 10*/
public void expand(){
if (! this.popped){
this.radius = this.radius + (Math.random()*6 + 4);
this.draw();
}
}
/** pop the balloon (changes colour to gray, draws, and pauses briefly)*/
public void pop(){
this.color = Color.lightGray;
this.popped = true;
this.draw();
UI.sleep(20);
}
/** Returns true if the balloon has been popped */
public boolean isPopped(){
return this.popped;
}
/** Returns true if the point (x,y) is on the balloon, and false otherwise */
public boolean on(double x, double y){
if (popped) return false;
double dx = this.centerX - x;
double dy = this.centerY - y;
return ((dx*dx + dy*dy) < (this.radius * this.radius));
}
/** Returns true if this Balloon is touching the other balloon, and false otherwise
* Returns false if either balloon is popped. */
public boolean isTouching(Balloon other){
if (this.popped || other.popped) return false;
double dx = other.centerX - this.centerX;
double dy = other.centerY - this.centerY;
double dist = other.radius + this.radius;
return (Math.hypot(dx,dy) < dist);
}
/** Calculates and returns the area of the balloon
* Returns it in "centi-pixels" (ie, number of pixels/100)
* to keep them in a reasonable range.
* Returns a negative size if it is popped.*/
public int size(){
int s = (int) ((this.radius * this.radius * Math.PI)/100);
if (popped) { s = 0 - s; }
return s;
}
}
is this right?
for (int j = 1; j <this.balloons.length; j++) {
doesn't it allow i and j to be equal, so you end up asking whether a balloon is touching itself? Do you mean j = i + 1 ?
If you are now getting null pointer exceptions, get into a debugger and step through until you see where. My guess is that you are visiting array items that have been popped, and hence are null.
if (this.balloons[i].isTouching(this.balloons[j]) && this.balloons[j] != null)
You are testing this.balloons[j] for null after you are using it. I'd put some null checks before trying to work with each item.