0

This is the code below I am using javafx canvas I am new to javafx and I want to add a background image to my Java fx game but it wont work i tried using pane and tried using draw at the beginning of the ccode but it didnt work. Here is my code how can I add a background in it I tried every possible solution but the picture won't show up in the background. Thanks in advance.

public class Main extends Application {

    //variables
    private static final Random RAND = new Random();
    private static final File themeFile=new File("music\\theme.mp3");
    private static final Media theme=new Media(themeFile.toURI().toString());
    private static final MediaPlayer themePlayer=new MediaPlayer(theme);
    File chickenFile=new File("music\\chickenSound.wav");
    Media chickenTheme=new Media(chickenFile.toURI().toString());
    MediaPlayer chickenSound=new MediaPlayer(chickenTheme);

    private static final int width = 1000;//screen width
    private static final int height = 800;//screen height
    private static final int rocketSize = 60;// rocket size in pixels
    static final Image backGround = new Image("file:images/back.png");
    static final Image chickensImage = new Image("file:images/1.png");
    static final Image rocketImage = new Image("file:images/spaceship.png");
    static final Image explosion = new Image("file:images/dead.png");
    static final Image logo = new Image("file:images/logo.png");
    static final Image heart = new Image("file:images/health.png");

    static final int steps = 15;
    static final int explosionHeight = 120;
    static final int explosionWidth = 120;
    static final int explosionImageRows = 3;
    static final int explosionImageColumns = 3;

    final int chickensOnScreen = 8;//max number of chickens can exist on screen
    final int shotsOnScreen = chickensOnScreen * 2;
    boolean dead = false;
    boolean start=false;
    private GraphicsContext gc;

    Rocket player;//instantiate the rocket class
    List<Shot> shots; //list of references shots
    List<Chicken> chickenList;

    private double mouseX;
    private int score;//score variable
     private int lives=3;
    
    public void start(Stage stage)  throws Exception {

        Canvas canvas = new Canvas(width, height);
        gc = canvas.getGraphicsContext2D();
        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(100), e -> run(gc)));
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
        canvas.setCursor(Cursor.MOVE);
        canvas.setOnMouseMoved(e -> mouseX = e.getX());

       canvas.setOnMouseClicked(e -> {
           if(!start){
               start=true;
                setup();
           }
            if(shots.size() < shotsOnScreen) {
                shots.add(player.shoot());
            }
            if(dead) {
                dead = false;
                anotherChance();
            }
            if (lives==0){
                Restart();
                lives=3;
            }
        });

        if (start) {
            setup();
        }
        shots = new ArrayList<>();
        chickenList = new ArrayList<>();
        player = new Rocket(width / 2, height - rocketSize, rocketSize, rocketImage);
        score = 0;//initialize the score variable
        stage.setScene(new Scene(new StackPane(canvas)));
        stage.setTitle("Chicken Invaders 1.0");
        stage.show();
    }

    //setup the game
    private void setup() {
        IntStream.range(0, chickensOnScreen).mapToObj(i -> this.newChicken()).forEach(chickenList::add);//copied
    }
    private void anotherChance(){
        shots = new ArrayList<>();
        chickenList = new ArrayList<>();
        player = new Rocket(width / 2, height - rocketSize, rocketSize, rocketImage);
        IntStream.range(0, chickensOnScreen).mapToObj(i -> this.newChicken()).forEach(chickenList::add);//copied
    }
    private void Restart(){
        shots = new ArrayList<>();
        chickenList = new ArrayList<>();
        player = new Rocket(width / 2, height - rocketSize, rocketSize, rocketImage);
        score =0;//initialize the score variable
        IntStream.range(0, chickensOnScreen).mapToObj(i -> this.newChicken()).forEach(chickenList::add);//copied
    }

//screen initialization
    private void run(GraphicsContext gc) {
        gc.setFill(Color.grayRgb(35));//set background color
        gc.fillRect(0, 0, width, height);//fill all the gui
        gc.setTextAlign(TextAlignment.CENTER);//align text to center
        gc.setFont(Font.font(25));//font size
        gc.setFill(Color.WHITE);//font color
        gc.fillText("Score: " + score, 50,  20);
        for (int i = 0; i < lives; i++) {
            gc.drawImage(heart, i * 28 + 8, height-30,20,20);
        }
        if(!start){
            gc.setFont(Font.font(35));
            gc.setFill(Color.WHITE);
            gc.drawImage(logo,300,40,400,250);
            gc.fillText("Welcome to Chicken Invaders 1.0 \n Click on the mouse to start", width / 2, height /2.5);


        }
        if(lives==0) {//print a message if the player lost
            gc.setFont(Font.font(35));
            gc.setFill(Color.WHITE);
            gc.fillText("Game Over \n You Scored: " + score + " \n Click the Mouse to play again", width / 2, height /2.5);

        }
        player.update();
        player.draw();
        player.posX = (int) mouseX;

        chickenList.stream().peek(Rocket::update).peek(Rocket::draw).forEach(e -> {
            if(player.collide(e) && !player.exploding) {
                player.explode();
            }
        });

        //remove the shot if the toRemove boolean variable is set
        //it is set when a shot collides with a chicken
        for (int i =0; i < shots.size() ; i++) {
            Shot shot = shots.get(i);
            if(shot.posY < 0 || shot.toRemove)  {
                shots.remove(i);
                continue;
            }
            shot.update();
            shot.draw();

        //if the shot collided with the target increment the score,explode the target and make the shot disappear

            for (Chicken chicken : chickenList) {
                if(shot.collide(chicken) && !chicken.exploding) {
                    score++;
                    chicken.explode();
                      chickenFile=new File("music\\chickenSound.wav");
                      chickenTheme=new Media(chickenFile.toURI().toString());
                      chickenSound=new MediaPlayer(chickenTheme);

                    chickenSound.setAutoPlay(true);

                    shot.toRemove = true;
                }
            }
        }
        //for loop to create new chickens in the next round if the chicken is killed or passed down the screen

        for (int i =0; i < chickenList.size(); i++){
            if(chickenList.get(i).destroyed)  {
                chickenList.set(i, newChicken());
            }
        }

        dead = player.destroyed;
        if(dead && lives!=0){
            gc.setFont(Font.font(35));
            gc.setFill(Color.WHITE);
            gc.fillText("You died but you have " + lives + " more live(s) \n Click the Mouse to continue", width / 2, height /2.5);
        }

    }

    
  • 2
    [mcve] please .. – kleopatra May 02 '21 at 03:24
  • The answer to this question shows how to set background color of `Canvas`: https://stackoverflow.com/questions/25468882/change-color-of-background-in-javafx-canvas However you want background image. Based on the answer to that question, you just need to set a background image on the parent container of the `Canvas`. See this question: https://stackoverflow.com/questions/9738146/javafx-how-to-set-scene-background-image Also this question: https://stackoverflow.com/questions/36699991/background-image-in-javafx – Abra May 02 '21 at 07:50

0 Answers0