我想創建一個可以由2個玩家玩的hang子手遊戲。玩家1給出另一個玩家需要猜測的單詞。玩家2獲得無限嘗試。用我的hangman遊戲(Java)中的userInput卡住
我的問題是,我需要給整個單詞而不是字母。我想在我的遊戲中有一個功能,玩家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);
}
}
這裏有很多hang子手問題。只要搜索它們,你就會找到你所需要的。 – Tom