-1

Hello I am new to java been around a month since I started. I am trying to make a mini Halloween Mini game where a user enters a House and can choose to explore it. I am trying to do this through if and else statements and a JOption Pane. The problem seems to be that the JOptionPane.YES_OPTION is always triggered even if I have renamed the panes and am trying to access different panes.Any advice would be greatly appreciated.

Below is the code

private static int DiningRoom;
private static int livingroom;
private static int upStairs;





public static void main(String[] args) {
   JFormattedTextField nameField = new JFormattedTextField();
   ImageIcon iconic = new ImageIcon("HauntedHousemap.png");


   /* New JPanel */
  JPanel myPanel = new JPanel();
  myPanel.add(new JLabel("Enter your name to play: "));
  myPanel.add(nameField);
  myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

  int result = JOptionPane.showConfirmDialog(null, myPanel, 
           "Enter Name", JOptionPane.OK_CANCEL_OPTION);
  if (result == JOptionPane.OK_OPTION) {   
  }

  JOptionPane.showMessageDialog(null,"Here is the Map!","Map",JOptionPane.INFORMATION_MESSAGE, iconic);

  JOptionPane livingRoomPane = new JOptionPane();
  JOptionPane startingPane = new JOptionPane();

  //***************************** STARTING OPTIONS **************************************//
  Object [] mainOptions = { "Living Room", "Dining Room", "Stairs" };
  Object [] StairsOptions = { "Bedroom1", "Beedroom2", "MasterBedroom"};
  Object [] DiningOptions = { "Kitchen", "Explore Items"};
  Object [] PantryOptions = { "Pantry", "Explore Items"};
  Object [] LivingOptions = { "Bathroom", "Explore Items"};
  Object [] Bathroom1stFloorOptions = { "Mirror", "Shower"};
  Object [] LivingRoomItems = { "Chest", "TV"};
  Object [] DiningRoomItems = { "Candelabra", "Table"};
  Object [] BedRoom1Items = { "Bathroom", "Explore Items"};
  Object [] BedRoom2Items = { "Bathroom", "Explore Items"};
  Object [] MasterBedRoomItems = { "Master Bathroom", "Explore Items"};



  //*********************************** User will choose where he wants to go from the front door **********************************//

  int startInput = startingPane.showOptionDialog(null, //Component parentComponent
                       ("Greetings " +  nameField.getText() + ", You are at the front door pick a path if you dare!"), //Object message,
                        "Haunted House", //String title
                       startingPane.YES_NO_OPTION, //int optionType
                       startingPane.INFORMATION_MESSAGE,  //int messageType
                       null,mainOptions, mainOptions [0]  ); //Icon icon, 

    //********************* IF PLAYER PICKED LIVING ROOM OUT OF STARTING OPTIONS ***************************************//
    switch (startInput) {
        case JOptionPane.YES_OPTION:
            System.out.println ("You are now in the living room");
            int livingRoom = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to the bathroom or explore the living room?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,LivingOptions, LivingOptions [0]  );
            break;
        case JOptionPane.NO_OPTION:
            System.out.println ("You are now in the dinning room");
            int DiningRoom = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to the kitchen or explore the dining room?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,DiningOptions, DiningOptions [0]  );
            break;
        default:
            System.out.println("You are now upstairs");
            int upStairs = JOptionPane.showOptionDialog(null, //Component parentComponent
                    ("Do you wish to go to Bedroom1, Bedroom2, or the Master Bedroom?"), //Object message,
                    "Haunted House", //String title
                    JOptionPane.YES_NO_OPTION, //int optionType
                    JOptionPane.INFORMATION_MESSAGE,  //int messageType
                    null,StairsOptions, StairsOptions [0]  );
            break; }




switch (livingroom) {
case JOptionPane.YES_OPTION: 
System.out.println ("You are now in the 1st floor Bathroom");
int bathRoomFloor1 = JOptionPane.showOptionDialog(null, 
               ("Do you wish to go to the bathroom or explore the living room?"), //Object message,
               "Haunted House", //String title
               JOptionPane.YES_NO_OPTION, //int optionType
               JOptionPane.INFORMATION_MESSAGE,  //int messageType
               null,Bathroom1stFloorOptions, Bathroom1stFloorOptions [0]  );
break;

default:
System.out.println ("You are now in the Exploring the living room");
int livingRoomExplore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item to explore"), 
               "Haunted House", //String title
               JOptionPane.YES_NO_OPTION, //int optionType
               JOptionPane.INFORMATION_MESSAGE,  //int messageType
               null,LivingRoomItems, LivingRoomItems [0]  ); } 


switch (DiningRoom) {     
case JOptionPane.YES_OPTION: 
System.out.println ("You are now in the kitchen");
int kitchenFloor = JOptionPane.showOptionDialog(null, 
               ("Do you wish to go to the Pantry or explore the dining room?"),
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,PantryOptions, PantryOptions [0]  );
 break;
 default: 
 System.out.println ("You are now in the Exploring the dining room");
 int DiningRoomExplore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item to explore"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,DiningRoomItems, DiningRoomItems [0]  ); }

  switch (upStairs) {
  case JOptionPane.YES_OPTION: 
  System.out.println ("You are now in bedRoom1");
  int bedRoom1Explore = JOptionPane.showOptionDialog(null, 
               ("Do you want to go to the Bathroom or Explore the room?"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,BedRoom1Items, BedRoom1Items [0]  ); 
 break;

  case JOptionPane.NO_OPTION: 
  System.out.println ("Do you want to go to the Bathroom or Explore the 
  room?");
  int bedRoom2Explore = JOptionPane.showOptionDialog(null, 
               ("Pick an Item"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,BedRoom2Items, BedRoom2Items [0]  ); 
 break;
 default:
 System.out.println("You are now in the Master Bedroom");
 int masterBedExplore = JOptionPane.showOptionDialog(null, 
               ("Do you want to go to the Bathroom or Explore the room?"), 
               "Haunted House", 
               JOptionPane.YES_NO_OPTION, 
               JOptionPane.INFORMATION_MESSAGE,  
               null,MasterBedRoomItems, MasterBedRoomItems [0]  ); }

The issue is that after the 1st set of IF and ElSE statments it always types:

"You are in the 1st floor Bathroom" and the rest of the options become very switched and messed up.

Any advice would be greatly appreciated.

Arthur
  • 37
  • 1
  • 7
  • Aside: I think you'd ultimately be happier if you implemented this using a [`State` design pattern](https://sourcemaking.com/design_patterns/state). It will significantly reduce the complexity of the code. – KevinO Oct 19 '18 at 14:38
  • But how would I use a JOptionPane to execute that? I just clicked the link and I dont really see how I could link it. Sorry for my lack of knowledge – Arthur Oct 19 '18 at 14:41
  • At any point, there are a limited number of options. In each room (which would be a state), you ask for where to go. But, as I said, that is an aside. I think at a minimum, if you move the question from the JOptionPane into a method that takes the parameters, and put each room into a method, then use a global variable to track the "room" and dispatch accordingly, it will be better. In essence, there are dead-ins because there is no looping here. I went upstairs->bathroom->shower (though the output said kitchen)->explored item (though the output seed bedRoom1) and it exited. – KevinO Oct 19 '18 at 14:51
  • To make this work, you need to simplify the code, because (conceptually) I could go into a room and then back out, but the current logic is one-way. Your JPanel question should be part of a loop that then dispatches based upon the player's current location. – KevinO Oct 19 '18 at 14:53
  • It is ment to be one-way where the person cant back out. I just redid the code using the switch method but it still dosent work – Arthur Oct 19 '18 at 14:59

2 Answers2

2

Using a full State design pattern would be much better. But here is an example that will greatly simplify OP's current approach, and make debugging much easier. It will eliminate the deep if/else (or switch) hierarchy, and can be easily adapted/expanded. It also reduces a great deal of essentially duplicated code.

Basically, keep the collection of all possible locations, and then keep a state variable for where the player is currently located. Dispatch based upon the current location to the particular room. Each room sets up the possible moves.

This code is not complete (does not have all rooms), and the enum needs to be finished, have valid .toString() added, etc., but it shows a general pattern to simply the OP's code. Also, the getAction can take additional text to display, the title could be adjusted to reflect the current room (would need a parameter), etc.

enum Locations
{
    FrontDoor, LivingRoom, DiningRoom, Stairs, Bedroom1, Bedroom2, MasterBedroom, Kitchen, Pantry, Bathroom, ExploreLivingRoomItems,

    // add a .toString() for each place
}



private static String getPlayer()
{
    JFormattedTextField nameField = new JFormattedTextField();

    /* New JPanel */
    JPanel myPanel = new JPanel();
    myPanel.add(new JLabel("Enter your name to play: "));
    myPanel.add(nameField);
    myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));

    int result = JOptionPane.showConfirmDialog(null,
                                               myPanel,
                                               "Enter Name",
                                               JOptionPane.OK_CANCEL_OPTION);


    if (result == JOptionPane.OK_OPTION) {
        return nameField.getText();
    }
    else {
        return "";
    }
}



private static void showMap()
{
    // show the map
}



private static Locations getAction(String playerName, Locations[] locations)
{
    Object[] opts = new Object[locations.length];
    for (int i = 0; i < opts.length; ++i) {
        opts[i] = locations[i].toString();
    }

    int res = JOptionPane.showOptionDialog(null,
                                           "Select your next move, "
                                                   + playerName,
                                           "Haunted House",
                                           JOptionPane.YES_NO_OPTION,
                                           JOptionPane.INFORMATION_MESSAGE,
                                           null,
                                           opts,
                                           opts[0]);

    return locations[res];
}



private static Locations getFrontDoor(String playerName)
{
    Locations[] locs = { Locations.LivingRoom, Locations.DiningRoom,
            Locations.Stairs };

    return getAction(playerName,
                     locs);
}



private static Locations getLivingRoom(String playerName)
{
    Locations[] locs = { Locations.Bathroom, Locations.ExploreLivingRoomItems };
    return getAction(playerName,
                     locs);
}



public static void main(String[] args)
{
    Locations loc = Locations.FrontDoor;


    final String playerName = getPlayer();
    showMap();


    boolean keepGoing = true;

    while (keepGoing) {

        switch (loc) {
        case FrontDoor:
            loc = getFrontDoor(playerName);
            break;

        case LivingRoom:
            loc = getLivingRoom(playerName);
            break;

        // all other rooms
        } // switch
    }


}

Enter Name Front Door Options Living Room Options

KevinO
  • 4,303
  • 4
  • 27
  • 36
  • Thank you so much man. I will try it now get to understand the code abit and get back to you. – Arthur Oct 19 '18 at 15:33
  • @Arthur, do hope it helps. If the answer proves to be useful, please consider accepting it. – KevinO Oct 19 '18 at 16:16
  • 100% will bro thanks so much just a quick last question. How would I split this up into 2 classes with the main being seperate like if i try doing: – Arthur Oct 19 '18 at 19:21
  • Location loc = new Location(.FrontDoor); – Arthur Oct 19 '18 at 19:21
  • `Locations` is an enum (assuming no changes from above), so you don't need to instantiate it using `new`. You just assign it directly. `Locations loc = Locations.FrontDoor` for example. [There is some discussion here](https://stackoverflow.com/questions/16851377/instantiate-enum-class), but one of their advantages is their "singleton" nature. Hope that helps! – KevinO Oct 19 '18 at 21:52
0

Insteadof to use if else... Use this

  switch(c) {   
case value1:        ...         break; 
case value2:        ...         break;  
case valueN:        ...     
default: }

The code is more clean to read..so you understand where is the problem...

Ferdinando
  • 964
  • 1
  • 12
  • 23
  • I am doing it now but I am having a problem where even though I have set int livingroom to the pane for example it says that it cannot find the variable when I use it for the next set. How would I fix this and why is it doing that? – Arthur Oct 19 '18 at 14:49
  • @Arthur i see that you have two variable livingRoom one static and one int...last if which variable use? – Ferdinando Oct 19 '18 at 15:33
  • The static is there because it said I could not access the int – Arthur Oct 19 '18 at 16:03