### Start New Game Session - Java Source: https://context7.com/stastnypremysl/mines3d/llms.txt Initiates a new game session in Mines3D from MainActivity. It sets up the game's difficulty, grid size, and mine count, then launches the GameActivity. State management is handled via the static LoadedGame class to preserve data across Activity lifecycles. ```java Intent myIntent = new Intent(activity, GameActivity.class); // Create game status tracking LoadedGame.gameStatus = new GameStatus(LoadedGame.mainActivity); boolean hardcore = LoadedGame.gameStatus.getHardcore(); // from settings int numLevels = LoadedGame.gameStatus.getNumLevels(); // typically 2 int gridSize = 10; int baseMines = 25; // Calculate actual mine count (1.5x for hardcore, scaled by levels) int mines = (int) (baseMines * (hardcore ? 1.5f : 1) * numLevels / 2); assert mines < numLevels * gridSize * gridSize; // Create the game container LoadedGame.minesContainer = new MinesContainer(gridSize, gridSize, numLevels, mines); // Start game activity startActivity(myIntent); ``` -------------------------------- ### Game View Integration with Gesture Detection (Java) Source: https://context7.com/stastnypremysl/mines3d/llms.txt This Java code illustrates the integration of the main game view (MinesView) within an Android Activity (GameActivity). It covers view initialization, setup of drawable components, and the implementation of gesture detection for long presses and double taps. The code also includes a refresh loop for maintaining a 60 FPS frame rate. Key components include AppCompatActivity, GestureDetector, Handler, and custom drawables. ```java // MinesView is the main game view in GameActivity // Defined in activity_game.xml layout public class GameActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // MinesView automatically initializes from LoadedGame } } // In MinesView constructor (simplified): GameStatus gameStatus = LoadedGame.gameStatus; MinesContainer minesContainer = LoadedGame.minesContainer; // Create drawable components Grid grid = new Grid(minesContainer, gameStatus); SwitchButton switchButton = new SwitchButton(gameStatus); StatusLabel statusLabel = new StatusLabel(context, minesContainer, gameStatus); // Setup gesture detection GestureDetector detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent e) { for (IDrawable drawable : drawables) { drawable.sendLongTap((int)e.getX(), (int)e.getY()); } } @Override public boolean onDoubleTap(MotionEvent e) { for (IDrawable drawable : drawables) { drawable.sendDoubleTap((int)e.getX(), (int)e.getY()); } return true; } }); // 60 FPS refresh loop Handler handler = new Handler(); Runnable refresh = () -> { postInvalidate(); handler.postDelayed(refresh, 17); // ~60 FPS }; handler.postDelayed(refresh, 17); ``` -------------------------------- ### Java: Manipulate Mine State and Listen for Changes Source: https://context7.com/stastnypremysl/mines3d/llms.txt This snippet demonstrates how to interact with individual mine objects within the Mines3D game. It covers retrieving a mine, registering listeners for state changes (like opening, blocking, or unblocking a mine), and manually updating a mine's status. It also shows how to query the current state of a mine, check if it's a real mine, and get the count of adjacent mines. ```java Mine mine = container.getMine(0, 5, 5); mine.addMineStatusChangedListener(new MineStatusChangedListener() { @Override public void onOpen(GameStatus status, Mine mine) { if (mine.getIsReal()) { status.endGame(false); // player loses } else { // increment opened count } } @Override public void onBlock(GameStatus status, Mine mine) { // Player marked this cell as containing a mine if (mine.getIsReal()) { // Correctly identified mine } } @Override public void onUnblock(GameStatus status, Mine mine) { // Player removed mine marker } }); GameStatus status = LoadedGame.gameStatus; mine.setGameStatus(MineStatus.OPENED, status); // reveal cell mine.setGameStatus(MineStatus.BLOCKED, status); // mark as mine mine.setGameStatus(MineStatus.UNBLOCKED, status); // unmark MineStatus current = mine.getStatus(); // OPENED, BLOCKED, or UNBLOCKED boolean isRealMine = mine.getIsReal(); int neighbors = mine.getNeighbors(); // adjacent mine count ``` -------------------------------- ### Mine Container Initialization and Management - Java Source: https://context7.com/stastnypremysl/mines3d/llms.txt Demonstrates the creation and manipulation of the 3D mine grid using the MinesContainer class. It covers initializing the grid, accessing individual mines, checking for actual mines, retrieving dimensions, and tracking game progress. The setFactorized() method is crucial for computing neighbor relationships. ```java // Create a 10x10x2 grid with 25 mines MinesContainer container = new MinesContainer(10, 10, 2, 25); // Access individual mines Mine mine = container.getMine(z, y, x); // z=level, y=row, x=column // Check if a position contains a real mine boolean isReal = container.isRealMine(z, y, x); // Get container dimensions int height = container.getHeight(); // 10 int width = container.getWidth(); // 10 int levels = container.getNumLevels(); // 2 // Track game progress int totalMines = container.getMinesNumber(); // 25 int blocked = container.getMinesBlocked(); // mines marked by player int correctBlocks = container.getOkBlockedMines(); // correctly marked mines int opened = container.getMinesOpened(); // cells revealed // Finalize after generation - computes all neighbor relationships container.setFactorized(); boolean ready = container.getFactorized(); // true ``` -------------------------------- ### Java: Manage Game Lifecycle and Player Settings Source: https://context7.com/stastnypremysl/mines3d/llms.txt This section details the management of the game's overall state and player preferences. It includes initializing the game status, accessing and modifying player settings like difficulty and display options, navigating between game levels, and registering callbacks for level switches and game end events. It also demonstrates how to programmatically end the game (win or lose) and check if the game is still in progress. ```java GameStatus status = new GameStatus(activity); int numLevels = status.getNumLevels(); // 2 (default) boolean hardcore = status.getHardcore(); // false (default) boolean numberType = status.getNumberType(); // use numeric display boolean colored = status.getColored(); // color-code neighbor counts boolean flood = status.getFlood(); // auto-reveal adjacent empty cells int currentLevel = status.getLevel(); // 0-based index status.incrementLevel(); // cycle to next level status.decrementLevel(); // cycle to previous level int lastLevel = status.getLastLevel(); // before last switch status.addLevelSwitchListener(new LevelSwitchListener() { @Override public void levelSwitched(GameStatus status) { // Update UI for new level int newLevel = status.getLevel(); } }); status.addGameEndedListener(new GameEndedListener() { @Override public void gameEnded(GameStatus status) { boolean won = status.hasUserWon(); Date startTime = status.getStartTime(); Date endTime = status.getEndTime(); double seconds = (endTime.getTime() - startTime.getTime()) / 1000.0; } }); status.endGame(true); // player wins status.endGame(false); // player loses boolean playing = status.stillPlaying(); // false after endGame() ``` -------------------------------- ### Java: Render Game Grid and Handle Touch Input Source: https://context7.com/stastnypremysl/mines3d/llms.txt This code illustrates the implementation of the visual game board in Mines3D. It covers the creation of a grid object, setting its position and dimensions on the screen, and drawing the grid to a canvas. It also details how to process user touch events, including single taps, long presses (to mark/unmark mines), and double taps (to reveal cells). The auto-flood feature for revealing adjacent empty cells is also mentioned. ```java Grid grid = new Grid(minesContainer, gameStatus); int x = 50, y = 150, width = 800, height = 800; grid.setPosition(x, width, y, height); Canvas canvas = ...; // Android canvas grid.draw(canvas); // draws grid lines and current level's mine fields int touchX = 250, touchY = 300; grid.sendVerifiedTap(touchX, touchY); // single tap (unused) grid.sendVerifiedLongTap(touchX, touchY); // long press - mark/unmark mine grid.sendVerifiedDoubleTap(touchX, touchY); // double tap - reveal cell Vector floodTargets = mine.getAllNeighborCoords(); grid.autoFlood(floodTargets); // recursively reveals if flood enabled ``` -------------------------------- ### Procedural Mine Generation - Java Source: https://context7.com/stastnypremysl/mines3d/llms.txt Illustrates the use of RandomMinesGenerator to populate the game grid with mines procedurally, ensuring the first clicked cell is always safe. It handles exception scenarios and details how mine neighbor counts and coordinates are accessible after generation. ```java // Generator ensures first clicked cell is never a mine RandomMinesGenerator generator = new RandomMinesGenerator(); MinesContainer container = new MinesContainer(10, 10, 2, 25); // Generate mines, excluding position [level=0, y=5, x=5] int clickedLevel = 0; int clickedY = 5; int clickedX = 5; try { generator.populateNewProblem(container, clickedLevel, clickedY, clickedX); // Mines are randomly distributed, avoiding the clicked position // Container is automatically factorized with neighbor counts computed } catch (MyHappyException ex) { ex.printStackTrace(); System.exit(1); } // After generation, each mine knows its neighbors Mine mine = container.getMine(0, 3, 4); int neighborMines = mine.getNeighbors(); // count of adjacent mines Vector allNeighbors = mine.getAllNeighborCoords(); // all adjacent positions ``` -------------------------------- ### Render Mine Field Cell with Animations (Java) Source: https://context7.com/stastnypremysl/mines3d/llms.txt This Java code snippet demonstrates how to create, position, and render an individual mine cell (MineField) on a canvas. It includes details on different cell states (UNBLOCKED, BLOCKED, OPENED) and how animations are handled when switching levels by setting a previous MineField state. Input parameters include grid, mine data, game status, and level. Outputs include visual rendering on a canvas and animation transitions. ```java Grid grid = ...; Mine mineData = container.getMine(0, 5, 5); GameStatus status = LoadedGame.gameStatus; int level = 0; MineField field = new MineField(grid, mineData, status, level); // Position the field within grid cell int cellX = 100, cellY = 200, cellWidth = 80, cellHeight = 80; field.setPosition(cellX, cellWidth, cellY, cellHeight); // Render the field (shows state visually) Canvas canvas = ...; field.draw(canvas); // - UNBLOCKED: X shape in white // - BLOCKED: X shape + vertical bars (flag marker) // - OPENED: horizontal lines + neighbor count indicator // * Numbers shown as vertical bars or roman-numeral style // * Color-coded if colored setting enabled (1=red, 2=blue, etc.) // Handle interactions field.sendLongTap(cellX + 40, cellY + 40); // toggle block/unblock field.sendDoubleTap(cellX + 40, cellY + 40); // open cell // Animation system (100ms transitions) // When switching levels, fields animate from previous level's state field.setPreviousMineField(previousLevelField); // Animations trigger automatically via level switch listeners ``` -------------------------------- ### Register Game End Listener and Handle Statistics in Java Source: https://context7.com/stastnypremysl/mines3d/llms.txt This Java snippet demonstrates how to register a listener for game end events. It calculates game statistics such as correctly blocked mines, total blocked mines, opened cells, and play time. It also handles checking and saving high scores based on game difficulty and time, then displays a results dialog to the user. The listener is typically registered in the main game view. ```java gameStatus.addGameEndedListener(new GameEndedListener() { @Override public void gameEnded(GameStatus status) { // Build statistics message int okBlocked = minesContainer.getOkBlockedMines(); int totalBlocked = minesContainer.getMinesBlocked(); int opened = minesContainer.getMinesOpened(); int totalMines = minesContainer.getMinesNumber(); double playTime = (status.getEndTime().getTime() - status.getStartTime().getTime()) / 1000.0; // Save and check high score String prefName = String.format("cos.premy.mines.%d.%d.%d.%d", minesContainer.getHeight(), minesContainer.getWidth(), gameStatus.getNumLevels(), minesContainer.getMinesNumber()); SharedPreferences prefs = activity.getSharedPreferences( prefName, Context.MODE_PRIVATE); float bestTime = prefs.getFloat("lowestTime", -1); boolean newRecord = status.hasUserWon() && (bestTime == -1 || bestTime > playTime); if (newRecord) { prefs.edit().putFloat("lowestTime", (float)playTime).apply(); } // Display results dialog AlertDialog.Builder alert = new AlertDialog.Builder(activity); String message = status.hasUserWon() ? "You have won!" : "You have lost!"; message += String.format("\nCorrectly marked: %d/%d\n" + "Total marked: %d\nCells opened: %d\nTime: %.1fs", okBlocked, totalMines, totalBlocked, opened, playTime); if (newRecord) message += "\nNew record!"; else if (bestTime != -1) message += String.format( "\nBest time: %.1fs", bestTime); alert.setTitle("Game Over"); alert.setMessage(message); alert.create().show(); activity.finish(); } }); // Winning condition: all and only real mines are blocked // Triggered in MinesContainer's block/unblock listeners: // if (minesOkBlocked == minesBlocked && minesOkBlocked == minesNumber) { // status.endGame(true); // } // Losing condition: opening a real mine // if (mine.getIsReal()) { // status.endGame(false); // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.