Условный оператор для методов перемещения в пазле BlueJ Java - PullRequest
0 голосов
/ 14 февраля 2019

Мне нужно пройти несколько методов, чтобы пройти через комнату и выйти.Если вы наступаете на каждое место, оно включает или выключает силовое поле.Как бы я написал условное утверждение для метода перемещения?Моя продолжает говорить мне, что я не могу, даже когда я должен быть в состоянии сделать шаг.

Я понимаю, как двигаться, но я не понимаю, как отформатировать условное выражение, чтобы позволить мне преодолеть барьеры, которые выключены (ложь), в то время как другие барьеры включены (правда).То есть, если красные барьеры включены, а желтый выключен, я смогу перейти к желтому, но это не тот случай, поскольку он говорит мне, что путь заблокирован.

 /*
 * 
 * This class allows a user to walk around in a virtual 3x3 room 
 * and solve a puzzle.
 * 
 * The room has nine locations with the following (x, y) coordinates.
 * 
 *                      (0, 0)  (1, 0)  (2, 0)
 *                      (0, 1)  (1, 1)  (2, 1)
 *                      (0, 2)  (1, 2)  (2, 2)
 *                      
 * The user starts at location (1, 2).  Directly across the room from the 
 * user is a door.  The door may be blocked by 0, 1, or 2 force fields.  
 * The frame of the door identifies which force field is currently blocking 
 * it: a red frame means that only the red force field is on, a yellow frame 
 * means that only the yellow force field is on, an orange frame means that 
 * both force fields are on, and a green frame means that both fields are off. 
 * 
 * Depending where the user steps in the room one of the force fields will 
 * either turn on or off. The goal of the puzzle is to cross the room (i.e., 
 * reach position (1,0)) facing the door with both force fields off (i.e., a 
 * green frame).  
 * 
 * The constructor and the methods of this class are incomplete.  The comments 
 * tell you what is missing.  You do not need to add any fields to this class.  
 * You do not need to change any of the other classes in this project.
 */

public class Puzzle
{

    //Your current xy position in the room
    private int xPosition;
    private int yPosition;

    //Boolean variables that tell you whether or not the red and yellow
    //force fields are currently turned on (true) or off (false).
    private boolean yellowField;
    private boolean redField;

    private View view;

    public Puzzle()
    {

        /*
         * Finish: Initialize xPosition and yPosition to reflect that your 
         * initial position in the puzzle is (1,2) and that both force fields 
         * are initially off.
         */
        xPosition = 1;
        yPosition = 2;
        yellowField = false;
        redField = false;
        view = new View();
        view.display(xPosition, yPosition, yellowField, redField);
    }

    public void moveForward() 
    { 
        /*
         * Finish: Implement this method that moves you forward in the room
         * if there is not a wall blocking you.  Otherwise print a message
         * alerting the user that this move is not permitted now.
         * 
         * If the move is allowed then you should call toggleFields() and
         * view.display(xPosition, yPosition, yellowField, redField) afterward.
         */

     }

    public void moveBackward()
    {
        /*
         * Finish: Implement this method that moves you backward in the room
         * if there is not a wall blocking you.  Otherwise print a message
         * alerting the user that this move is not permitted now.
         * 
         * If the move is allowed then you should call toggleFields() and
         * view.display(xPosition, yPosition, yellowField, redField) afterward.
         */

        if (yellowField)
        {
            if (yellowField == false)
                {
                    yPosition += 1;
                    toggleFields();
                    view.display(xPosition, yPosition, yellowField, redField);
                }
            else
                {
                    System.out.println("Your path is blocked pick another move");
                }
        }
        else
        {
            if (redField == false)
                {
                    yPosition += 1;
                    toggleFields();
                    view.display(xPosition, yPosition, yellowField, redField);
                }
            else
                {
                    System.out.println("Your path is blocked pick another move");
                }
        }
    }

    public void moveRight()
    {

    }

    public void moveLeft()
    {
        /*
         * Finish: Implement this method that moves you to the left in the room
         * if there is not a wall blocking you.  Otherwise print a message
         * alerting the user that this move is not permitted now.
         * 
         * If the move is allowed then you should call toggleFields() and
         * view.display(xPosition, yPosition, yellowField, redField) afterward.
         * 
         */

    }

    private void toggleFields()
    {
        /*
         * Finish: Implement this method that turns a field on or off depending 
         * on where you step.  The following table describes the coordinate system 
         * and the effect of stepping in a particular location.
         * 
         * The x coordinate of a location is its row number, and the y coordinate 
         * is its column number.
         * 
         *     0   1   2  
         *  ------------
         *  0| r   r   r
         *   |
         *  1| r   y   r
         *   |
         *  2| y   y   y
         *  
         *  
         *  By stepping in a location labeled 'r' the red force field will turn 
         *  'on' if it is currently 'off' and 'off' if it is currently turned 'on'.
         *  
         *  By stepping in a location labeled 'y' the yellow force field will turn 
         *  'on' if it is currently 'off' and 'off' if it is currently turned 'on'.
         */
        if(redField)
        {
            if (redField == true)
            {
                redField = false;
            }
            else 
            {
                redField = true;
            }
        }
        else
        {
            if (yellowField == true)
            {   
                yellowField = false;
            }
            else
            {
                yellowField = true;
            }
        }
    }  

    public void walkthrough()
    {
        /*
         * Extra Credit:  Provide a sequence of calls to moveForward(), moveLeft(), 
         * moveRight(), and moveBackward() that solves the puzzle.  The puzzle is
         * solved if these moves take the user from location (1, 2) to location (1, 0)
         * facing a green door.
         * 
         */   
    }
}

1 Ответ

0 голосов
/ 14 февраля 2019

Редактировать:
Ошибка вашего метода в том, что вы не обращаете внимания на то, какие координаты включит / выключит желтое или красное поле.Вы просто проверяете, включены ли они.Итак, сначала вы должны принять к сведению эти разные координаты, поскольку, как вы сказали, есть определенные координаты, которые будут включать или выключать либо желтое, либо повторное поле.После того, как вы узнаете эти координаты, вы затем проверяете, находится ли пользователь в желто-красной позиции, после чего вы должны проверить, в каком состоянии находится это поле (например, если оно в данный момент включено, то вы выключаете его).

Я понимаю, как двигаться, но я не понимаю, как отформатировать условное выражение, чтобы позволить мне преодолевать барьеры, которые выключены (ложь), в то время как другие барьеры включены (правда).То есть, если красные барьеры включены, а желтый выключен, я смогу перейти к желтому, но это не тот случай, так как он говорит мне, что путь заблокирован.

Основа на том, что высказал выше, я думаю, что вы неправильно поняли проблему.Вы предполагаете, что у каждого местоположения есть силовое поле, и это зависит от буквы y / r на карте, но я думаю, что это не так.Только дверь имеет силовое поле, и ваша цель - добраться до того места, где дверь со всеми силовыми полями выключена.Поскольку, если вы придерживаетесь своего понимания и цель состоит в том, чтобы перевести пользователя из местоположения (1, 2) в местоположение (1, 0), обращенное к зеленой двери (все поля отключены), это будет невозможно.

Это будет карта:

               0   1   2
            --------------  
            0| r   r   r  
            1| r   y   r  
            2| y   y   y  

Тогда это будет статус:
начало в координате (1,2) (redField выключен, yellowField выключен)
перейти к координате (1,1) (redField выключен, yellowField включен)
перейти к координатам (1,0) (redField включен, yellowField включен)

Вы находитесь в положении целино все поля включены, таким образом, вы еще не закончили, однако в этом состоянии вы не можете двигаться, так как все поля включены.Делать эту проблему неразрешимой, если вы предполагаете, что алгоритм должен быть выполнен так же, как вы сказали.

Отсюда вы можете обратиться к моему первоначальному ответу о том, как решить проблему.

Оригинальный ответ:
Прежде всего у меня будут эти предположения, так как вашописание того, как работает игра, неясно.

  1. Цель игры - перейти в «определенное» место, но вам необходимо отключить все силовые поля этого места, чтобы войти.
  2. That »определенное место "никогда не объявляется в программе, и нет параметра метода, который объявляет его, поэтому я предполагаю, что это статическая переменная.Поэтому пока я буду использовать комментарий метода пошагового руководства и назначу местоположение пользователя (1, 2), а «определенное» местоположение места - (1, 0)

Учитывая приведенное выше предположениеВот как вы будете реализовывать игру.

Вы должны реализовать следующие проверки:

  1. Сначала вам нужно проверить границы.
    In your case this one:<br>
    (0, 0) (1, 0) (2, 0)<br>
    (0, 1) (1, 1) (2, 1)<br>
    (0, 2) (1, 2) (2, 2)<br>
    Thus your x and y coordinate should not be less than 0 or more than 2
    <li>Check if the red field is on. </li>
    <li>Check if the yellow field is on.</li>
    <li>Check if you are facing the door and the green frame is on</li>
    </ol>
    
    <p>Here is the gist:</p>
    
    <p>In beginning of your movement methods (moveLeft, moveRight, moveBackward, moveForward) you have to calculate where to user will go. And from that newly calculated place you have to do the above checking (Check 1 only).</p>
    
    <p>Example:</p>
    
    <pre><code>public void moveBackward() {
        int tmpY = yPosition + 1; // Subtract 1 from y position since the user is about to move backward
    
        // Check # 1
        if (tmpY > 2) { // you only need this check since you know that you are only incrementing yPosition
            System.out.println("Your path is blocked pick another move");
            return;
        }
    
        // If a valid move but the user did not win
        yPosition = tmpY;
        toggleFields();
        view.display(xPosition, yPosition, yellowField, redField);
    }
    </code>

    Теперь вам нужно реализовать оставшиеся проверки в ваших полях toggleFieldsМетод.

    public void toggleFields(){ /* You can store all the locations of the red and yellow fields in a matrix but for simplicity sake I will just hard code it to the if/else statements. * Also the goal location is hard coded since there is no mention from your post where the goal location is. The goal location is (1.0) * 0 1 2 * ------------ * 0| r r r * | * 1| r y r * | * 2| y y y */ // Check # 2 if ((xPosition == 0 && yPosition == 0) || (xPosition == 1 && yPosition == 0) || (xPosition == 2 && yPosition == 0) || (xPosition == 0 && yPosition == 1) || (xPosition == 2 && yPosition == 1) ) { if (redField) { redField = false; } else { redField = true; } } // Check # 3 if ((xPosition == 1 && yPosition == 1) || (xPosition == 0 && yPosition == 2) || (xPosition == 1 && yPosition == 2) || (xPosition == 2 && yPosition == 2) ) { if (yellowField) { yellowField= false; } else { yellowField= true; } } // Check # 4 if (!redField && !yellowField && xPosition == 1 && yPosition == 0) { System.out.println("You win"); return; } }
...