IP BOM FALTA CONSTANTES

 avatar
unknown
java
5 months ago
11 kB
2
Indexable
import java.util.Scanner;

final char TREASURE_ROOM_SYMBOL = 'T';
final char LOOPER_ROOM_SYMBOL = 'L';
final char STARTING_POSITION_SYMBOL = 'P';
final char ESCAPE_ROOM_SYMBOL = 'E';
final char STAIR_ROOM_SYMBOL = 'S';
final char ZIGZAGGER_ROOM_SYMBOL = 'Z';
final char EMPTY_ROOM_SYMBOL = '.';
final int LEVEL1 = 0;
final int LEVEL2 = 1;
final int NUMBER_OF_LEVELS = 2;
final int looperSteps = 1;
final String MOVE_RIGHT = "right";
final String MOVE_LEFT = "left";
final String QUIT = "quit";
final String ZIGZAGGER_INFORMATION = "Level 2 enemy: Zigzagger, room ";
final String LOOPER_LEVEL_INFORMATION = "Level ";
final String LOOPER_ROOM_INFORMATION = "enemy: Looper, room";
final String PLAYER_LEVEL_INFORMATION = "Player: level ";
final String PLAYER_ROOM_INFORMATION = ", room ";
final String PLAYER_TREASURES_COLLECTED_INFORMATION = ", treasures ";
final String LOOPER = "looper";
final String ZIGZAGGER = "zigzagger";
char[][] dungeon = new char[NUMBER_OF_LEVELS][];
char[][] enemyPositions = new char[NUMBER_OF_LEVELS][];

int zigzaggerSteps = 1;
int totalTreasures = 0;
int treasuresCollected = 0;
int currentRoom = 0;
int currentLevel = 0;
int[] escapePosition = new int[2];
boolean gameOver;
boolean quitGame;
boolean winGame;
boolean gameLostMessageDisplayed;

void inItState() {
    totalTreasures = 0;
    treasuresCollected = 0;
    gameOver = false;
    winGame = false;
    currentRoom = 0;
    currentLevel = 0;
    gameLostMessageDisplayed = false;
    quitGame = false;
}

char[] levelsInChar(String sLevel) {
    char[] level;
    level = sLevel.toCharArray();
    return level;
}

char[] readLevel(Scanner scanner) {
    String input = scanner.nextLine();
    return levelsInChar(input);
}

int countTotalTreasures() {
    int count = 0;
    for (int i = 0; i < dungeon.length; i++) {
        for (int j = 0; j < dungeon[i].length; j++) {
            if (dungeon[i][j] == TREASURE_ROOM_SYMBOL) {
                count++;
            }
        }
    }
    return count;
}

void movePlayer(String direction, int steps) {
    if (direction.equals(MOVE_RIGHT)) {
        currentRoom = Math.min(currentRoom + steps, dungeon[currentLevel].length - 1);
    } else if (direction.equals(MOVE_LEFT)) {
        currentRoom = Math.max(currentRoom - steps, 0);
    }
}

void checkForTreasure() {
    if (dungeon[currentLevel][currentRoom] == TREASURE_ROOM_SYMBOL) {
        treasuresCollected++;
        dungeon[currentLevel][currentRoom] = EMPTY_ROOM_SYMBOL;
    }
}

// Método para mover todos os inimigos
void moveEnemies() {
    // Criar um buffer para armazenar as novas posições dos inimigos
    char[][] enemyPositionsBuffer = cloneEnemyPositions(enemyPositions);

    // Mover os Loopers
    moveLoopers(enemyPositionsBuffer);

    // Mover os Zigzaggers
    moveZigzaggers(enemyPositionsBuffer);

    // Atualizar as posições dos inimigos com as novas posições calculadas
    for (int i = 0; i < enemyPositions.length; i++) {
        enemyPositions[i] = enemyPositionsBuffer[i].clone();
    }
}

// Método para clonar as posições dos inimigos
char[][] cloneEnemyPositions(char[][] enemyPositions) {
    char[][] buffer = new char[enemyPositions.length][];
    for (int i = 0; i < enemyPositions.length; i++) {
        buffer[i] = enemyPositions[i].clone();
    }
    return buffer;
}

// Método para mover os Loopers
void moveLoopers(char[][] enemyPositionsBuffer) {
    for (int i = 0; i < dungeon.length; i++) {
        for (int j = 0; j < dungeon[i].length; j++) {
            if (enemyPositions[i][j] == LOOPER_ROOM_SYMBOL) {
                enemyPositionsBuffer[i][j] = EMPTY_ROOM_SYMBOL; // Limpa a sala atual
                if (j + 1 >= dungeon[i].length) {
                    enemyPositionsBuffer[i][0] = LOOPER_ROOM_SYMBOL; // Movimento circular
                } else {
                    enemyPositionsBuffer[i][j + 1] = LOOPER_ROOM_SYMBOL; // Mover uma sala à direita
                }
            }
        }
    }
}

// Método para mover os Zigzaggers
void moveZigzaggers(char[][] enemyPositionsBuffer) {
    for (int i = 0; i < dungeon.length; i++) {
        for (int j = 0; j < dungeon[i].length; j++) {
            if (enemyPositions[i][j] == ZIGZAGGER_ROOM_SYMBOL) {
                enemyPositionsBuffer[i][j] = EMPTY_ROOM_SYMBOL; // Limpa a sala atual

                // Calcular a nova posição, considerando o movimento circular
                if (j + zigzaggerSteps >= dungeon[i].length) {
                    int stepsBeyond = (j + zigzaggerSteps) % dungeon[i].length;
                    enemyPositionsBuffer[i][stepsBeyond] = ZIGZAGGER_ROOM_SYMBOL;
                } else {
                    enemyPositionsBuffer[i][j + zigzaggerSteps] = ZIGZAGGER_ROOM_SYMBOL;
                }

                // Atualizar o passo do Zigzagger
                if (zigzaggerSteps == 5) {
                    zigzaggerSteps = 1;
                } else {
                    zigzaggerSteps++;
                }
            }
        }
    }
}

void checkForEnemyCollision() {
    char symbol = enemyPositions[currentLevel][currentRoom];
    if(symbol == LOOPER_ROOM_SYMBOL || symbol == ZIGZAGGER_ROOM_SYMBOL) {
        gameOver = true;

    }
}

int findStairPosition(int level) {
    for (int i = 0; i < dungeon[level].length; i++) {
        if (dungeon[level][i] == STAIR_ROOM_SYMBOL) {
            return i;
        }
    }
    return -1;
}

void checkForStairs() {
    if(dungeon[currentLevel][currentRoom] == STAIR_ROOM_SYMBOL) {
        if(currentLevel == LEVEL1) currentLevel = LEVEL2;
        else currentLevel = LEVEL1;

        currentRoom = findStairPosition(currentLevel);
    }
}

int findLevelEnemy(int level) {
    for (int i = 0; i < enemyPositions[level].length; i++) {
        char symbol = enemyPositions[level][i];
        if(symbol == LOOPER_ROOM_SYMBOL || symbol == ZIGZAGGER_ROOM_SYMBOL) {
            return i;
        }
    }
    return -1;
}

String getEnemyFromType(char type) {
    if(type == LOOPER_ROOM_SYMBOL) return LOOPER;
    else return ZIGZAGGER;
}

void displayLevelEnemy(int level) {
    int enemyPosition = findLevelEnemy(level);
    char enemySymbol = enemyPositions[level][enemyPosition];
    System.out.println("Level " + (level+1) + " enemy: " + getEnemyFromType(enemySymbol) + " room " + (enemyPosition+1));
}

void displayGameInformation() {
    System.out.println("Player: level " + (currentLevel + 1) + " room " + (currentRoom + 1) + " treasures " + treasuresCollected);
    displayLevelEnemy(LEVEL1);
    displayLevelEnemy(LEVEL2);
}
boolean checkWin() {
    return treasuresCollected == totalTreasures && dungeon[currentLevel][currentRoom] == ESCAPE_ROOM_SYMBOL;
}

void findPositions() {

    for (int i = 0; i < dungeon.length; i++) {
        for (int j = 0; j < dungeon[i].length; j++) {
            char symbol = dungeon[i][j];
            if (symbol == STARTING_POSITION_SYMBOL) {
                currentLevel = i;
                currentRoom = j;
            }else if(symbol == ESCAPE_ROOM_SYMBOL) {
                escapePosition[0] = i;
                escapePosition[1] = j;
            }
        }
    }

}

void shouldContinue(String direction) {
    if (direction.equals(QUIT)) {
        quitGame = true; // Indicar que o jogo deve encerrar
    }
}

// Main method to control the game flow
void playGame(Scanner scanner) {
    while (!quitGame) {
        // Obter a direção e o número de passos
        String direction = getInputDirection(scanner); // Obter direção válida do input

        // Verificar se o jogador deseja sair
        shouldContinue(direction);

        // Se o jogador digitou "quit", não processamos mais
        if (quitGame) {
            break; // Sai do loop para exibir a mensagem final
        }

        int steps = getInputSteps(scanner); // Obter o número de passos

        // Processar o turno do jogo (movimento e verificação de estado)
        processGameTurn(direction, steps);

        // Se o jogo já acabou, não processar mais turnos
        if (gameOver || winGame) {
            continue; // Apenas continuar esperando por "quit"
        }
    }

    // Exibir a mensagem final após o loop terminar
    if (gameOver) {
        System.out.println("Goodbye: You lost the game!");
    } else if (winGame) {
        System.out.println("Goodbye: You won the game!");
    } else {
        System.out.println("The game was not over yet!");
    }
}

// Method to handle user input for direction and handle invalid commands
String getInputDirection(Scanner scanner) {
    String direction = "";

    // Continuar pedindo um comando até que um válido seja dado
    while (!quitGame && !direction.equals(MOVE_RIGHT) && !direction.equals(MOVE_LEFT) && !direction.equals(QUIT)) {
        if (!direction.equals("") && !gameOver && !winGame) {
            System.out.println("Invalid command");
        }
        direction = scanner.next(); // Ler o comando de direção
        shouldContinue(direction); // Verificar se o jogador digitou "quit"
    }

    return direction;
}

// Method to handle user input for steps
int getInputSteps(Scanner scanner) {
    return scanner.nextInt(); // Read the steps input
}

// Method to process game logic based on the direction and steps given
// Método para processar a lógica do jogo com base na direção e no número de passos dados
void processGameTurn(String direction, int steps) {
    // Mover o jogador
    movePlayer(direction, steps);

    // Verificar se há tesouro
    checkForTreasure();

    // Mover inimigos
    moveEnemies();

    // Verificar se o jogador está nas escadas
    checkForStairs();

    // Verificar se o jogador colidiu com um inimigo
    checkForEnemyCollision();

    // Se o jogador perdeu, sinalizar e interromper o processamento
    if (gameOver) {
        if (!gameLostMessageDisplayed) {
            gameLostMessageDisplayed = true;
            System.out.println("You lost the game!"); // Exibir mensagem apenas uma vez

        }
        return; // Parar aqui para não exibir mais informações após a derrota
    }

    // Verificar se o jogador venceu
    if (checkWin()) {
        winGame = true;
        System.out.println("You won the game!");
    }

    // Exibir as informações do jogo, apenas se o jogador não perdeu
    displayGameInformation();
}

void main() {
    Scanner scanner = new Scanner(System.in);
    inItState();

    dungeon[1] = readLevel(scanner);
    dungeon[0] = readLevel(scanner);

    enemyPositions =  new char [NUMBER_OF_LEVELS][];
    for (int i = 0; i < dungeon.length; i++) {
        for (int j = 0; j< dungeon[i].length;j++)
            enemyPositions[i] = dungeon[i];
    }

    findPositions();
    totalTreasures = countTotalTreasures();

    playGame(scanner);

    scanner.close();
}



//Move display information after game check

/* S.T..L.E
P.L...T.S
right 2

 */
Editor is loading...
Leave a Comment