Java猜字母游戏开发求助:替换玩家猜对的隐藏字符功能异常
Hey there! I see you're working on a Java word guess game, and the tricky part right now is getting the guessed characters to show up in the hidden spots. Let's break down what's going wrong in your current code and fix it up.
First, Let's Spot the Problems in Your Current Code
Looking at your snippet, a couple of key issues are holding you back:
- You're looping to input 10 words, but you only keep the last one (since you overwrite
wordeach time). We need to store all 10 words so we can cycle through them as the player guesses correctly. - You're not saving the original characters or the positions you hid. Without that info, when the player guesses a character, you have no way to know which '-' to replace or what character to put there.
- There's no logic for handling the second player's guesses and updating the displayed word.
Let's Build the Solution Step by Step
Here's how we can adjust your code to make the character replacement work, plus handle the full game flow:
1. Store All Game Data
We'll use lists to keep track of:
- The original words (so we know what characters should be in the hidden spots)
- The current displayed state of each word (as char arrays, since they're mutable)
- The set of hidden positions for each word (so we can check if a guess hits a hidden spot)
2. Generate Hidden Words Properly
For each input word, pick 3 unique random positions, hide them, and store all the relevant data.
3. Handle Player Guesses
For each word, let the player guess characters. When they guess correctly, replace the '-' in the displayed array with the original character. Once all hidden spots are filled, move to the next word. Keep track of wrong guesses too—if they hit 10, end the game.
Full Working Example Code
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.Set; import java.util.HashSet; public class WordGuessGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); // Lists to store game data for all 10 words List<String> originalWords = new ArrayList<>(); List<char[]> displayedWords = new ArrayList<>(); List<Set<Integer>> hiddenPositions = new ArrayList<>(); // Step 1: First player inputs 10 words System.out.println("First player: Enter 10 words one by one:"); for (int i = 0; i < 10; i++) { System.out.print("Word " + (i + 1) + ": "); String word = scanner.nextLine().trim(); originalWords.add(word); // Pick 3 unique random positions to hide Set<Integer> positions = new HashSet<>(); while (positions.size() < 3) { positions.add(random.nextInt(word.length())); } hiddenPositions.add(positions); // Create the displayed version with '-' in hidden spots char[] displayed = word.toCharArray(); for (int pos : positions) { displayed[pos] = '-'; } displayedWords.add(displayed); } // Step 2: Second player starts guessing int wrongGuesses = 0; int currentWordIndex = 0; System.out.println("\nSecond player: Start guessing! You have 10 wrong guesses allowed."); while (wrongGuesses < 10 && currentWordIndex < 10) { char[] currentDisplay = displayedWords.get(currentWordIndex); String originalWord = originalWords.get(currentWordIndex); Set<Integer> currentHidden = hiddenPositions.get(currentWordIndex); // Show current state System.out.println("\nCurrent word: " + new String(currentDisplay)); System.out.print("Guess a character: "); char guess = scanner.nextLine().toLowerCase().charAt(0); boolean guessCorrect = false; // Check if the guess matches any hidden character for (int pos : currentHidden) { if (originalWord.charAt(pos) == guess) { // Replace the '-' with the correct character currentDisplay[pos] = guess; guessCorrect = true; // Remove this position from hidden set (since it's now revealed) currentHidden.remove(pos); // Break early if we found a match break; } } if (guessCorrect) { System.out.println("Correct guess!"); // Check if all hidden characters are revealed for this word if (currentHidden.isEmpty()) { System.out.println("You solved this word! Moving to the next one."); currentWordIndex++; } } else { wrongGuesses++; System.out.println("Wrong guess! You have " + (10 - wrongGuesses) + " tries left."); } } // Game end messages if (wrongGuesses >= 10) { System.out.println("\nGame over! You used all 10 wrong guesses."); } else if (currentWordIndex >= 10) { System.out.println("\nCongratulations! You guessed all 10 words correctly!"); } scanner.close(); } }
Key Explanations
- Storing Hidden Positions: Using a
Setfor each word's hidden positions ensures we don't pick duplicate spots, and we can easily remove positions once they're guessed correctly. - Mutable Char Arrays: Using
char[]for the displayed words lets us directly modify characters when a guess is correct (unlikeStringwhich is immutable). - Game Flow Control: We track the current word index and wrong guess count to handle moving between words or ending the game when the limit is hit.
This should fix your character replacement issue and give you a complete working game framework to build on if you want to add extra features!
内容的提问来源于stack exchange,提问作者Losha

