接(二)
用户类,电脑人类,我们已经编写完了··剩下的就是游戏类了,说白了,游戏类的主要作用就是控制游戏的流程,就相当于游戏机的手柄。
不多说了,看代码吧
- import java.util.Scanner;
- public class Game
- {
- Person per;
- Computer com;
- int count;
- Scanner input = new Scanner(System.in);
- //构造方法,初始化
- public Game()
- {
- per = new Person();
- com = new Computer();
- count = 0;
- }
- //开始游戏
- public void gameBegin()
- {
- System.out.println("==========猜拳小游戏==========");
- System.out.println("==============================");
- System.out.println("游戏规则:1.拳头 2.剪刀 3.包袱");
- System.out.println("请选择人物:1.小强 2.小毛 3.小明");
- int number = input.nextInt();
- switch(number)
- {
- case 1:
- per.name = "小强";
- System.out.println("您选择的是小强");
- break;
- case 2:
- per.name = "小毛";
- System.out.println("您选择的是小毛");
- break;
- case 3:
- per.name = "小明";
- System.out.println("您选择的是小明");
- break;
- }
- //记录出的拳
- int perno;
- int comno;
- System.out.println("要开始游戏吗?(y/n)");
- String answer = input.next();
- while(answer.equalsIgnoreCase("y"))
- {
- perno = per.showFist();
- comno = com.showFist();
- //判断结果
- if((perno==1&&comno==1)||(perno==2&&comno==2)||(perno==3&&comno==3))
- {
- System.out.println("平局");
- //记录较量总次数
- this.count ++;
- }
- else if((perno==1&&comno==2)||(perno==2&&comno==3)||(perno==3&&comno==1))
- {
- System.out.println("玩家胜");
- per.count ++;
- this.count++;
- }
- else
- {
- System.out.println("电脑胜");
- com.count++;
- this.count++;
- }
- System.out.println("是否要继续?(y/n)");
- answer = input.next();
- }
- //当结束时,显示总结果
- showResult();
- }
- //显示结果
- public void showResult()
- {
- System.out.println("较量总次数:" + this.count);
- System.out.println("玩家胜次数:" + per.count);
- System.out.println("电脑胜次数:" + com.count);
- }
- }
接下来,编写测试类
- public class Test
- {
- public static void main(String args [])
- {
- Game game = new Game();
- game.gameBegin();
- }
- }
运行一下,看看吧··
到现在,这个简单的JAVA猜拳小游戏就完成了··