一、Person类的编写
public class Person { Scanner input = new Scanner(System.in); String name1; // 用户姓名 int perFist; // 用户出拳 int comFist; // 电脑出拳 int score1; // 用户积分 int score2; // 对方积分 int count; // 对战次数 int choose; // 选择 /** * 用户选择类 */ public void show() { System.out.println("出拳规则:1.剪刀2.石头3.布"); System.out.println("请选择对方角色(1.刘备2.孙权3.曹操)"); choose = input.nextInt(); System.out.println("请输入您的姓名:"); name1 = input.next(); // 对决判断 do { switch (choose) { case 1: System.out.println(name1 + " VS" + "刘备"); break; case 2: System.out.println(name1 + " VS" + "孙权"); break; case 3: System.out.println(name1 + " VS" + "曹操"); break; default: System.out.println("输入有误请重新输入:"); break; } } while (choose > 3); } /** * 出拳循环类 */ public void show1() { System.out.println("要开始吗?(y/n)"); char answer = input.next().charAt(0); if (answer == 'y') { System.out.println("\n请出拳:1.剪刀2.石头3.布(请输入相应数字!):"); int perFist = input.nextInt(); boolean chose=true; // 随机数的产生 int comFist = (int) (Math.random() * 3+1); switch (comFist) { case 1: System.out.println("对手出拳:剪刀"); break; case 2: System.out.println("对手出拳:石头"); break; case 3: System.out.println("对手出拳:布"); break; } // 判断用户与计算机的出拳结果 if ((perFist == 1 && comFist == 1) || (perFist == 2 && comFist == 2) || (perFist == 3 && comFist == 3)) { System.out.println("结果:平局,真衰!\n"); // 平局 } else if ((perFist == 1 && comFist == 3) || (perFist == 2 && comFist == 1) || (perFist == 3 && comFist == 2)) { score1++; System.out.println("结果:恭喜,你赢了!"); // 用户赢 } else { score2++; System.out.println("结果:你输了,真笨!\n"); // 计算机赢 } } } /** * 结果类 */ public void show2() { String name2 = ""; // 定义选手名字 System.out.println("————————————————————————————————————————————-"); switch (choose) { case 1: name2 = "刘备"; break; case 2: name2 = "孙权"; break; case 3: name2 = "曹操"; break; } System.out.println(name1 + " VS" + name2); System.out.println("对战次数:" + count); System.out.println("\n姓名\t得分"); System.out.println(name1 + "\t" + score1); System.out.println(name2 + "\t" + score2); if (score1 > score2) { System.out.println("恭喜恭喜!"); } else { System.out.println("呵呵,笨笨,下次加油哦!"); } System.out.println("————————————————————————————————————————————-"); } }
二、测试Person类
public class Test { /** * 实例化过程 */ public static void main(String[] args) { System.out.println("————————————欢迎进入游戏世界————————————"); System.out.println("\t******************"); System.out.println("\t**猜拳,开始**"); System.out.println("\t******************\n"); Scanner input = new Scanner(System.in); /** * 创建对象 */ Person game = new Person(); char chioce; // 定义选择 int count = 0; // 定义对战次数 /** * 调用方法 */ game.show(); do { /** * 调用方法 */ game.show1(); // 判断 System.out.println("\n是否进入下一轮?(y/n)"); chioce = input.next().charAt(0); count++; } while (chioce == 'y'); /** * 调用方法 */ game.show2(); } }