我的刽子手游戏(Java)中的用户输入
我想创建一个刽子手游戏,可以由2名玩家玩。玩家1给出了另一个玩家需要猜的单词。玩家2得到了无限的尝试
我的问题是我需要给出整个单词而不是字母。我想在我的游戏中有一个功能,玩家2可以通过输入字母来查询单词。我知道我需要使用一个StringBuffer来让它工作,但我不知道我需要怎么做
我是Java新手,我总是喜欢学习
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Hangman {
public static void main(String[] args) {
JFrame frame = new JFrame("Hangman");
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50,50,800,600);
//OBJECTS
JButton start = new JButton("START");
start.setBounds(140,80,110,30);
frame.getContentPane().add(start);
frame.repaint();
JButton guess = new JButton("GUESS");
guess.setBounds(280,80,110,30);
frame.getContentPane().add(guess);
frame.repaint();
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String tip = JOptionPane.showInputDialog("Give a tip for the user.");
JLabel givenTip = new JLabel(tip);
givenTip.setBounds(50, 300, 300, 40);
frame.getContentPane().add(givenTip);
frame.repaint();
JButton buttons = new JButton();
String word = JOptionPane.showInputDialog("What is the word?");
for (int i = 0; i < word.length(); i++) {
buttons = new JButton("___");
buttons.setBounds(50 + (i * 80), 350, 60, 40);
frame.getContentPane().add(buttons);
frame.repaint();
}
guess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I think that I need to add this function here.
String inputUser = JOptionPane.showInputDialog("Give a letter.");
if (word.equals(inputUser)) {
JOptionPane.showMessageDialog(null,"This is right!");
JLabel won = new JLabel("You won the game!");
won.setBounds(50, 400, 110, 40);
frame.getContentPane().add(won);
JLabel restart = new JLabel("Restart the game to play again.");
restart.setBounds(50, 500, 250, 40);
frame.getContentPane().add(restart);
JButton correctInput = new JButton(inputUser);
correctInput.setBounds(210, 400, 300, 40);
frame.getContentPane().add(correctInput);
frame.repaint();
}
else
{
JOptionPane.showMessageDialog(null,"This is not right.");
}
}
});
}
});
frame.setVisible(true);
}
}
# 1 楼答案
使用
if (word.equals(inputUser)) {
只需检查输入是否是完整的单词,而不仅仅是一个字母# 2 楼答案
你可以先保留一个版本的player1的单词,但它是由下划线组成的,因此在猜测时在正确的位置添加字母更容易,也更好地由player2可视化
然后,您可以为player2添加一个按钮,以进行猜测,并在该按钮的侦听器方法中(通过方法调用)执行以下常规检查:
猜出的字母是player1单词的一部分吗?如果是这样,将其添加到player2单词的正确位置(在player1单词中查找位置)
2)玩家1的单词和玩家2的单词相同吗?然后通知玩家2他赢了
3)如果您决定也实施失败(例如,在进行了大量猜测之后),也在此处添加一个检查。如果您需要任何其他游戏逻辑功能,也可以将其添加到此处