Для моей игры с палачом я хотел бы иметь кучу сообщений об ошибках, чтобы проверять такие вещи, как ввод более одной буквы, угадывание одной и той же буквы дважды и т. д. Мой полный код на данный момент:
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;
public class MainFrame extends javax.swing.JFrame {
public MainFrame() {
initComponents();
}
//declare variables
static String secretWord = "";
double result = 0;
StringBuilder mainWord = new StringBuilder();
StringBuilder xletters = new StringBuilder(); // letters guessed
String[] words = {"technology", "computer", "camera", "graphic", "digital", "media", "technician",
"photography", "troubleshoot", "pixels", "application", "download"};
Random r = new Random();
int randValue = r.nextInt(12);
String guessWord = words[randValue];
int errors = 0;
public static int wins = 0, losses = 0;
String foundWord = null;
private void GuessButtonActionPerformed(java.awt.event.ActionEvent evt) {
String strGuess = GuessText.getText(); //user input
String letter = strGuess;
xletters.append(strGuess.toUpperCase());
String GuessedLetters = xletters.toString();
try {
//replace underscores with letters as they are guessed
do {
for (int i = 0; i < 1; i++) {
secretWord = secretWord + letter.charAt(0);
foundWord = words[randValue].replaceAll("[^" + secretWord + "]", "_ ");
//if user entered more than one letter
if (strGuess.length() > 1) {
JOptionPane.showMessageDialog(null, "Only one letter at a time!");
xletters.append("");
GuessedLetters = null;
GuessText.setText(null);
GuessText.requestFocusInWindow();
} //if letter isn't in word
else if (guessWord.indexOf(strGuess) == -1) {
JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word.");
errors++;
if (errors == 1) {
Hangman0.setVisible(false);
}
if (errors == 2) {
Hangman1.setVisible(false);
}
if (errors == 3) {
Hangman2.setVisible(false);
}
if (errors == 4) {
Hangman3.setVisible(false);
}
if (errors == 5) {
Hangman4.setVisible(false);
}
if (errors == 6) {
Hangman5.setVisible(false);
}
if (errors == 7) {
Hangman6.setVisible(false);
}
if (errors == 8) {
Hangman7.setVisible(false);
}
if (errors == 9) {
Hangman8.setVisible(false);
}
if (errors == 10) {
Hangman9.setVisible(false);
JOptionPane.showMessageDialog(null, "You lost! The word was: " + guessWord);
losses++;
DirectionsFrame DFrame = new DirectionsFrame();
DFrame.setVisible(true);
setVisible(false);
MainFrame MFrame = new MainFrame();
MFrame.dispose();
xletters.delete(0, 100);
secretWord = "";
foundWord = null;
strGuess = null;
String strLosses = Integer.toString(losses);
String strWin = Integer.toString(wins);
DirectionsFrame.WinsLabel.setText(strWin);
DirectionsFrame.LossesLabel.setText(strLosses);
}
}
}
WordLabel.setText(foundWord.toUpperCase());
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
} while (foundWord == null);
if (foundWord.equalsIgnoreCase(guessWord)) {
JOptionPane.showMessageDialog(null, "Yay!");
wins++;
DirectionsFrame DFrame = new DirectionsFrame();
DFrame.setVisible(true);
setVisible(false);
MainFrame MFrame = new MainFrame();
MFrame.dispose();
xletters.delete(0, 100);
secretWord = "";
foundWord = null;
String strWin = Integer.toString(wins);
String strLosses = Integer.toString(losses);
DirectionsFrame.WinsLabel.setText(strWin);
DirectionsFrame.LossesLabel.setText(strLosses);
}
} catch (StringIndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(null, "Please enter a letter.");
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
}
}
private void GetButtonActionPerformed(java.awt.event.ActionEvent evt) {
//print out underscores to begin game
for (int i = 0; i < guessWord.length(); i++) {
mainWord.append("_ ");
}
String SetMain = mainWord.toString();
mainWord.append(secretWord);
WordLabel.setText(SetMain);
GuessButton.setEnabled(true);
GetButton.setEnabled(false);
}
Больше всего у меня возникают проблемы с проверкой того, дважды ли пользователь ввел одну и ту же букву. Таким образом, вы можете только один раз угадать одну букву в алфавите. Кроме того, я считаю, что код, в котором он проверяет, ввел ли пользователь более одной буквы, имеет ошибку, потому что там, где я хочу, чтобы он не добавлял эти буквы в поле угаданных букв, он все равно добавляется. (т.е. пользователь угадывает "hf" и в угаданных буквах идет "hf", где должно быть просто ничего)
Я чувствую, что ответ лежит в методе indexOf(), но я не совсем уверен в том, что скажет условие if...
Я использую Netbeans IDE 7.2 для компиляции своего кода. Пожалуйста помоги! Спасибо.
Hangman0
...Hangman9
можно заменить наHangman[errors]
. Просто мысль. - person Yanick Rochon   schedule 11.11.2012A
доZ
, и позволить пользователю нажимать их (button.setEnabled(false);
) вместо использования текстового поля? - person Yanick Rochon   schedule 11.11.2012actionPerformed
вы можете получить, какая кнопка была нажата, используяevt.getActionComment()
(пример: который верните строку A, если эта кнопка нажата), и вы сможете получить данныйJButton
с помощью(JButton) evt.getSource()
- person Yanick Rochon   schedule 11.11.2012