Question

JavaFX program - Add a second level to the game. //Main game object/class package main; import java.util.ArrayList; impo...

JavaFX program - Add a second level to the game.

//Main game object/class
package main;

import java.util.ArrayList;
import javafx.animation.AnimationTimer;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;


public class Game extends Pane implements Runnable {
  
   // instance variables

   private ArrayList<MOB> mobs;
   private ArrayList<Rectangle> hitBoxes;
   private ArrayList<Treasure> treasure;
   private Player player;
   private final ImageView background = new ImageView();
   private Level level;
   private SimpleIntegerProperty score;
   private int enemyCount;
   private int chestCount;
   private HBox GUIView;

/**
   * Constructor
   */
   public Game(Stage stage) {
   // create the score counter
this.score = new SimpleIntegerProperty(0);
// create our mobs arraylist
       this.mobs = new ArrayList<>();
// create the arraylist for MOB & wall hitboxes
       this.hitBoxes = new ArrayList<>();
       // create an arraylist for our treasure objects
this.treasure = new ArrayList<>();
       this.enemyCount = 0;
this.loadLevel(1); // load the first level of our game.
this.initGUI(); // load/initialize the GUI
// run our main loop once the stage is shown
stage.setOnShown(e -> this.run());
   }
  

   /**
   * Loads the default/background images for our lvlMap
   * @param in   the integer value for the lvlMap image to load
   * all images are 'lvlMap' + in
   */
   private void loadLevel(int in) {
hitBoxes.clear(); // clear the list of hitboxes
mobs.clear();   // remove any existing old mobs
       switch (in) {
           case 1:
               this.level = new Level1();
           break;
           case 2:
               this.level = new Level2();   // placeholder for second level
break;
       }
       background.setImage(level.getImage());   // get the background image
       hitBoxes.addAll(level.getWalls());   // get all the wall hitboxes
       enemyCount = level.getEnemyCount();       // get the enemy count from the level
chestCount = level.treasureCount(); // get the treasure count from the level
       this.getChildren().add(background);       // add the lvlMap imageview to scene
this.getChildren().addAll(hitBoxes); // add all the hitboxes for the walls to the scene
// this.getChildren().addAll(stopWatchGUI.getStopWatch()));
this.initTreasure(chestCount); // add the treasure chests for the level
this.initMobs(enemyCount); // initialize our mobs
}

/**
   * Initializes the default mobs for a given level
   */
   private void initMobs(int count) {
player = (player == null ? new Player(this.level) : player); // load the player
player.setStartPoint(level.playerStart()[0], level.playerStart()[1]);
       mobs.add(player); // add the player to the mob array first, so always index 0
       // add our enemies to the arraylist after the player
   for (int i = 0; i < count; i++) {
   mobs.add(new Enemy(this.level, i));
}
   // set the starting coordinates for each enemy, skip the player/index 0
for (int i = 1; i < mobs.size(); i++) {
/* the enemy coordinates are stored in a 2-element array
with index 0 = x-coord, and index 1 = y-coord */
Double[] coords = level.getEnemyCoords().get(i-1);
mobs.get(i).setStartPoint(coords[0], coords[1]);
}
   // iterate over the list of mobs and...
       for (int i = 0; i < mobs.size(); i++) {
       MOB m = mobs.get(i);
           hitBoxes.add(m.getHitbox());   // add it's hitbox to our hitbox list
this.getChildren().add(m.getHitbox()); // add the hitbox to the scene
           this.getChildren().add(m.getView());   // add it's view to our scene
       }
}


private void initTreasure(int count) {
for (int i = 0; i < count; i++) {
Double[] coords = level.treasureCoords().get(i);
Treasure t = new Treasure(i, coords[0], coords[1]);
treasure.add(t);
hitBoxes.add(t.getHitbox());
this.getChildren().addAll(t.getHitbox(), t.getView());
}
}


private Treasure getTreasure(Rectangle r) {
for (int i = 0; i < treasure.size(); i++){
if (treasure.get(i).getHitbox().equals(r)) {
return treasure.get(i);
}
}
return null;
}

/**
* Collision check method to determine if the player
* has hit enemies, or treasure/chests
*/
private void collisionCheck() {
for (int i = 1; i < hitBoxes.size(); i++) {
Rectangle r = hitBoxes.get(i); // get the hitbox to check
boolean bool = player.getHitbox().intersects(r.getBoundsInParent()); // see if the boxes intersect
if (bool) {
if (r.getFill().equals(Color.RED)) { // RED = enemy collision
player.takeDamage(1); // if we're the player, take damage
} else if (r.getFill().equals(Color.BLACK)) { // BLACK = fake wall
// TODO fakeWallCollision();
// play a secret sound, ala zelda.
} else if (r.getFill().equals(Color.GREEN)) { // GREEN = treasure/chest
Treasure t = getTreasure(r);
if (!t.isOpen()) {
score.set(score.get() + 10); // increase the score
chestCount--; // decrease our global chest count to track end of level
t.openNow(); // open the chest so it can't be opened twice
}
}
}
}
}

   /**
   * Main game loop method.
   */
   private void play() {
       // Creates gameLoop, where most operations will be handled
       gameLoop = new AnimationTimer() {
               // check if we're ready to move the enemies
for (int i = 0; i < mobs.size(); i++) {
MOB m = mobs.get(i);
if (m instanceof Enemy) {
((Enemy) m).moveCheck(arg0);
}
}
// check for collisions with the player and other objects
collisionCheck();
// check if our player isDead/we need to respawn
if (player.isDead()) {
}
if (player.livesProperty().get() > 0 && player.isDead()) {
player.reSpawn();
}
               // check if the level is over
if (chestCount == 0) {
// DO Something for level over!    
}
           }
   };
       // start the loop now
       gameLoop.start();
   }


   /**
   * Main runnable:
* 1) register our key handler
   * 2) register our game over listener
* 3) starts playing the game
   */
   @Override
   public void run() {
   // Uncomment to see the actual stage layout coordinates for the scene
// this is useful to determine the width and height of the window frame
   // System.out.println("layoutX: " + this.getScene().getX()); = 0
// System.out.println("layoutY: " + this.getScene().getY()); = 22
this.getScene().setOnKeyPressed(e -> player.moveHandler(e));
   // this.getScene().setOnKeyPressed(player::moveHandler);// java8+ method reference style
       // start the game loop now
       this.play();
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program import javafx.application.Application; imoort javafx.geometry.Insets; import javafx. scene. Group import javafx. scenImageView Image (ThreeCard. class final Imageview imgvw4 final Image img4 getResourceAsStream (Threecard.get (2) + .pnq));

2. import javafx.application.Application import javafx. stage. Stage; import javafx.scene.. import javafx. event.*; public cl

Code:

import javafx.application.Application;

import javafx.geometry.Insets;

import javafx.scene.Group;

import javafx.scene.Scene;

import javafx.scene.layout.GridPane;

import javafx.scene.paint.Color;

import javafx.scene.image.Image;

import javafx.scene.image.ImageView;

import javafx.scene.layout.HBox;

import javafx.stage.Stage;

import java.util.*;

public class ThreeCard extends Application

{

    public static void main(String[] args)

     {

        Application.launch(args);

    }

   

    @Override

    public void start(Stage ThreeCardprimaryStage)

     {

        ArrayList<Integer> Threecard = new ArrayList<>();

        for(int i = 1;i < 55;i++)

            Threecard.add(i);

        cardshuffle(Threecard);

       

        ThreeCardprimaryStage.setTitle("Three Cards");

        Group ct = new Group();

        Scene scene = new Scene(ct, 250, 130, Color.GREEN);

       

        GridPane gridpane = new GridPane();

        gridpane.setPadding(new Insets(5));

        gridpane.setHgap(10);

        gridpane.setVgap(10);

       

        final ImageView imgvw2 = new ImageView();

final Image img2 = new Image(ThreeCard.class. getResourceAsStream(Threecard.get(0) +".png"));

        imgvw2.setImage(img2);       

        final ImageView imgvw3 = new ImageView();

final Image img3 = new Image(ThreeCard.class. getResourceAsStream (Threecard.get(1)+ ".png"));

        imgvw3.setImage(img3);

       

        final ImageView imgvw4 = new ImageView();

final Image img4 = new Image(ThreeCard.class. getResourceAsStream (Threecard.get(2)+ ".png"));

        imgvw4.setImage(img4);

        final HBox imageRgn = new HBox();

       

        imageRgn.getChildren().addAll(imgvw2,imgvw3,imgvw4);

        gridpane.add(imageRgn, 1, 1);

       

        ct.getChildren().add(gridpane);       

        ThreeCardprimaryStage.setScene(scene);

        ThreeCardprimaryStage.show();

    }

   

    public static void cardshuffle( ArrayList<Integer> list )

    {

        Collections.cardshuffle(list);

    }

}

2. To play audion

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.*;

import javafx.event.*;

public class PlaySound extends Application

{

    Button btn;

    MediaPlayer mediaPlayer;

    // Main code part is added in the existing code

     public static void main(String[] args)

     {

        Application.launch(args);

   }

   

@Override

    public void start(Stage primaryStage)

     {

Media hit = new Media("http://ak.channel9.msdn.com/ch9/56ef/e9aef824-77b5-45c5-b48e-a005017456ef/WindowsBlogWin8CPSizzle_ch9.mp3");

// Media hit = new Media(new File("audio/name.mp3").toURI().toString());

        mediaPlayer = new MediaPlayer(hit);

        mediaPlayer.play();

        btn = new Button("Pause");

        btn.setOnAction(new EventHandler<ActionEvent>()

          {

            @Override

            public void handle(ActionEvent event)

{

                if (btn.getText().equals("Pause"))

              {

                    mediaPlayer.pause();

                    btn.setText("Play");

                } else

              {

                    mediaPlayer.play();

                    btn.setText("Pause");

                }

            }

        });

}

}

Add a comment
Know the answer?
Add Answer to:
JavaFX program - Add a second level to the game. //Main game object/class package main; import java.util.ArrayList; impo...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private...

    package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private static int cardNumber[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; private static char suitName[] = { 'c', 'd', 'h', 's' }; public static void main(String[] args) throws CardException, DeckException, HandException { Scanner kb = new Scanner(System.in); System.out.println("How many Players? "); int numHands = kb.nextInt(); int cards = 0; if (numHands > 0) { cards = 52 / numHands; System.out.println("Each player gets " + cards + " cards\n"); } else...

  • JAVAFX ONLY PROGRAM!!!!! SORTING WITH NESTED CLASSES AND LAMBDA EXPRESSIONS. DIRECTIONS ARE BELOW: DIRECTIONS: The main...

    JAVAFX ONLY PROGRAM!!!!! SORTING WITH NESTED CLASSES AND LAMBDA EXPRESSIONS. DIRECTIONS ARE BELOW: DIRECTIONS: The main point of the exercise is to demonstrate your ability to use various types of nested classes. Of course, sorting is important as well, but you don’t really need to do much more than create the class that does the comparison. In general, I like giving you some latitude in how you design and implement your projects. However, for this assignment, each piece is very...

  • import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private...

    import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private ArrayList<String> words; private HashSet<String> foundWords = new HashSet<String>(); public FindWordInMaze(char[][] grid) { this.grid = grid; this.words = new ArrayList<>();    // add dictionary words words.add("START"); words.add("NOTE"); words.add("SAND"); words.add("STONED");    Collections.sort(words); } public void findWords() { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[i].length; j++) { findWordsFromLocation(i, j); } }    for(String w: foundWords) { System.out.println(w); } } private boolean isValidIndex(int i, int j, boolean visited[][]) { return...

  • /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {   ...

    /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {    /**    * @param args    */    public static void main(String[] args) {        List groceryList = new ArrayList<>();        groceryList.add("rice");        groceryList.add("chicken");        groceryList.add("cumin");        groceryList.add("tomato");        groceryList.add("cilantro");        groceryList.add("lime juice");        groceryList.add("peppers");               groceryList.remove("cilantro");               for (int i = 0; i            if (groceryList.get(i).equals("peppers")) {...

  • What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class...

    What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test implements Comparable<Test> private String[] cast; public Test( String[] st) cast = st; public int compareTo( Test t) if ( cast.length >t.cast.length ) t return +1; else if cast.length < t.cast.length return -1; else return 0; public static void main( String[] args String[] a"Peter", "Paul", "Mary" String[] b_ { "Мое", ''Larry", "Curly", String [ ] c = { ·Mickey", "Donald" }; "Shemp" }; List<Test>...

  • Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections;...

    Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections; class Grid { private boolean bombGrid[][]; private int countGrid[][]; private int numRows; private int numColumns; private int numBombs; public Grid() { this(10, 10, 25); }    public Grid(int rows, int columns) { this(rows, columns, 25); }    public Grid(int rows, int columns, int numBombs) { this.numRows = rows; this.numColumns = columns; this.numBombs = numBombs; createBombGrid(); createCountGrid(); }    public int getNumRows() { return numRows;...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • package week_4; import input.InputUtils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; import static input.InputUtils.positiveIntInput; import static input.InputUtils.yesNoInput;...

    package week_4; import input.InputUtils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; import static input.InputUtils.positiveIntInput; import static input.InputUtils.yesNoInput; /** Write a program to roll a set of dice. Generate a random number between 1 and 6 for each dice to be rolled, and save the values in an ArrayList. Display the total of all the dice rolled. In some games, rolling the same number on all dice has a special meaning. In your program, check if all dice have the same value,...

  • import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args)...

    import java.util.Random; import java.util.ArrayList; /** * */ public class hw5_task8 { public static void main(String[] args) { int[] grades = randomIntArr(10); printIntArray("grades", grades); ArrayList<Integer> indexesF_AL = selectIndexes_1(grades); System.out.println(" indexesF_AL: " + indexesF_AL); int[] indexesF_Arr = selectIndexes_2(grades); printIntArray("indexesF_Arr",indexesF_Arr); } public static int[] randomIntArr(int N){ int[] res = new int[N]; Random r = new Random(0); for(int i = 0; i < res.length; i++){ res[i] = r.nextInt(101); // r.nextInt(101) returns an in in range [0, 100] } return res; } public static void...

  • / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import...

    / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.media.AudioClip; import javafx.stage.Stage; public class JukeBox extends Application { private ChoiceBox<String> choice; private AudioClip[] tunes; private AudioClip current; private Button playButton, stopButton;    //----------------------- // presents an interface that allows the user to select and play // a tune from a drop down box //-----------------------   ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT