Java记忆游戏:全部卡牌翻转后显示GameOver界面的实现方法
Hey there! Let's walk through exactly how to get that game over screen showing once all cards are flipped. I'll assume you're using Swing for your GUI (super common for small Java games), but the core logic translates to other frameworks too.
Step 1: Track Flipped Cards
First, you need a way to keep count of how many cards have been successfully flipped (adjust this to match your game's rules—whether it's just flipped, or flipped and matched). Add a class-level variable to track this:
// At the top of your game class, alongside other variables private int flippedCardsCount = 0; private final int TOTAL_CARDS = 16; // Adjust this to your game's total card count
Every time a player flips a card (and completes the required action, like a match), increment this count and check if we've hit the total:
// Inside your card flip/match handler method flippedCardsCount++; // Trigger game over once all cards are processed if (flippedCardsCount == TOTAL_CARDS) { gameOver(); }
Step 2: Implement the gameOver() Method
Now let's build out the method to load and display your game over image. We'll use Swing components to replace the game content with the image:
public void gameOver() { // 1. Load the game over image from the sprites folder ImageIcon gameOverImage = null; try { // Ensure the path matches your project structure—"sprites" should be accessible gameOverImage = new ImageIcon("sprites/game_over.jpg"); // Optional: Resize the image to fit your game window perfectly Image scaledImage = gameOverImage.getImage().getScaledInstance( getWidth(), getHeight(), Image.SCALE_SMOOTH ); gameOverImage = new ImageIcon(scaledImage); } catch (Exception e) { // Handle image loading failures gracefully System.err.println("Couldn't load game over image: " + e.getMessage()); return; } // 2. Create a label to display the image JLabel gameOverLabel = new JLabel(gameOverImage); gameOverLabel.setHorizontalAlignment(JLabel.CENTER); gameOverLabel.setVerticalAlignment(JLabel.CENTER); // 3. Replace the game's current content with the game over screen // Assuming your game uses a main container like a JPanel or JFrame content pane getContentPane().removeAll(); getContentPane().add(gameOverLabel, BorderLayout.CENTER); getContentPane().revalidate(); getContentPane().repaint(); }
Quick Tips to Avoid Issues
- Image Path Check: Make sure your
spritesfolder is marked as a resource folder in your IDE (IntelliJ/Eclipse) so the path resolves correctly at runtime. - Layout Adjustments: If your game uses a different layout manager than
BorderLayout, tweak how you add thegameOverLabelto fit your existing setup. - Rule Alignment: If your game requires card matches instead of just flips, only increment
flippedCardsCountwhen a successful match is confirmed.
内容的提问来源于stack exchange,提问作者Lenxos

