Как получить переменную из другого класса без создания объекта - PullRequest
0 голосов
/ 10 мая 2018

Я создаю игру Risk на Java, и мне нужна помощь по графической части.

У меня есть 3 класса, первый является основным, который запустит второй:

public class Main extends StateBasedGame{

public static final String nomjeu = "Risk !"; //name of the game
public static final int nombre_joueurs = 0;
public static final int nom_joueurs = 1;

public Main(String nomjeu) {

    super(nomjeu);
    this.addState(new NombreJoueurs(nombre_joueurs));
    this.addState(new NomJoueurs(nom_joueurs));
}

public void initStatesList(GameContainer container) throws SlickException{

    this.getState(nombre_joueurs).init(container, this);
    this.getState(nom_joueurs).init(container, this);
    this.enterState(nombre_joueurs);

}

public static void main(String[] args) {

    AppGameContainer appgc;
    try {

        appgc = new AppGameContainer(new Main(nomjeu));
        appgc.setDisplayMode(1920/2,1080/2, false);
        appgc.start();

    }catch(SlickException e) {
        e.printStackTrace();
    }

}

Второй - это класс, в котором я показываю 5 пяти кнопок, чтобы спросить пользователя, сколько игроков будет играть в игру (от 2 до 6):

public class NombreJoueurs extends BasicGameState{


int nb_joueurs; //number of players
Image bouton_2_joueurs;
Image bouton_3_joueurs;
Image bouton_4_joueurs;  
Image bouton_5_joueurs;
Image bouton_6_joueurs;

public NombreJoueurs(int slate) {

}


public void init(GameContainer container, StateBasedGame sbg) throws SlickException {

    bouton_2_joueurs = new Image("res/button_2_joueurs.png");
    bouton_3_joueurs = new Image("res/button_3_joueurs.png");
    bouton_4_joueurs = new Image("res/button_4_joueurs.png");
    bouton_5_joueurs = new Image("res/button_5_joueurs.png");
    bouton_6_joueurs = new Image("res/button_6_joueurs.png");
    nb_joueurs = 0;

}

public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {

    int x = Mouse.getX();
    int y = Mouse.getY();

    // 2 Players
    if( (x>423 && y>400) && (x<567 && y<440) ) {

        if (Mouse.isButtonDown(0)) {

            nb_joueurs = 2;
            sbg.enterState(1);


        }

    }
    // 3 Players
    if( (x>423 && y>330) && (x<567 && y<370) ) {

        if (Mouse.isButtonDown(0)) {

            nb_joueurs = 3;
            sbg.enterState(1);

        }

    }
    // 4 Players
    if( (x>423 && y>260) && (x<567 && y<300) ) {

        if (Mouse.isButtonDown(0)) {

            nb_joueurs = 4;
            sbg.enterState(1);

        }

    }
    // 5 Players
    if( (x>423 && y>190) && (x<567 && y<230) ) {

        if (Mouse.isButtonDown(0)) {

            nb_joueurs = 5;
            sbg.enterState(1);

        }

    }
    // 6 Players
    if( (x>423 && y>120) && (x<567 && y<160) ) {

        if (Mouse.isButtonDown(0)) {

            nb_joueurs = 6;
            sbg.enterState(1);

        }

    }

}

public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {

    g.drawString("Combien de joueurs ?", 405, 50);
    bouton_2_joueurs.draw(420,100);
    bouton_3_joueurs.draw(420,170);
    bouton_4_joueurs.draw(420,240);
    bouton_5_joueurs.draw(420,310);
    bouton_6_joueurs.draw(420,380);

}





public int getID() {
    return 0;
}

Например, если он нажмет кнопку «2 игрока», я собираюсь установить значение nb_joueurs равным 2 и запустить свой третий класс, где я прошу его ввести имена игроков:

public class NomJoueurs extends BasicGameState {

TextField nomj1;
TextField nomj2;
TextField nomj3;
TextField nomj4;
TextField nomj5;
TextField nomj6;



public NomJoueurs(int state) {

}


public void init(GameContainer container, StateBasedGame sbg) throws SlickException {

    // Here there should be the code where I create the textfields, but I need to know how many players
    // are playing to create the right amount of textfields.
    // So I need to get the variable nombre_joueurs

}

public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException {


}


public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {

    g.drawString("Quels sont les noms des joueurs ?", 330, 50);

}


public int getID() {
    return 1;
}

Мне нужно получить переменную nb_joueurs в моем третьем классе. Как я могу это сделать ?

Я уже пробовал геттеры, но не могу создать объект для получения значения.

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Помимо статичности, обязательно создайте экземпляр класса, если он не загружен.Сделайте это с помощью

Class.forName(NombreJoueurs.class.getCanonicalName());
0 голосов
/ 10 мая 2018

Если он статический, вы можете просто использовать статические геттеры, такие как

private static String test;

public static String getTest() {
        return test;
    }

    public static void setTest(String test) {
        Main.test = test;
    }
...