Question

In: Computer Science

I have a JavaFx game that you have a rectangle and you move it with the...

I

have a JavaFx game that you have a rectangle and you move it with the arrow keys to shoot circles that I call enemies. I want to add some collision to the rectangle so that when it hits the circles the game ends and I also want to add a counter so that each time I shoot an enemy it adds 2 points and when you die it prints out how many points you get.

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;

public class MainClass extends Application {
   // Create Constructors

public Pane root;

public List<GameObject> bullets = new ArrayList<>();
public List<GameObject> enemies = new ArrayList<>();

public GameObject player;

public Parent createContent() {
root = new Pane();
root.setPrefSize(500, 500);
root.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null),null, null));
  
player = new Player();
player.setVelocity(new Point2D(1, 0));
addGameObject(player, 300, 300);
  
// Start Animation Timer

AnimationTimer timer = new AnimationTimer() {
@Override
public void handle(long now) {
onUpdate();
}
};
timer.start();

return root;
}
// Add the bullets and enemies

public void addBullet(GameObject bullet, double x, double y) {
bullets.add(bullet);
addGameObject(bullet, x, y);
}

public void addEnemy(GameObject enemy, double x, double y) {
enemies.add(enemy);
addGameObject(enemy, x, y);
}

public void addGameObject(GameObject object, double x, double y) {
object.getView().setTranslateX(x);
object.getView().setTranslateY(y);
root.getChildren().add(object.getView());
}
  
// Provide collions for the bullets and enimes

public void onUpdate() {
for (GameObject bullet : bullets) {
for (GameObject enemy : enemies) {
if (bullet.isColliding(enemy)) {
bullet.setAlive(false);
enemy.setAlive(false);

root.getChildren().removeAll(bullet.getView(), enemy.getView());
}
}
}
  

bullets.removeIf(GameObject::isDead);
enemies.removeIf(GameObject::isDead);

bullets.forEach(GameObject::update);
enemies.forEach(GameObject::update);

player.update();
  
// Generate the enemies

if (Math.random() < 0.03) {
addEnemy(new Enemy(), Math.random() * root.getPrefWidth(), Math.random() * root.getPrefHeight());
}
}
  
// Inherit the player,bullets, and enemies from the GameObject class
  
public class Player extends GameObject {
Player() {
super(new Rectangle(40, 20, Color.BLUE));
}
}

public class Enemy extends GameObject {
Enemy() {
super(new Circle(15, 15, 15, Color.RED));
}
}

public class Bullet extends GameObject {
Bullet() {
super(new Circle(5, 5, 5, Color.BROWN));
}
}
// Shoot the bullets
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.getScene().setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.LEFT) {
player.rotateLeft();
} else if (e.getCode() == KeyCode.RIGHT) {
player.rotateRight();
} else if (e.getCode() == KeyCode.SPACE) {
Bullet bullet = new Bullet();
bullet.setVelocity(player.getVelocity().normalize().multiply(5));
addBullet(bullet, player.getView().getTranslateX(), player.getView().getTranslateY());
}
});
stage.show();
}

public static void main(String[] args) {
launch(args);
}

GameObject

import javafx.geometry.Point2D;
import javafx.scene.Node;


public class GameObject {

   public Node view;
public Point2D velocity = new Point2D(0, 0);

public boolean alive = true;

public GameObject(Node view) {
this.view = view;
}

public void update() {
view.setTranslateX(view.getTranslateX() + velocity.getX());
view.setTranslateY(view.getTranslateY() + velocity.getY());
}

public void setVelocity(Point2D velocity) {
this.velocity = velocity;
}

public Point2D getVelocity() {
return velocity;
}

public Node getView() {
return view;
}

public boolean isAlive() {
return alive;
}

public boolean isDead() {
return !alive;
}

public void setAlive(boolean alive) {
this.alive = alive;
}

public double getRotate() {
return view.getRotate();
}

public void rotateRight() {
view.setRotate(view.getRotate() + 10);
setVelocity(new Point2D(Math.cos(Math.toRadians(getRotate())), Math.sin(Math.toRadians(getRotate()))));
}

public void rotateLeft() {
view.setRotate(view.getRotate() - 10);
setVelocity(new Point2D(Math.cos(Math.toRadians(getRotate())), Math.sin(Math.toRadians(getRotate()))));
}

public boolean isColliding(GameObject other) {
return getView().getBoundsInParent().intersects(other.getView().getBoundsInParent());
}
}

Solutions

Expert Solution

// GameObject.java

import javafx.geometry.Point2D;
import javafx.scene.Node;

public class GameObject {

   public Node view;
   public Point2D velocity = new Point2D(0, 0);

   public boolean alive = true;

   public GameObject(Node view) {
       this.view = view;
   }

   public void update() {
       view.setTranslateX(view.getTranslateX() + velocity.getX());
       view.setTranslateY(view.getTranslateY() + velocity.getY());
   }

   public void setVelocity(Point2D velocity) {
       this.velocity = velocity;
   }

   public Point2D getVelocity() {
       return velocity;
   }

   public Node getView() {
       return view;
   }

   public boolean isAlive() {
       return alive;
   }

   public boolean isDead() {
       return !alive;
   }

   public void setAlive(boolean alive) {
       this.alive = alive;
   }

   public double getRotate() {
       return view.getRotate();
   }

   public void rotateRight() {
       view.setRotate(view.getRotate() + 10);
       setVelocity(new Point2D(Math.cos(Math.toRadians(getRotate())), Math.sin(Math.toRadians(getRotate()))));
   }

   public void rotateLeft() {
       view.setRotate(view.getRotate() - 10);
       setVelocity(new Point2D(Math.cos(Math.toRadians(getRotate())), Math.sin(Math.toRadians(getRotate()))));
   }

   public boolean isColliding(GameObject other) {
       return getView().getBoundsInParent().intersects(other.getView().getBoundsInParent());
   }
}

// MainClass.java

import java.util.ArrayList;
import java.util.List;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class MainClass extends Application {
   // Create Constructors

   public Pane root;

   public List<GameObject> bullets = new ArrayList<>();
   public List<GameObject> enemies = new ArrayList<>();
   public int score = 0;

   public GameObject player;

   public Parent createContent() {
       root = new Pane();
       root.setPrefSize(500, 500);
       root.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null), null, null));

       player = new Player();
       player.setVelocity(new Point2D(1, 0));
       addGameObject(player, 300, 300);

// Start Animation Timer

       AnimationTimer timer = new AnimationTimer() {
           @Override
           public void handle(long now) {
               if(player.isAlive())
                   onUpdate();
               else
               {
                   showScore();
                   this.stop();
               }
           }

       };
       timer.start();

       return root;
   }
  
  
   public void showScore() {
       GameObject g = new GameObject(new Rectangle(root.getHeight(),root.getWidth()));
      
       root.getChildren().add(g.getView());
       Label l = new Label("Game Over\nYour Score is: "+score);
       l.setAlignment(Pos.CENTER);
       l.setFont((new Font("Arial", 30)));
       l.setTextFill(Color.WHITE);
      
       root.getChildren().add(l);
  
   }
// Add the bullets and enemies

   public void addBullet(GameObject bullet, double x, double y) {
       bullets.add(bullet);
       addGameObject(bullet, x, y);
   }

   public void addEnemy(GameObject enemy, double x, double y) {
       enemies.add(enemy);
       addGameObject(enemy, x, y);
   }

   public void addGameObject(GameObject object, double x, double y) {
       object.getView().setTranslateX(x);
       object.getView().setTranslateY(y);
       root.getChildren().add(object.getView());
   }

// Provide collions for the bullets and enimes

   public void onUpdate() {
       for (GameObject bullet : bullets) {
           for (GameObject enemy : enemies) {
               if (bullet.isColliding(enemy)) {
                   bullet.setAlive(false);
                   enemy.setAlive(false);
                   score += 2;
                   root.getChildren().removeAll(bullet.getView(), enemy.getView());
               }
           }
       }

       for (GameObject enemy : enemies) {
           if (player.isColliding(enemy)) {
               player.setAlive(false);
               root.getChildren().removeAll(player.getView());
           }
       }

       bullets.removeIf(GameObject::isDead);
       enemies.removeIf(GameObject::isDead);

       bullets.forEach(GameObject::update);
       enemies.forEach(GameObject::update);

       player.update();

// Generate the enemies

       if (Math.random() < 0.03) {
           addEnemy(new Enemy(), Math.random() * root.getPrefWidth(), Math.random() * root.getPrefHeight());
       }
   }

// Inherit the player,bullets, and enemies from the GameObject class

   public class Player extends GameObject {
       Player() {
           super(new Rectangle(40, 20, Color.BLUE));
       }
   }

   public class Enemy extends GameObject {
       Enemy() {
           super(new Circle(15, 15, 15, Color.RED));
       }
   }

   public class Bullet extends GameObject {
       Bullet() {
           super(new Circle(5, 5, 5, Color.BROWN));
       }
   }

// Shoot the bullets
   @Override
   public void start(Stage stage) throws Exception {
       stage.setScene(new Scene(createContent()));
       stage.getScene().setOnKeyPressed(e -> {
           if (e.getCode() == KeyCode.LEFT) {
               player.rotateLeft();
           } else if (e.getCode() == KeyCode.RIGHT) {
               player.rotateRight();
           } else if (e.getCode() == KeyCode.SPACE) {
               Bullet bullet = new Bullet();
               bullet.setVelocity(player.getVelocity().normalize().multiply(5));
               addBullet(bullet, player.getView().getTranslateX(), player.getView().getTranslateY());
           }
       });
       stage.show();
   }

   public static void main(String[] args) {
       launch(args);
   }
}


Related Solutions

(6) A diagonal of a rectangle in neutral geometry divides the rectangle into triangle I and...
(6) A diagonal of a rectangle in neutral geometry divides the rectangle into triangle I and triangle II. Can the angle-sum of triangle I be less than 180°? Why or why not?
Suppose you are given the following one-shot, simultaneous-move game:                               &nbsp
Suppose you are given the following one-shot, simultaneous-move game:                                      BP and Exxon are deciding whether or not to charge a high price or a low price for       gasoline sales tomorrow. The two firms cannot collude, and both will post their prices tomorrow at the same time. This game has the following payoff matrix (profits for the day are in parentheses):                                                                                     Exxon High Price Low Price High Price ($800, $800) (-$300, $1,200) Low Price ($1,200, -$300) ($500,...
In this project we will implement the Minesweeper game. Minesweeper is played on a rectangle grid....
In this project we will implement the Minesweeper game. Minesweeper is played on a rectangle grid. When the game starts, a number of bombs are hidden on random positions on the field. In every round, the player "touches" a cell of the field. If the cell contains a bomb, it explodes, the game ends, and the player loses. Otherwise, the cell is uncovered to show the number of bombs in the vicinity, that is, the number of neighboring cells that...
Consider the following information for a simultaneous move game: If you advertise and your rival advertises,...
Consider the following information for a simultaneous move game: If you advertise and your rival advertises, you each will earn $5 million in profits. If neither of you advertises, you will each earn $10 million in profits. However, if one of you advertises and the other does not, the firm that advertises will earn $15 million and the non-advertising firm will earn $1 million. If you and your rival plan to be in business for 10 (ten) years, then the...
Four firms (A, B, C, and D) play a simultaneous-move pricing game. Each firm (i) may...
Four firms (A, B, C, and D) play a simultaneous-move pricing game. Each firm (i) may choose any price Pi ∈ [0, ∞) with the goal of maximizing its own profit. (Firms do not care directly about their own quantity or others’ profits.) Firms A and B have MC = 10, while firms C and D have MC = 20. The firms serve a market with the demand curve Q = 100 – P. All firms produce exactly the same...
This is the assignment I have, I need the best game theory problem example for it...
This is the assignment I have, I need the best game theory problem example for it which is difficult. Thank you:) Think of an example of a decision problem or a game theory problem. This time you will have to submit the source of the story. You can take it from a newspaper, from Internet, magazine, book... 1. Submit a photocopy or a printed version of your problem. 2. Simplify the problem and represent it using the concepts of game...
Consider the hypothetical example using game theory. Assume that it is a one-off simultaneous move game,...
Consider the hypothetical example using game theory. Assume that it is a one-off simultaneous move game, and that each player only cares about their own payoff. LG and Samsung are deciding whether or not to release a new 360-degree camera. If both LG and Samsung release the camera, then LG will make $20 million profit, and Samsung will make $40 million profit. If LG releases the camera, and Samsung does not, then LG will make $30 million profit and Samsung...
A game design document is used to develop an actual game. I would like you to...
A game design document is used to develop an actual game. I would like you to be disciplined from the start and build a document that you shall use later to build your final project. However, please note that a game design document is a living document. Therefore, you are allowed to change the game design document according to the progress made in the later modules. Most of game designers know that larger the design team, the better the document....
Design and implement a class Rectangle to represent a rectangle. You should provide two Constructors for...
Design and implement a class Rectangle to represent a rectangle. You should provide two Constructors for the class, the first being the default constructor and the second which takes the basic dimensions and sets up the private member variables with the appropriate initial values. Methods should be provided that allow a user of the class to find out the length, width, area and perimeter of the shape plus a toString()method to print the values of the basic dimensions. Now implement...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length...
This is python #Create a class called Rectangle. Rectangle should #have two attributes (instance variables): length and #width. Make sure the variable names match those words. #Both will be floats. # #Rectangle should have a constructor with two required #parameters, one for each of those attributes (length and #width, in that order). # #Rectangle should also have a method called #find_perimeter. find_perimeter should calculate the #perimeter of the rectangle based on the current values for #length and width. # #perimeter...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT