You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java保险箱破解游戏开发求助:类与方法实现遇阻

Let's Build Your Java Safe Cracker Game Properly

Hey there! I see you're working on a safe cracker game in Java and hit a roadblock with the class/method structure. Let's start by looking at your existing code, then fix up the structure and add the missing game logic to get you moving forward.

Your Current Code

import java.util.Random;
import java.util.Scanner;
public class Main {
 public static void main(String[] args) {
 entrance();
 playGame();
 quitGame();
 }
 private static void entrance() {
 System.out.println("Welcome to the SafeCracker!\nI...");
 }
}

The Bottleneck You're Facing

Right now, you've got a basic entrance method, but playGame() and quitGame() are unimplemented, and everything relies on static methods instead of using classes to encapsulate game state. For a game like this, we need to track things like the secret code, remaining attempts, and player input—all of which are perfect to wrap in a dedicated game class to follow OOP principles.

Let's Refactor with Proper Class Structure

Let's create a SafeCrackerGame class to hold all game-related logic and state. Here's how to build it step by step:

  1. Encapsulate Game State: Add private fields for the secret code, max attempts, remaining attempts, and input/random utilities.
  2. Initialize the Game: Use a constructor to set up the secret code and attempt limits when the game starts.
  3. Core Game Methods: Build modular methods to handle player input, check guesses, and run the main game loop.
  4. Connect to Main: Update your Main class to create an instance of the game and run its methods.

Full Working Example

import java.util.Random;
import java.util.Scanner;

// Dedicated game class to encapsulate state and logic
class SafeCrackerGame {
    private int secretCode;
    private int maxAttempts;
    private int attemptsLeft;
    private Scanner scanner;
    private Random random;

    // Constructor to initialize game settings (code length + max attempts)
    public SafeCrackerGame(int codeLength, int maxAttempts) {
        this.maxAttempts = maxAttempts;
        this.attemptsLeft = maxAttempts;
        this.scanner = new Scanner(System.in);
        this.random = new Random();
        // Generate a secret code with the specified digit length
        int min = (int) Math.pow(10, codeLength - 1);
        int max = (int) Math.pow(10, codeLength) - 1;
        this.secretCode = random.nextInt(max - min + 1) + min;
    }

    // Display welcome message with game rules
    public void showEntrance() {
        System.out.println("Welcome to the SafeCracker!");
        System.out.printf("I've generated a %d-digit secret code. You have %d attempts to crack it.\n",
                String.valueOf(secretCode).length(), maxAttempts);
    }

    // Get valid player guess (handles non-numeric/wrong-length input)
    private int getPlayerGuess() {
        int guess = -1;
        while (true) {
            System.out.print("Enter your guess: ");
            if (scanner.hasNextInt()) {
                guess = scanner.nextInt();
                // Validate guess has the correct number of digits
                if (String.valueOf(guess).length() == String.valueOf(secretCode).length()) {
                    break;
                } else {
                    System.out.printf("Oops! Please enter a %d-digit number.\n", String.valueOf(secretCode).length());
                }
            } else {
                System.out.println("Invalid input! Please enter a number.");
                scanner.next(); // Clear invalid input from the scanner
            }
        }
        return guess;
    }

    // Check if guess matches secret code, give hints, and track attempts
    private boolean checkGuess(int guess) {
        attemptsLeft--;
        if (guess == secretCode) {
            System.out.println("Congratulations! You cracked the safe! 🎉");
            return false; // End game loop
        } else {
            // Give simple hint (higher/lower)
            String hint = guess > secretCode ? "Too high!" : "Too low!";
            System.out.printf("%s You have %d attempts left.\n", hint, attemptsLeft);
            return attemptsLeft > 0; // Keep playing if there are attempts left
        }
    }

    // Main game loop
    public void play() {
        boolean keepPlaying = true;
        while (keepPlaying) {
            int guess = getPlayerGuess();
            keepPlaying = checkGuess(guess);
        }
        if (attemptsLeft == 0) {
            System.out.printf("Game over! The secret code was %d.\n", secretCode);
        }
    }

    // Clean up resources and show exit message
    public void quit() {
        scanner.close();
        System.out.println("Thanks for playing SafeCracker! Goodbye!");
    }
}

public class Main {
    public static void main(String[] args) {
        // Create game instance (4-digit code, 5 attempts)
        SafeCrackerGame game = new SafeCrackerGame(4, 5);
        game.showEntrance();
        game.play();
        game.quit();
    }
}

Key Improvements Explained

  • OOP Structure: The SafeCrackerGame class centralizes all game state and logic, making the code organized and easy to extend (you could add difficulty levels or advanced hints later!).
  • Encapsulation: Private fields ensure game state can only be modified through controlled methods, avoiding accidental bugs.
  • Modular Methods: Each method handles one specific task (getting input, checking guesses, running the loop), which makes debugging and updating code simpler.
  • Error Handling: We validate player input to prevent crashes from non-numeric or wrong-length guesses.

This structure should get you past your bottleneck—feel free to tweak the code (like adjusting code length or attempt limits) to fit your vision for the game!

内容的提问来源于stack exchange,提问作者Eren Arican

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:39:19