Chapitre 4: Jeu Sokoban

Solutions

SOLUTION TASK 4.01 to 4.09

public class MyKara extends KaraSokoban {
    
    int counter = 0;

    public void act() {
        String key = getKey();

        if (key.equals("right")) {
            setDirectionRight();
            tryToMove();
        }

        if (key.equals("down")) {
            setDirectionDown();
            tryToMove();
        }

        if (key.equals("left")) {
            setDirectionLeft();
            tryToMove();
        }

        if (key.equals("up")) {
            setDirectionUp();
            tryToMove();
        }
    }

    /**
     * Kara makes one step. This method first tests if Kara can move or if he
     * has to move a mushroom first.
     */
    public void tryToMove() {
        if (!treeFront()) {
            if (mushroomFront()) {
                if (canPushMushroom()) {
                    move();
                    counter++;
                    setNumberOfMoves(counter);
                }
            } else {
                move();
                counter++;
                setNumberOfMoves(counter);
            }

            if (testLevelComplete()) {
                saveHighscore();
                levelComplete();
            }
        }
    }

    /**
     * Handles the saving of the highscore.
     */
    public void saveHighscore() {
        // Test if it is in the top 3
        if (isHighscoreTop3(counter)) {
            // Is in top 3 --> add it
            addHighscoreEntry(counter);
        }
    }
}

Comments