我目前正在研究基于Hangman的GUI游戏,用于大学作业。我有一个基于控制台的版本,它按我想要的方式工作,但将其转换为基于GUI的版本证明是棘手的。到目前为止,我在GUI中有基本布局等。然而,按钮并没有像我希望的那样发挥作用,它们都表明它们不在单词中。我已经围绕这个问题绕圈子,任何帮助都将不胜感激。
import java.io.IOException;
import javax.swing.JFrame;
public class TestHangman
{
public static void main(String[] args) throws IOException
{
Hangman sample = new Hangman();
sample.setTitle("Hangman Game");
sample.setSize(800, 500);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}
}
这是目前为止游戏的主要代码:
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Hangman extends JFrame implements ActionListener, MouseListener
{
private static final ActionListener letterHandler = null;
private Container cPane, cn;
private JLabel lblTitle, lblTitle2, lblTitle3, lblTitle4, btn2, btn3, btn4;
private JButton btnExit, btnStart;
private JButton [] btn = new JButton[26];
private JPanel pNorth, pSouth, pEast, pWest, pCenter, p3;
private JFrame frame = new JFrame();
private Font fnt;
private JMenuBar mb;
private JMenu mSystem;
private JMenuItem mIRules, mIDev, mIRestart, mIExit;
private static String hiddenCountry;
static StringBuilder currentGuess;
private static ArrayList<Character> previousGuesses = new ArrayList<>();
static int maxTries = 7;
static int currentTry = 0;
int outputTry = maxTries - currentTry;
boolean doYouWantToPlay = true;
static char guess;
ArrayList<String> countries = new ArrayList<>();
private static FileReader fileReader;
private static BufferedReader bufferedFileReader;
Hangman() throws IOException
{
fnt = new Font( "Monospaced", 0, 24 );
setFont(fnt);
initializeStreams();
setHiddenCountry(pickCountry());
currentGuess = initializeCurrentGuess();
mb = new JMenuBar();
mSystem = new JMenu("File");
mIDev = new JMenuItem("Developer");
mIRules = new JMenuItem("Rules");
mIRestart = new JMenuItem("Restart");
mIExit = new JMenuItem("Exit");
mIDev.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith");
}
});
mIRules.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word"
+ "\n to guess is represented by dashes. The player"
+ "\n is given the option to enter a letter. If the letter"
+ "\n guessed is contained in the word, the letter will"
+ "\n replace the dash in its appropriate placement."
+ "\n You cannot exceed 7 wrong guesses or else you"
+ "\n lose. Words are selected randomly.", "Instructions",
JOptionPane.INFORMATION_MESSAGE);
}// end actionPerformed method
});
mIRestart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
mIRestart.setVisible(true);
Hangman sample = null;
try {
sample = new Hangman();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sample.setTitle("Hangman Game");
sample.setSize(800, 500);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
mIExit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
mSystem.add(mIDev);
mSystem.add(mIRules);
mSystem.add(mIRestart);
mSystem.add(mIExit);
mb.add(mSystem);
setJMenuBar(mb);
cPane = getContentPane();
cPane.setBackground(new Color (236, 128, 19));
cn = getContentPane();
//cn.setLayout(new BorderLayout (5,5));
cn.setBackground(new Color (236, 128, 19));
pNorth = new JPanel();
pSouth = new JPanel();
pEast = new JPanel();
pWest = new JPanel();
pCenter = new JPanel();
p3 = new JPanel(new GridLayout (3, 10));
pCenter.setLayout(new GridLayout (3,9,0,0));
pWest.setLayout(new GridLayout(3,1,10,10));
pEast.setLayout(new GridLayout(2,1,10,10));
pSouth.setLayout(new GridLayout(3,10,1,1));
pCenter.setLayout(null);
lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER);
lblTitle.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle.setBackground(new Color (38, 29, 226));
lblTitle.setOpaque(true);
lblTitle.setForeground(Color.white);
pNorth.add(lblTitle);
lblTitle2 = new JLabel("" + getActualCurrentGuess(), SwingConstants.CENTER);
lblTitle2.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle2.setBackground(new Color (38, 29, 226));
lblTitle2.setOpaque(true);
lblTitle2.setForeground(Color.white);
pCenter.add(lblTitle2);
lblTitle2.setBounds(1,275,650,30);
lblTitle4 = new JLabel("" + Hangman.hiddenCountry, SwingConstants.CENTER);
lblTitle4.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle4.setBackground(new Color (38, 29, 226));
lblTitle4.setOpaque(true);
lblTitle4.setForeground(Color.white);
pCenter.add(lblTitle4);
lblTitle4.setBounds(150,1,500,30);
for(int i = 0; i < 26; i++)
{
JButton btnX = new JButton();
btn[i] = btnX;
btn[i].setText("" + (char)('A'+ i));
btn[i].addActionListener(this);
pSouth.add(btn[i]);
btn[i].addActionListener(letterHandler);
}
cn.add(p3, BorderLayout.SOUTH);
btnStart = new JButton(" Restart ");
btnStart.setFont(new Font("Comic Sans", Font.BOLD, 12));
btnStart.setBackground(Color.GREEN);
btnStart.setForeground(Color.white);
btnStart.setOpaque(true);
btnStart.setBorder(BorderFactory.createRaisedBevelBorder());
//pEast.setBackground(Color.WHITE);
//pEast.add(lblTitle);
pWest.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
mIRestart.setVisible(true);
Hangman sample = null;
try
{
sample = new Hangman();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
sample.setTitle("Hangman Game");
sample.setSize(800, 500);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
btn2 = new JLabel(" Tries Remaining " + outputTry);
btn2.setFont(new Font("Comic Sans", Font.BOLD, 12));
btn2.setBackground(new Color (38, 29, 226));
btn2.setForeground(Color.white);
btn2.setOpaque(true);
btn2.setBorder(BorderFactory.createRaisedBevelBorder());
//pWest.setBackground(Color.WHITE);
//pWest.add(btn2);
pWest.add(btn2);
cPane.add(pNorth, BorderLayout.NORTH);
cPane.add(pSouth, BorderLayout.SOUTH);
cPane.add(pWest, BorderLayout.WEST);
cPane.add(pEast, BorderLayout.EAST);
cPane.add(pCenter, BorderLayout.CENTER);
//btnExit.addActionListener(this);
pCenter.addMouseListener(this);
pNorth.addMouseListener(this);
pSouth.addMouseListener(this);
pEast.addMouseListener(this);
pWest.addMouseListener(this);
}
protected void Hangman()
{
// TODO Auto-generated method stub
}
public char getText(String string)
{
return guess;
}
public char setText(String string, char guess)
{
return Hangman.guess = guess;
}
public void actionPerformed(ActionEvent e)
{
for(int j = 0; j < 26; j++)
{
if(e.getSource() == btn[j])
{
Hangman.guess = btn[j].getText().charAt(0);
btn[j].setVisible(false);
if(Hangman.playGuess(guess))
{
}
else
{
}
}
}
}//end actionPerformed Method
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void initializeStreams() throws IOException
{
try
{
File inFile = new File("F:\\Java Programs\\IntroJavaPrograms\\src\\hangmanapplication\\countriesnospaces.txt");
fileReader = new FileReader(inFile);
bufferedFileReader = new BufferedReader(fileReader);
String currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
countries.add(currentLine);
currentLine = bufferedFileReader.readLine();
}
bufferedFileReader.close();
fileReader.close();
}
catch (IOException e)
{
System.out.println("Could not initiate streams");
}
}
public String pickCountry()
{
Random rand = new Random();
int wordIndex = Math.abs(rand.nextInt()) % countries.size();
return countries.get(wordIndex).toUpperCase();
}
public StringBuilder initializeCurrentGuess()
{
StringBuilder current = new StringBuilder();
for (int i = 0; i < getHiddenCountry().length() * 2; i++)
{
if (i % 2 == 0)
{
current.append("_");
}
else
{
current.append(" ");
}
}
return current;
}
public String getActualCurrentGuess()
{
return "Country to Guess: " + currentGuess.toString();
}
public static boolean gameOver()
{
if (playerWin())
{
System.out.println("Congratulations!!! You Won!!! You guessed the country was " + getHiddenCountry());
return true;
}
else if (playerLose())
{
System.out.println(addWholeMan());
System.out.println();
System.out.println("HANGMAN - You Lose!!! The country was " + getHiddenCountry());
System.out.println();
return true;
}
return false;
}
public static boolean playerWin()
{
String guess = getCondensedCurrentGuess();
return guess.equals(getHiddenCountry());
}
public static String getCondensedCurrentGuess()
{
String guess = currentGuess.toString();
return guess.replace(" ", "");
}
public static boolean playerLose()
{
return currentTry >= maxTries;
}
public static boolean letterAlreadyGuessed(char guess)
{
return getPreviousGuesses().contains(guess);
}
public static boolean playGuess(char guess)
{
boolean isItAGoodGuess = false;
//boolean isItAGoodGuess = true;
getPreviousGuesses().add(guess);
for(int i = 0; i < getHiddenCountry().length(); i++)
{
if (getHiddenCountry().charAt(i) == guess)
{
currentGuess.setCharAt(i * 2, guess);
isItAGoodGuess = true;
System.out.print("That letter is in the country's name!!");
}
}
if (!isItAGoodGuess)
{
currentTry++;
System.out.print("That letter is not in the country's name");
}
return isItAGoodGuess;
}
public String drawMan()
{
switch(currentTry)
{
case 0: return noMan();
case 1: return addMandHead();
case 2: return addManBody();
case 3: return addManFirstArm();
case 4: return addManSecondArm();
case 5: return addManFirstLeg();
//case 6: return addWholeMan();
default : return addWholeMan();
}
}
private static String addWholeMan()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| /|\\ \n"+
"\t| | \n"+
"\t| | \n"+
"\t| / \\\n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String addManFirstLeg()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| /|\\ \n"+
"\t| | \n"+
"\t| | \n"+
"\t| / \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String addManSecondArm()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| /|\\ \n"+
"\t| | \n"+
"\t| | \n"+
"\t| \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String addManFirstArm()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| /| \n"+
"\t| | \n"+
"\t| | \n"+
"\t| \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String addManBody()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| | \n"+
"\t| | \n"+
"\t| | \n"+
"\t| \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String addMandHead()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| 0 \n"+
"\t| \n"+
"\t| \n"+
"\t| \n"+
"\t| \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
private String noMan()
{
return "\t - - - - -\n"+
"\t| |\n"+
"\t| \n"+
"\t| \n"+
"\t| \n"+
"\t| \n"+
"\t| \n"+
"\t|\\ \n"+
"\t|_\\\n";
}
public static String getHiddenCountry()
{
return hiddenCountry;
}
public void setHiddenCountry(String hiddenCountry)
{
Hangman.hiddenCountry = hiddenCountry;
}
public static ArrayList<Character> getPreviousGuesses()
{
return previousGuesses;
}
public void setPreviousGuesses(ArrayList<Character> previousGuesses)
{
Hangman.previousGuesses = previousGuesses;
}
}
txt文件countriesnospaces包含以下国家/地区列表:
阿富汗 阿尔巴尼亚 阿尔及利亚 安道尔 安哥拉 安圭拉 南极洲 阿根廷 亚美尼亚 阿鲁巴 澳大利亚 奥地利 阿塞拜疆 巴哈马 巴林 孟加拉国 巴巴多斯 白俄罗斯 比利时 伯利兹 贝宁 百慕大 不丹 玻利维亚 波斯尼亚 博茨瓦纳 巴西 文莱 保加利亚 布基纳法索 布隆迪 柬埔寨 喀麦隆 加拿大 鳄鱼 乍得 智利 中国 科科斯 哥伦比亚 科摩罗 刚果 克罗地亚 古巴 塞浦路斯 丹麦 吉布提 多米尼加 厄瓜多尔 埃及 厄立特里亚 爱沙尼亚 埃塞俄比亚 斐 芬兰 法国 加蓬 冈比亚 格鲁吉亚 德国 加纳 直布罗陀 希腊 格陵兰 格林纳达 瓜德罗普岛 关岛 危地马拉 几内亚 圭亚那 海地 洪都拉斯 匈牙利 冰岛 印度 印度尼西亚 伊朗 伊拉克 爱尔兰 以色列 意大利 牙买加 日本 约旦 哈萨克斯坦 肯尼亚 基里巴斯 科威特 吉尔吉斯斯坦 老挝 拉脱维亚 黎巴嫩 莱索托 利比里亚 利比亚 列支敦士登 立陶宛 卢森堡 澳门 马其顿 马达加斯加 马拉维 马来西亚 马尔代夫 马里 马耳他 马提尼克 毛里塔尼亚 毛里求斯 马约特 墨西哥 密克罗尼西亚 摩尔多瓦 摩纳哥 蒙古 蒙特塞拉特 摩洛哥 莫桑比克 缅甸 纳米比亚 瑙鲁 尼泊尔 荷兰 尼加拉瓜 尼日尔 尼日利亚 纽埃 挪威 阿曼 巴基斯坦 帕劳 巴拿马 巴拉圭 秘鲁 菲律宾 皮特凯恩 波兰 葡萄牙 卡塔尔 团圆 罗马尼亚 卢旺达 萨摩亚 塞内加尔 塞舌尔 新加坡 斯洛文尼亚 索马里 西班牙 苏丹 苏里南 斯威士兰 瑞典 瑞士 叙利亚 台湾 塔吉克斯坦 坦桑尼亚 泰国 多哥 托克劳 汤加 突尼斯 火鸡 土库曼斯坦 图瓦卢 乌干达 乌克兰 乌拉圭 乌兹别克斯坦 瓦努阿图 委内瑞拉 越南 也门 南斯拉夫 扎伊尔 赞比亚 津巴布韦
答案 0 :(得分:0)
忽略代码中可能存在的设计缺陷,我将尝试解决您的直接问题。
当您调用以下行以确定按钮具有哪个文本时:
Hangman.guess = getText("" + (char)('A' + j));
您正试图从guess
变量中检索它,显然您只需要检索按钮的文本,因此从您的案例中的按钮获取文本的调用将如下{{ 1}}因为你在每个按钮的文本中只有一个btn[index].getText()
,你可以通过调用char
从字符串中检索它,所以最后你可以把这一行写成:
charAt(0)
在您完成游戏后,我强烈建议您在CodeReview.SE中提交以供审核,这将为您提供有关如何改进代码的结构/可读性等方面的一些好建议。