FP - Projeto "Campo DEISIado" (parte 2)
Fundamentos da Programação: Parte Dois
Introdução ao Projeto
- O vídeo apresenta a continuação do projeto "Fundamentos da Programação", focando na parte dois do campo designado.
- A interface inicial do jogo permanece inalterada, incluindo o menu e as validações.
Estrutura do Jogo
- As linhas são numeradas de 1 a n e as colunas são representadas por letras começando em A. O jogador é indicado por um 'J' e o objetivo final por um 'F'.
- O jogador deve evitar minas escondidas enquanto se dirige para a célula marcada como 'F'. Se ele entrar em uma célula com mina, perde imediatamente.
Movimentação e Comandos
- O movimento é feito através de uma string que indica primeiro o número da linha e depois a letra da coluna. Internamente, utiliza-se uma matriz bidimensional começando em zero.
- Um comando especial chamado "abracadabra" revela todas as minas e números no tabuleiro, mas não deve ser usado durante o jogo normal.
Interpretação dos Números
- Os números ao redor das células indicam quantas minas estão adjacentes. Eles aparecem apenas nas células sem minas.
- Por exemplo, um número '2' significa que há duas minas nas células vizinhas. Isso ajuda os jogadores a planejar seus movimentos.
Estratégia de Jogo
- Durante o jogo, apenas os números adjacentes ao jogador são visíveis. Isso limita a informação disponível para tomar decisões estratégicas.
- Jogadores devem avaliar cuidadosamente suas opções antes de saltar para novas posições, pois algumas podem conter minas ocultas.
Conclusão do Jogo
- Ao perder ou ganhar, o jogo revela todas as informações sobre as minas e números no tabuleiro, permitindo que os jogadores entendam suas falhas ou sucessos.
- Após uma partida, os jogadores retornam ao menu inicial para iniciar um novo jogo com um terreno gerado aleatoriamente.
Understanding Game Strategy in Minesweeper
Identifying Mines and Making Strategic Moves
- The player identifies three mines surrounding a specific area, concluding their locations based on the game's rules. This deduction is made without needing to see additional numbers.
- When jumping to a numbered box, the player notes that they will not see any new numbers in the next turn, emphasizing the importance of risk management in gameplay.
- The player discusses the strategy of avoiding always jumping to numbered boxes, as it would make winning too easy. They must decide whether to take risks or play conservatively.
- After making a calculated jump to a non-numbered box (B), the player successfully avoids mines and regains visibility of surrounding numbers, illustrating how risk can lead to advantageous outcomes.
- The player reflects on their knowledge of mine locations while considering further moves. They weigh options between safety and advancing towards their goal (F).
Risk Assessment and Decision-Making
- Taking another risk by jumping to an unknown location (D), the player finds success again, which reinforces their understanding of game dynamics where taking risks can yield positive results.
- Upon landing on D, new numbers appear around them. However, uncertainty remains about exact mine placements due to limited information from adjacent boxes.
- The player contemplates potential empty spaces among identified mines but decides against unnecessary risks at this stage in favor of safer moves toward F.
- With a small board size allowing for more straightforward navigation, the player confidently jumps directly towards F without concern for remaining mines.
Game Mechanics and Validations
- The mechanics allow for diagonal movements within two spaces horizontally or vertically. This flexibility aids strategic positioning during gameplay.
- The discussion shifts towards validating user inputs within the game interface. Invalid responses prompt re-entry until correct answers are provided.
- Examples of invalid movements are given; players cannot exceed two spaces or move outside designated boundaries on the board.
- Players are encouraged to think creatively about what constitutes an invalid move as part of mastering game rules and enhancing overall experience.
Saving and Loading Game States
- A command allows players to exit the game at any time if they wish to stop playing, providing flexibility in gameplay engagement.
- Instructions are provided for loading pre-created game files containing mine configurations rather than saving mid-game states—this simplifies file management for users.
- When loading a file with predefined settings (e.g., terrain), players must ensure compatibility with existing formats; otherwise, errors may occur during setup.
Game Development Insights
File Management and Game Initialization
- The game utilizes an altered CXT file, where users should place the terrain TXT or any preferred filename. The game starts without a legend, mimicking the behavior of a new game.
- Emphasis on code reuse between new game and load game functionalities; only the file loading process differs. The terrain inherently contains mine information, eliminating the need to ask for mine counts during loading.
- Demonstration of handling invalid files: if an invalid terrain is loaded, the game does not exit but returns to the menu for retrying options like starting a new game or loading again.
Functionality Overview
- All functions from part one are retained in part two, except for
createTerrain, which will be modified later.
- Internal representation of terrain is crucial; it must be stored in a two-dimensional array that tracks what exists at each position (e.g., J for player, F for flag).
Visibility and Information Display
- The application decides what information to display based on internal data; visibility is determined by whether elements should be shown or hidden.
- An example illustrates how empty spaces are represented with actual spaces in the array. Each entry consists of a string (representing content) and a boolean indicating visibility.
Game Mechanics and Player Movement
- Initially, all mines are visible when starting; however, as gameplay progresses, only adjacent numbers around the player are displayed while other elements remain hidden.
- When moving the player (J), changes occur in both current and destination positions within the array—updating values accordingly to reflect movement.
Coordinate Handling
- Moving players involves translating coordinates into array indices; this requires careful mapping from user input to internal matrix references.
- The function
getCoordinatestranslates user inputs into pairs representing row and column indices starting from zero. It ensures case insensitivity for letter inputs.
Coordinate Validation and Movement Logic
Validating Coordinates
- The system should accept both lowercase and uppercase inputs for coordinates, treating them equivalently.
- If invalid coordinates are entered, the function
obtemCoordenadasmust return null instead of printing an error message. This allows the caller to handle the output appropriately.
Terrain Boundaries
- It's essential to validate whether the provided coordinates fall within the defined terrain boundaries before proceeding with any operations.
- For a 3x3 terrain, valid coordinate ranges are from (0,0) to (2,2). Any input outside this range is considered invalid.
Movement Validity
- Even if coordinates are valid in terms of being within bounds, they must also represent a legitimate movement according to game rules.
- Players can move one or two spaces in any direction; however, certain jumps (e.g., from (0,0) to (0,4)) are not allowed.
Calculating Surrounding Squares
Defining Square Areas
- A function is needed to determine the square area around a given point based on its row and column indices along with terrain dimensions.
- The function returns two sets of coordinates: one for the upper-left corner and another for the lower-right corner of the square.
Handling Edge Cases
- Care must be taken when dealing with squares near terrain edges to avoid negative indices or out-of-bounds errors.
Counting Adjacent Mines
Mine Counting Functionality
- A new function will count how many mines surround a specified position on the terrain matrix.
- The counting process involves checking adjacent cells; only those directly next to the specified cell will be counted as adjacent mines.
Utilizing Previous Functions
- To efficiently count mines around a point, first obtain its surrounding square using previously defined functions. This helps streamline mine counting by limiting checks to relevant areas.
Generating Terrain Matrix
Creating Game Terrain
- The
geramatrizTerrenofunction generates a game board that includes mines and player positions based on user-defined parameters such as rows and columns.
Random Mine Placement
- Mines need to be placed randomly across the generated board. This randomness adds unpredictability and challenge to gameplay.
Generating Random Terrain in a Game
Functionality of Random Terrain Generation
- The function generates a random terrain each time it is called, creating different layouts with four rows and three columns, while ensuring six mines are placed randomly.
- Validation checks confirm that exactly six mines are generated and distributed randomly across the terrain. The function should not produce the same arrangement upon multiple calls.
- The parameters for visibility (J and F) must always be set to true, while all other elements should default to false until later functions handle their visibility.
Mine Placement Logic
- Care must be taken to avoid placing a mine on top of another; a loop should continue generating random positions until six unique mine placements are achieved.
- The function modifies the array directly without returning any value, filling it with mines based on previously defined logic.
Revealing Numbers Around Mines
- A separate function reveals numbers around selected coordinates but never exposes the mines themselves. It changes the visibility status from false to true for surrounding numbers.
- If a player selects an empty cell, they will see surrounding numbers in subsequent turns; this requires careful tracking of visible states.
Validating Cell States
- Functions need to check if a cell contains a visible number before revealing its state. This ensures players only see relevant information based on their actions.
- An additional function hides all matrix elements except for J and F by setting everything else to false, maintaining game integrity.
Creating Visual Representation of Terrain
- The final function creates a visual representation of the terrain as a string format rather than just an array. This output can then be printed or displayed in-game.
Game Development Insights
Overview of Game Functionality
- The game undergoes multiple phases before being presented to the player, including terrain generation and mine placement.
- A function is introduced that accepts a two-dimensional array along with optional parameters for displaying legends and revealing all elements.
- Examples are provided to illustrate different configurations of the display options, highlighting when to use them during gameplay.
Display Options Explained
- The
cria terrenofunction does not perform any printing; it returns a string instead. Printing occurs externally after this function call.
- An optional function allows for creating a fully functional game without requiring file reading capabilities, although implementing this part is encouraged for better grades.
File Reading Mechanics
- The file reading function validates the number of rows and columns in the terrain file against expected values, returning a matrix if successful.
- The required format for the terrain file is specified: it must be a TXT file created with Notepad or Intel G, containing rows separated by commas.
Validation Criteria
- Each row should have six columns (five commas), with specific characters representing spaces and mines. Any discrepancies lead to errors in validation.
- Examples illustrate invalid scenarios such as mismatched row counts or duplicate entries (e.g., two 'J's), which would result in null returns.
Integrating Game Components
- Discussion on how to cohesively integrate various functions into a working game structure, emphasizing clarity and coherence in gameplay mechanics.