首先创建一个Java project,在其中创建如下类:

在GameWindow中写入代码如下:

  1 package game;
  2
  3 import java.awt.BorderLayout;
  4 import java.awt.Color;
  5 import java.awt.FlowLayout;
  6 import java.awt.Font;
  7 import java.awt.GridBagConstraints;
  8 import java.awt.GridBagLayout;
  9 import java.awt.event.ActionEvent;
 10 import java.awt.event.ActionListener;
 11 import java.util.Random;
 12
 13 import javax.swing.*;
 14
 15 public class GameWindow extends JFrame implements ActionListener {// 窗口充当监听器 { 16     JButton a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
 17     JLabel lblword, lblmessage;
 18     JPanel keypad, key1, key2, key3, screen, notify;
 19     int len, count, chance, flag, rnd;
 20     Random rd;
 21     String word[] = { "JAPAN", "QATAR", "SYRIA", "MONGOLIA", "BAHARAIN", "INDIA", "PAKISTAN", "AUSTRALIA", "AFGHNISTAN",
 22             "CHINA" };
 23
 24     StringBuffer blanks;
 25
 26     public GameWindow() {
 27         a = new JButton("A");
 28         b = new JButton("B");
 29         c = new JButton("C");
 30         d = new JButton("D");
 31         e = new JButton("E");
 32         f = new JButton("F");
 33         g = new JButton("G");
 34         h = new JButton("H");
 35         i = new JButton("I");
 36         j = new JButton("J");
 37         k = new JButton("K");
 38         l = new JButton("L");
 39         m = new JButton("M");
 40         n = new JButton("N");
 41         o = new JButton("O");
 42         p = new JButton("P");
 43         q = new JButton("Q");
 44         r = new JButton("R");
 45         s = new JButton("S");
 46         t = new JButton("T");
 47         u = new JButton("U");
 48         v = new JButton("V");
 49         w = new JButton("W");
 50         x = new JButton("X");
 51         y = new JButton("Y");
 52         z = new JButton("Z");
 53
 54         lblmessage = new JLabel("Guess a Country Name");
 55         lblmessage.setFont(new Font("Serif", Font.PLAIN, 20));
 56
 57         lblword = new JLabel();
 58         lblword.setFont(new Font("Serif", Font.PLAIN, 35));
 59
 60         notify = new JPanel();
 61         notify.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
 62
 63         screen = new JPanel();
 64         screen.setBackground(Color.WHITE);
 65         screen.setSize(0, 200);
 66
 67         keypad = new JPanel();
 68         keypad.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
 69         keypad.setBackground(Color.black);
 70
 71         key1 = new JPanel();
 72         key1.setBackground(Color.blue);
 73
 74         key2 = new JPanel();
 75         key2.setBackground(Color.GREEN);
 76
 77         key3 = new JPanel();
 78         key3.setBackground(Color.RED);
 79
 80         // 变量初始化
 81         count = 0;
 82         chance = 0;
 83         rd = new Random();
 84         blanks = new StringBuffer();
 85
 86         setTitle("Hangman Game");
 87         setSize(500, 450);
 88         setVisible(true);
 89         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 90
 91         // Add Listener
 92         a.addActionListener(this);
 93         b.addActionListener(this);
 94         c.addActionListener(this);
 95         d.addActionListener(this);
 96         e.addActionListener(this);
 97
 98         f.addActionListener(this);
 99         g.addActionListener(this);
100         h.addActionListener(this);
101         i.addActionListener(this);
102         j.addActionListener(this);
103
104         k.addActionListener(this);
105         l.addActionListener(this);
106         m.addActionListener(this);
107         n.addActionListener(this);
108         o.addActionListener(this);
109
110         p.addActionListener(this);
111         q.addActionListener(this);
112         r.addActionListener(this);
113         s.addActionListener(this);
114         t.addActionListener(this);
115
116         u.addActionListener(this);
117         v.addActionListener(this);
118         w.addActionListener(this);
119         x.addActionListener(this);
120         y.addActionListener(this);
121
122         z.addActionListener(this);
123     }
124
125     public void addComponent() {
126         GridBagConstraints gc = new GridBagConstraints();
127
128         notify.setLayout(new FlowLayout());
129         notify.add(lblmessage);
130
131         screen.setLayout(new GridBagLayout());
132         screen.add(lblword, gc);
133
134         keypad.setLayout(new GridBagLayout());
135
136         key1.setLayout(new FlowLayout());
137         key1.add(q);
138         key1.add(w);
139         key1.add(e);
140         key1.add(r);
141         key1.add(t);
142         key1.add(y);
143         key1.add(u);
144         key1.add(i);
145         key1.add(o);
146         key1.add(p);
147
148         gc.gridx = 0;
149         gc.gridy = 0;
150         keypad.add(key1, gc);
151
152         key2.setLayout(new FlowLayout());
153         key2.add(a);
154         key2.add(s);
155         key2.add(d);
156         key2.add(f);
157         key2.add(g);
158         key2.add(h);
159         key2.add(j);
160         key2.add(k);
161         key2.add(l);
162
163         gc.gridx = 0;
164         gc.gridy = 1;
165         keypad.add(key2, gc);
166
167         key3.setLayout(new FlowLayout());
168         key3.add(z);
169         key3.add(x);
170         key3.add(c);
171         key3.add(v);
172         key3.add(b);
173         key3.add(n);
174         key3.add(m);
175
176         gc.gridx = 0;
177         gc.gridy = 2;
178         keypad.add(key3, gc);
179
180         setLayout(new BorderLayout());
181         add(notify, BorderLayout.NORTH);
182         add(screen, BorderLayout.CENTER);
183         add(keypad, BorderLayout.SOUTH);
184
185     }
186
187     @Override
188     public void actionPerformed(ActionEvent ae) {
189         JButton jb = (JButton) ae.getSource();
190         String letter = ae.getActionCommand();
191
192         flag = 0;
193         for (int loop = 0; loop < len; loop++) {
194             if (letter.charAt(0) == word[rnd].charAt(loop)) {
195                 flag = 1;
196                 blanks.replace((loop * 3), ((loop * 3) + 1), letter);
197                 count++;
198
199             }
200         }
201         if (flag == 1) {
202             lblword.setText(blanks.toString());
203             jb.setBackground(Color.GREEN);
204             jb.setEnabled(false);
205
206         } else {
207             jb.setBackground(Color.RED);
208             jb.setEnabled(false);
209             chance++;
210
211         }
212         if (count == len) {
213             JOptionPane.showMessageDialog(this, "Congrats You Guessed the Word correctly");
214             int n = JOptionPane.showConfirmDialog(this, "Do you want to play again ?", "Restart Game",
215                     JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
216
217             if (n == JOptionPane.YES_NO_OPTION) {
218                 GameWindow obj = new GameWindow();
219                 obj.stratGame();
220                 this.dispose();
221
222             } else {
223                 this.dispose();
224                 Menu obj = new Menu();
225                 obj.addComponent();
226             }
227
228         }
229         if (chance > 5) {
230             JOptionPane.showMessageDialog(this, "Sorry you lost your chances");
231             int n = JOptionPane.showConfirmDialog(this, "Do you want to play again", "Restart Game",
232                     JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
233
234             if (n == JOptionPane.YES_OPTION) {
235                 GameWindow obj = new GameWindow();
236                 obj.stratGame();
237                 this.dispose();
238
239             } else {
240                 this.dispose();
241                 Menu obj = new Menu();
242                 obj.addComponent();
243             }
244         }
245     }
246
247     public void stratGame() {
248         addComponent();
249         rnd = rd.nextInt(10);
250         len = word[rnd].length();
251
252         for (int j = 0; j < len; j++) {
253             blanks.append("_  ");
254
255         }
256         lblword.setText(blanks.toString());
257     }
258 }

View Code

在Hangman中写入代码如下:

 1 package game;
 2
 3 public class Hangman {
 4     public static void main(String args[]) {
 5         Menu mobj = new Menu();
 6         mobj.addComponent();
 7
 8         /*
 9          * GameWindow gobj=new GameWindow(); gobj.addComponent();
10          */
11         // validate;
12     }
13 }
14
15 /*
16  * package game;
17  *
18  * import java.util.Random;
19  *
20  * import java.util.Scanner;
21  *
22  * public class Hangman { String word[] = { "japan", "qatar", "syria",
23  * "mongolia", "bathrain", "india" };
24  *
25  * public void showMenu() {
26  * System.out.println("--------------Menu------------");
27  * System.out.println("1.play Game"); System.out.println("2.Instructions");
28  * System.out.println("3.Exit"); System.out.println();
29  * System.out.println("\nPlease input your choose:"); Scanner reader = new
30  * Scanner(System.in); int option = 0; try { option = reader.nextInt(); } catch
31  * (RuntimeException e) {
32  * System.out.println("Please  provide a valid numeric input"); showMenu(); } //
33  * switch构造(接受用户选择) switch (option) { case 1: playGame(); break; case 2:
34  * instructionGame(); break; case 3: exitGrame(); break; // 不是1,2,3的时候抛出异常
35  * default: try { throw new MenuInputException(); } catch (Exception e) {
36  * showMenu(); } System.out.println("The input is wrong !"); } }
37  *
38  * private void exitGrame() { // TODO Auto-generated method stub
39  * System.out.println("Exit Grame is waking up !");
40  *
41  * }
42  *
43  * private void instructionGame() { // TODO Auto-generated method stub
44  * System.out.println("Instruction Game is waking up!");
45  *
46  * }
47  *
48  * private void playGame() { // String
49  * word[]={"japan","qatar","syria","mongolia","bathrain","india"}; int len, i,
50  * count = 0, rnd, flag = 0; String choice, temp; Random rd = new Random();
51  * Scanner input = new Scanner(System.in); rnd = rd.nextInt(6); len =
52  * word[rnd].length();
53  * System.out.println("The length of the first word you guess is :" + len);
54  * char[] newString = new char[len]; StringBuffer wrgString = new
55  * StringBuffer(); for (int j = 0; j < len; j++) { System.out.print("_ "); }
56  * System.out.println(); do { flag = 0;
57  * System.out.print("\n\nEnter your guess:"); String ch; try { ch =
58  * input.nextLine().toLowerCase(); if (ch.length() != 1) { throw new
59  * WrongInputException(); } count++; for (i = 0; i < len; i++) { //
60  * System.out.println( " answer"+ch.charAt(0)); if (word[rnd].charAt(i) ==
61  * ch.charAt(0)) { System.out.println("yeah,right ;" + ch.charAt(0));
62  * newString[i] = word[rnd].charAt(i); flag = 1; } } if (flag == 0) { flag = 1;
63  * wrgString.append(ch + " ,"); System.out.println("\nMisses:" + wrgString +
64  * "   Go on! "); System.out.println(); } System.out.println(newString); temp =
65  * new String(newString); System.out.print(temp); if (word[rnd].equals(temp)) {
66  * System.out.println("---------Congrats :)You won -----------");
67  * System.out.println("Do you want to play again(Y/N)"); choice =
68  * input.nextLine(); if (choice.equalsIgnoreCase("y")) { playGame(); } else {
69  * showMenu(); } } } catch (WrongInputException e) { flag = 1; } } while (flag
70  * != 0); }
71  *
72  * public static void main(String[] args) { Hangman gh = new Hangman();
73  * gh.showMenu(); } }
74  */

View Code

在Menu中写入代码如下:

 1 package game;
 2
 3 import java.awt.Font;
 4 import java.awt.GridBagConstraints;
 5 import java.awt.GridBagLayout;
 6 import java.awt.event.ActionEvent;
 7 import java.awt.event.ActionListener;
 8
 9 import javax.swing.JButton;
10 import javax.swing.JFrame;
11 import javax.swing.JLabel;
12 import javax.swing.JOptionPane;
13
14 public class Menu extends JFrame implements ActionListener {
15     JButton option1;
16     JButton option2;
17     JButton option3;
18     JLabel name;
19
20     public Menu() {
21         option1 = new JButton("Play Game");
22         option2 = new JButton("View Instructions");
23         option3 = new JButton("Exit");
24         name = new JLabel("HANGAME");
25         name.setFont(new Font("Serif", Font.PLAIN, 24));
26
27         setTitle("Hangman Game");
28         setSize(300, 200);
29         setResizable(false);
30         setVisible(true);
31
32         // 注册监听器
33         option1.addActionListener(this);
34         option2.addActionListener(this);
35         option3.addActionListener(this);
36
37     }
38
39     public void addComponent() {
40         setLayout(new GridBagLayout());
41         GridBagConstraints c = new GridBagConstraints();
42
43         c.gridx = 0;
44         c.gridy = 0;
45         c.weighty = 0.1;
46         c.anchor = c.CENTER;
47         add(name, c);
48
49         c.gridx = 0;
50         c.gridy = 1;
51         c.fill = c.HORIZONTAL;
52         add(option1, c);
53
54         c.gridx = 0;
55         c.gridy = 2;
56         c.fill = c.HORIZONTAL;
57         add(option2, c);
58
59         c.gridx = 0;
60         c.gridy = 3;
61         c.fill = c.HORIZONTAL;
62         add(option3, c);
63     }
64
65     @Override
66     public void actionPerformed(ActionEvent e) {
67         // TODO Auto-generated method stub
68         if (e.getSource() == option1) {
69             GameWindow obj = new GameWindow();
70             obj.stratGame();
71         } else if (e.getSource() == option2) {
72             JOptionPane.showMessageDialog(this, "1.You can"
73                     + " guess the word by clicking the character from the virtual keypad.\n"
74                     + "2.You can select a maximum color, and the correct one will be highlighted with green color.",
75                     "Instructions ", JOptionPane.INFORMATION_MESSAGE);
76             ;
77         } else if (e.getSource() == option3) {
78             System.exit(0);
79
80         }
81     }
82 }

View Code

另外,添加了2个异常的处理:

在MenuInputException中写入代码如下:

1 package game;
2
3 public class MenuInputException extends RuntimeException {
4     MenuInputException() {
5         System.out.println("Please provide a valid input(1-3)");
6     }
7 }

分析:该段代码为在命令行界面运行时,出现选择超过3 ,则报出异常,但是在命令行界面不会出现。

在WrongInputException中写入代码如下:

1 package game;
2
3 public class WrongInputException extends RuntimeException {
4     WrongInputException(){
5         System.out.println("Please provide a single character only..!!");
6     }
7 }

分析:该段代码也是在命令行运行时可能出现单次输入的字母不为一个,则报出异常。同样ui界面不会出现。

运行结果如下:

出现如下窗口:窗口中有三个选项:play Game,View Introduction,Exit

点击Play Game 出现下图,表示开始玩游戏

点击View Intorduction界面弹出消息对话框,提示游戏规则:

点击Exit,就直接退出。

转载于:https://www.cnblogs.com/Catherinezhilin/p/8005109.html

Java--制作乱字游戏相关推荐

  1. 【教程1】Java制作国际象棋小游戏-01

    Java 制作国际象棋小游戏-01 菜鸟学了几天Java之后手痒痒了,所以开始谋划写个小游戏什么的练练手,刚好一门面向对象的课程布置了一个project,不限内容不限语言,所以菜鸟的小组决定做个国际象 ...

  2. 【java】猜字游戏

    猜字游戏 首先声明一个字符数组来储存单词(由程序设计者决定储存哪些单词及个数),根据储存的下标来随机访问其中一个,作为一次猜字. 进入猜字流程的入口.设置一个字符变量entrance,初始化为'y', ...

  3. 用JAVA制作抓老鹰游戏_Java制作最难练手速游戏,Faker都坚持不了一分钟

    原标题:Java制作最难练手速游戏,Faker都坚持不了一分钟 想练手速,来啊,互相伤害啊 Java制作最难练手速游戏,目测Faker也坚持不了一分钟 制作思路:只靠Java实现.Java.Java. ...

  4. java制作纯字rpg小游戏_求java rpg小游戏源代码 最好是文字rpg 不需要很复杂 只是交作业用...

    展开全部 连连看的小源码 package Lianliankan; import javax.swing.*; import java.awt.*; import java.awt.event.*; ...

  5. JAVA练习208-井字游戏

    设计一个算法,判断玩家是否赢了井字游戏.输入是一个 N x N 的数组棋盘,由字符" ","X"和"O"组成,其中字符" &quo ...

  6. 类似java制作计算器的游戏_急求一Java编写的类似计算机带的计算器的程序!!...

    展开全部 No 1. import java.awt.*; import java.awt.event.*; import java.applet.*; public class Calculator ...

  7. 用JAVA制作小游戏——飞机大战(三)

    本篇博客是对飞机大战游戏项目完整代码的展示 详细代码讲解: 用JAVA制作小游戏--飞机大战(一) 用JAVA制作小游戏--飞机大战(二) 最下方附整个程序的文件下载链接 代码展示 主界面 impor ...

  8. 用JAVA制作小游戏——飞机大战(二)

    本篇博客是对飞机大战游戏使用代码的展示 重难点: 首先需要鼠标能够控制战机,使鼠标在窗口内时始终能够使战机的位置与鼠标相同,实现鼠标控制战斗机移动. 其次需要能够以一定的速度产生子弹和敌机,并且以一定 ...

  9. 用JAVA制作小游戏——推箱子(三)

    本篇博客主要是对推箱子地图编辑器功能的代码讲解. 首先给出这段代码的部分运行截图: 重难点: 地图编辑器主要有三个重难点: 需要有一个绘制地图的界面 能够实现地图绘制的功能 地图绘制完成后需要将地图内 ...

  10. 用JAVA制作小游戏——推箱子(二)

    本篇博客主要是推箱子游戏界面功能的代码讲解. 首先先给出这段代码的部分运行截图: 重难点: 游戏界面主要有五个重难点: 固定好地图的位置 地图的显示 构建菜单栏 读取地图数据 玩家操作功能实现 地图的 ...

最新文章

  1. Python 的一万种用法:制作 Web 可视化页面
  2. vb调用excel方法详解及操作相关操作命令大全
  3. 深入研究Clang(九) Clang代码阅读之打log读流程2
  4. limit是mysql的语法
  5. python profile_python程序之profile分析
  6. boost::math::tools::simple_continued_fraction用法的测试程序
  7. 08.存储Cinder→4.Cinder组件详解→3.cinder-volume
  8. 不兼容结构的协调——适配器模式
  9. Java网页开发中model实现Serializable接口的原因
  10. configureWebpack与chainWebpack
  11. fastjson对Date的处理
  12. 《云计算核心技术剖析》读书笔记之一
  13. 21天学通JAVA——学习笔记
  14. java编译jni错误_JNI开发的常见错误
  15. c# word 增加段落_word排版技巧:如何防止行距随字号而改变?
  16. 安卓QQ协议抓包教程
  17. 用java操作MySQL编写的高校水电费管理系统
  18. html空白键,空格键符号是什么?HTML中空格键符号有哪些?
  19. 15、react 的 非受控组件 和 受控组件
  20. 图像配置分类及名词解释

热门文章

  1. cad指定许可服务器,AutoCAD许可证版本
  2. JS日期、年月日、时分秒
  3. 【老罗笔记】异类(Outliers)
  4. 深入理解 Laravel Eloquent(一)——基本概念及用法
  5. 已解决 There are unfinished transactions remaining. You might consider running yum-complete-transaction
  6. 数据结构之线性表(顺序表、链表、栈、队列)
  7. (二)SGE 部署 预配置
  8. 在 Go 中处理恐慌
  9. openssl1.1.1下载地址
  10. 锂离子电池种类介绍和分类