简体   繁体   中英

How to create a JavaFX Scene for multiple Key Listeners?

so I am trying to create a Tron mulitplayer game, which is a bit like snake. Anyways multiple people should be able to play that game using one keyboard, but diffrent key combinations to steer their character on the screen. One player would currently use the WASD Keys and the other one should use the arrow keys.

My problem is that I have created a scene with Javafx Scene Builder using an FXML. Only after creating the game I have noticed that the scene builder is apparently only supporting one key listener, so at the moment only one player can control their game figure. Is there any way to fix that? Please help so one player can use the WASD-Keys and the other one can use the arrow keys to navigate. MY question is diffrent from the existing solutions as the snakes need to belong to diffrent players. It is not sufficient to just check if a key input was pressed or two were pressed simultaneously, but it needs to check if the correct player pressed the input, even if another player pressed their input at that time too. Hope that clears up the confusuion a bit.

Key Listener

 import java.util.ArrayList;

import javafx.scene.Scene;

public class Human extends Player implements Runnable{


int keyboardControlsLayout;
Scene scene;

public Human(int stepSize, String colour, int playerNum, Scene scene, 
           int keyboardControlsLayout) {
    super(stepSize, colour, playerNum);
    // keyboardControlsLayout(0) = WASD
    // keyboardControlsLayout(1) = ARROWS
    this.keyboardControlsLayout = keyboardControlsLayout;
    this.scene = scene;

}

@Override
public void run() {
    // TODO Auto-generated method stub

    while(this.getSnake().getAlive()) {

        if (keyboardControlsLayout == 1) {
            // use WASD
            System.out.println("wasd");

            scene.setOnKeyPressed(event -> {
                switch (event.getCode()) {
                    case W:
                        snake.setDirection(0);
                        break;
                    case S:
                        snake.setDirection(1);
                        break;
                    case A:
                        snake.setDirection(3);
                        break;
                    case D:
                        snake.setDirection(2);
                        break;
                    default:
                        break;
                }
                //System.out.println(event.getCode().toString());
            });


        } else if (keyboardControlsLayout == 0) {
            System.out.println("arrows");
            // use arrow keys
            scene.setOnKeyPressed(event -> {
                switch (event.getCode()) {
                    case UP:
                        snake.setDirection(0);
                        break;
                    case DOWN:
                        snake.setDirection(1);
                        break;
                    case LEFT:
                        snake.setDirection(3);
                        break;
                    case RIGHT:
                        snake.setDirection(2);
                        break;
                    default:
                        break;
                }
            });
        }


    }

}
 }

Where I create the scene:

public void newGame() {
    System.out.println("<----- NEW GAME ----->");
    game = new Game(10, scene, numHumans);
    displayController.setUpDisplay(game);

    timer = new Timeline((new KeyFrame(
            Duration.millis(80),
            event -> {
                try {
                    timerTick();
                } catch (Exception e) {
                    // TODO Auto-generated catch 
                                         block
                    e.printStackTrace();
                }
            })));
    timer.setCycleCount(Animation.INDEFINITE);

    start();
}

private void start() {
// starts game and logic
}


private void loadDisplayFXMLLoader() {
    FXMLLoader displayFXMLLoader = new 
    FXMLLoader(getClass().getResource("DisplayView.fxml"));

    try {
        scene = new Scene(displayFXMLLoader.load(), 500, 525);
    } catch (IOException e) {
        Main.outputError(e);
    }

    displayController = displayFXMLLoader.getController();

}

private void loadScene() {
    this.setScene(scene);
    this.show();

    //error Handling and closing



}

Any help would be appreciated!

Thanks

I'm not familiar with FXML but I personally use the javafx myself and it works well. I tweaked an old program to suit your needs if you'd like to try and test it out

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class yeet {

    private static JFrame frame;
    private static JPanel panel;

    private static int x = 300;
    private static int y = 300;
    private static int x1 = 500;
    private static int y1 = 500;

    private static boolean running = true;
    private static boolean moving = false;
    private static boolean moving1 = false;
    private static boolean up;
    private static boolean down;
    private static boolean right;
    private static boolean left;
    private static boolean up1;
    private static boolean down1;
    private static boolean right1;
    private static boolean left1;

    private static Timer refresh;
    private static Timer speed;

    private static Graphics g;

    public static void main(String[] args) {

        UI();



        ActionListener al = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(moving && up) y--;
                if (moving && down) y++;
                if (moving && right) x++;
                if (moving && left) x--;

                if (moving1 && up1) y1--;
                if (moving1 && down1) y1++;
                if (moving1 && right1) x1++;
                if (moving1 && left1) x1--;

                panel.repaint();

            }

        };

        ActionListener al1 = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                guy(g);
                laser(g);

            }

        };

        refresh = new Timer(0, al1);
        refresh.start();
        speed = new Timer (4, al);
        speed.start();



        while (running) {
            guy(g);
            laser(g);

        }

    }

    public static void guy(Graphics g) {
        g = panel.getGraphics();
        g.setColor(Color.green);
        g.drawRect(x, y, 25, 25);
        g.fillRect(x, y, 25, 25);

    }

    public static void laser (Graphics g) {
        g = panel.getGraphics();
        g.setColor(Color.red);
        g.drawRect(x1, y1, 30, 30);
        g.fillRect(x1, y1, 30, 30);
    }

    public static void UI () {

        frame = new JFrame("Multiple movement test");
        panel = new JPanel();

        panel.setBackground(Color.black);
        panel.setLayout(null);

        frame.setSize(600,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_UP) {
                    moving = true;
                    up = true;

                    down = false;
                    right = false;
                    left = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                    moving = true;
                    down = true;

                    up = false;
                    right = false;
                    left = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    moving = true;
                    left = true;

                    up = false;
                    down = false;
                    right = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    moving = true;
                    right = true;

                    left = false;
                    up = false;
                    down = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_W) {
                    moving1 = true;
                    up1 = true;

                    down1 = false;
                    right1 = false;
                    left1 = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_A) {
                    moving1 = true;
                    left1 = true;

                    up1 = false;
                    down1 = false;
                    right1 = false;


                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_S) {
                    moving1 = true;
                    down1 = true;

                    up1 = false;
                    right1 = false;
                    left1 = false;

                    refresh.start();
                    speed.start();
                }

                if (e.getKeyCode() == KeyEvent.VK_D) {
                    moving1 = true;
                    right1 = true;

                    up1 = false;
                    down1 = false;
                    left1 = false;

                    refresh.start();
                    speed.start();
                }

            }

            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyTyped(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

        });

        frame.add(panel);

    }
}   

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM