1、Computer 类:
public class Computer { String name; int score; public int computerPunches(){ int number=(int)(Math.random()*10); if(number<=3){ number=1; }else if (number>3&&number<=6){ number=2; }else { number=3; } switch (number){ case 1: System.out.println(name +"出拳:剪刀"); break; case 2: System.out.println(name +"出拳:石头"); break; case 3: System.out.println(name +"出拳:布"); break; } return number; } }
2、Game 类:
public class Game { int count=0; People people=new People(); Computer computer=new Computer(); Scanner input=new Scanner(System.in); public void select(){ System.out.println("请选择对战角色:1:刘备;2:孙权;3:曹操"); int number=input.nextInt(); System.out.print("请输入你的名字:"); people.name=input.next(); if(number==1){ System.out.print("刘备 VS"+ people.name +" 对战"); } if(number==2) { System.out.print("孙权 VS" + people.name + " 对战"); } if(number==3) { System.out.print("曹操 VS" + people.name + " 对战"); } } public void begin(){ String answer1; String answer2; Scanner input=new Scanner(System.in); System.out.print("\n要开始吗?(y/n) "); answer1=input.next(); ; if("y".equals(answer1)){ do{ int a=people.peoplePunches(); int b=computer.computerPunches(); if(a==1&&b==3||a==2&&b==1||a==3&&b==2){ System.out.println("你赢了"); people.score++; }else if(a==1&&b==1||a==2&&b==2||a==3&&b==3){ System.out.println("平局"); }else { System.out.println("你输了"); } computer.score++; count++; System.out.println("是否开始下一轮?(y/n)"); answer2=input.next(); }while ("y".equals(answer2)); } } public String result(){ String a; if(people.score>computer.score){ a="你赢了"; }else if(people.score==computer.score){ a="平局"; }else { a="你输了"; } return a; } }
3、People 类:
public class People { String name; int score; public int peoplePunches(){ Scanner input=new Scanner(System.in); System.out.println("请你出拳: "); int number=input.nextInt(); switch (number){ case 1: System.out.println("你出拳:剪刀"); break; case 2: System.out.println("你出拳:石头"); break; case 3: System.out.println("你出拳:布"); break; } return number; } }
4、GameTest
public static void main(String[] args) { Game game = new Game(); System.out.println("*********人机大战********"); System.out.println("出拳规则:1:剪刀;2:石头;3:布"); game.select(); game.begin(); } }