Untitled
unknown
java
5 months ago
15 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; boolean victoryAnnounced; void inItState() { totalTreasures = 0; treasuresCollected = 0; gameOver = false; winGame = false; currentRoom = 0; currentLevel = 0; gameLostMessageDisplayed = false; quitGame = false; boolean victoryAnnounced = 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++; // Incrementa a contagem de tesouros coletados dungeon[currentLevel][currentRoom] = EMPTY_ROOM_SYMBOL; // Limpa o tesouro da sala } } // 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) { int i = 0; // Índice de linha int j = 0; // Índice de coluna // Itera enquanto houver linhas na masmorra do { // Enquanto houver colunas na linha atual while (j < dungeon[i].length) { if (enemyPositions[i][j] == LOOPER_ROOM_SYMBOL) { enemyPositionsBuffer[i][j] = EMPTY_ROOM_SYMBOL; // Limpa a sala atual // Verifica se a nova posição (j + 1) ultrapassa o comprimento do nível 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 } } j++; // Move para a próxima coluna } j = 0; // Reseta j para a próxima linha i++; // Move para a próxima linha } while (i < dungeon.length); // Continua até percorrer todas as linhas } // Método para mover os Zigzaggers void moveZigzaggers(char[][] enemyPositionsBuffer) { int i = 0; // Índice de linha int j = 0; // Índice de coluna // Itera enquanto houver linhas na masmorra do { // Itera sobre cada coluna na linha atual while (j < dungeon[i].length) { if (enemyPositions[i][j] == ZIGZAGGER_ROOM_SYMBOL) { enemyPositionsBuffer[i][j] = EMPTY_ROOM_SYMBOL; // Limpa a sala atual // Calcula a nova posição considerando os passos do Zigzagger int newPosition = j + zigzaggerSteps; // Nova posição a partir da atual // Verifica se newPosition ultrapassa o comprimento do nível if (newPosition >= dungeon[i].length) { newPosition = newPosition - dungeon[i].length; // Corrige para a posição correta } // Mover o Zigzagger para a nova posição enemyPositionsBuffer[i][newPosition] = ZIGZAGGER_ROOM_SYMBOL; zigzaggerSteps++; if (zigzaggerSteps > 5) { zigzaggerSteps = 1; // Reseta para 1 quando chega a 5 } } j++; // Move para a próxima coluna } j = 0; // Reseta j para a próxima linha i++; // Move para a próxima linha } while (i < dungeon.length); // Continua até percorrer todas as linhas } void checkForEnemyCollision() { // Verifique se os índices estão dentro dos limites antes de acessar if (currentLevel >= 0 && currentLevel < enemyPositions.length && currentRoom >= 0 && currentRoom < enemyPositions[currentLevel].length) { char symbol = enemyPositions[currentLevel][currentRoom]; if (symbol == LOOPER_ROOM_SYMBOL || symbol == ZIGZAGGER_ROOM_SYMBOL) { gameOver = true; } } } int findStairPosition(int level) { int i = 0; // Inicia o índice em 0 do { if (dungeon[level][i] == STAIR_ROOM_SYMBOL) { return i; // Retorna a posição da escada se encontrada } i++; // Incrementa o índice } while (i < dungeon[level].length); // Continua enquanto i for menor que o comprimento do nível return -1; // Retorna -1 se não encontrar a escada } 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; } */ int findLevelEnemy(int level){ int i = 0; do{ char symbol = enemyPositions[level][i]; if(symbol == LOOPER_ROOM_SYMBOL || symbol == ZIGZAGGER_ROOM_SYMBOL) { return i; } i++; }while (i < enemyPositions[level].length); 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() { boolean foundStartingPosition = false; boolean foundEscapePosition = false; int i = 0; do { int j = 0; do { char symbol = dungeon[i][j]; if (symbol == STARTING_POSITION_SYMBOL) { currentLevel = i; currentRoom = j; foundStartingPosition = true;} if (symbol == ESCAPE_ROOM_SYMBOL) { escapePosition[0] = i; escapePosition[1] = j; foundEscapePosition = true; } if (foundStartingPosition && foundEscapePosition) { break; } j++; } while (j < dungeon[i].length); if (foundStartingPosition && foundEscapePosition) { break; } i++; } while (i < dungeon.length); } void shouldContinue(String direction) { if (direction.equals(QUIT)) { quitGame = true; // Indicar que o jogo deve encerrar } } // Main method to control the game flow // Adiciona uma variável de controle boolean lostTheGame = false; boolean winTheGame = false; void playGame(Scanner scanner) { while (!quitGame) { // Se o jogador já perdeu if (gameOver) { if(!lostTheGame) { System.out.println("You lost the game!"); lostTheGame = true;// Exibe a perda uma vez } // Aguarda um novo input String direction = getInputDirection(scanner); if (direction.equals("quit")) { quitGame = true; // Exibe a mensagem de fim de jogo break; // Encerra o loop se o jogador quiser sair } else { // Continua informando a perda se o jogador não digitar "quit" System.out.println("The game is Over!"); continue; // Volta ao início do loop } } // Solicita a direção e verifica se o jogador deseja sair String direction = getInputDirection(scanner); if (direction.equals("quit")) { quitGame = true; break; } // Solicita os passos e processa a jogada int steps = getInputSteps(scanner); processGameTurn(direction, steps); // Verifica se o jogador ganhou if (winGame) { if(!winTheGame){ System.out.println("You won the game!"); winTheGame = true; } // Exibe a vitória uma vez // Continua aguardando novo input após vencer String nextDirection = getInputDirection(scanner); if (nextDirection.equals("quit")) { quitGame = true; // Exibe a mensagem de fim de jogo break; } else { System.out.println("The Game is Over!"); continue; // Volta ao início do loop } } // Se o jogador não ganhou nem perdeu, continua exibindo as informações do jogo } // Mensagem de despedida única if (winGame) { System.out.println("Goodbye: You won the game!"); } else if (gameOver) { System.out.println("Goodbye: You lost the game!"); } else { System.out.println("The game was not over yet!"); } } // Method to handle user input for direction and handle invalid commands // Method to handle user input for steps int getInputSteps(Scanner scanner) { return scanner.nextInt(); // Read the steps input } void processGameTurn(String direction, int steps) { // Mova o jogador primeiro movePlayer(direction, steps); // Verifique se o jogo acabou devido a colisão com inimigos apenas se o movimento foi válido checkForTreasure(); // Verifica se o jogador coletou um tesouro // Agora mova os inimigos moveEnemies(); // Mover inimigos // Verifique escadas checkForStairs(); // Verifica escadas // Verifica colisão com inimigos checkForEnemyCollision(); // Verifica colisão com inimigos // Verifica se o jogador venceu if (checkWin()) { winGame = true; // Define que o jogador ganhou } if(!gameOver && !quitGame && !winGame) displayGameInformation(); } // Método para lidar com a entrada do usuário para a direção e tratar comandos inválidos String getInputDirection(Scanner scanner) { String direction = ""; 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(); // lê a direção shouldContinue(direction); // verifica se deve encerrar o jogo } return direction; // retorna a direção } void main() { Scanner scanner = new Scanner(System.in); inItState(); dungeon[1] = readLevel(scanner); dungeon[0] = readLevel(scanner); enemyPositions = new char[NUMBER_OF_LEVELS][]; // Inicializa as posições dos inimigos for (int i = 0; i < dungeon.length; i++) { enemyPositions[i] = new char[dungeon[i].length]; // Inicializa as linhas corretamente for (int j = 0; j < dungeon[i].length; j++) { enemyPositions[i][j] = dungeon[i][j]; // Copia as posições do nível } } findPositions(); totalTreasures = countTotalTreasures(); playGame(scanner); scanner.close(); } /* S.T..L.E P.L...T.S right 2 */ /* ..TT..S.Z.. L.TPSE.T jump4 left 1 right 2 */
Editor is loading...
Leave a Comment