创建个用户类(Person)
public class Person {
String name="用户";
int score;
boolean is;
int show;
public int show(){
Scanner sc=new Scanner(System.in);
do{
System.out.println("请出拳:(1.剪刀 2.石头 3.布):");
is=false;
show=sc.nextInt();
switch(show){
case 1:
System.out.println("你出拳为:剪刀");
break;
case 2:
System.out.println("你出拳为:石头");
break;
case 3:
System.out.println("你出拳为:布");
break;
default:
System.out.println("输入有误,请重新输入!");
break;
}
}while(is==true);
return show;
}
}
创建计算机类(Computer)
public class Computer {
String name="电脑";
int score;
public int show(){
int show=(int)(Math.random()*10)%3+1;
switch(show){
case 1:
System.out.println(name+"出拳:剪刀");
break;
case 2:
System.out.println(name+"出拳:石头");
break;
case 3:
System.out.println(name+"出拳:布");
break;
}
return show;
}
}
创建游戏类(Game)
public class Game {
Person person;
Computer computer;
int count;
Scanner sc;
public void initial() {
person = new Person();
computer = new Computer();
count = 0;
sc = new Scanner(System.in);
}
public void startGame() {
initial();
System.out.println("******欢迎进入人机猜拳游戏******");
System.out.println("*********开始猜拳*********");
System.out.print("请输入用户姓名:");
person.name = sc.next();
System.out.print("请选择角色:(1.刘备 2.孙权 3.曹操):");
int role = sc.nextInt();
if (role == 1) {
computer.name = "刘备";
} else if (role == 2) {
computer.name = "孙权";
} else if (role == 3) {
computer.name = "曹操";
}
System.out.println("你选择了:" + computer.name + "对战!");
// 是否要开始游戏
System.out.print("要开始吗?(y/n):");
String con = sc.next();// 输入是否开始
int perFist;// 用户出的拳
int comFist;// 电脑出的拳
while (con.equals("y")) {
perFist = person.show();// 人出拳的方法
comFist = computer.show();// 电脑出拳的方法
/**
* 叛决输赢
*/
// 平局叛决
if ((perFist == 1 && comFist == 1) || (perFist == 2 && comFist == 2) || (perFist == 3 && comFist == 3)) {
System.out.println("平局!");
} else if ((perFist == 1 && comFist == 3) || (perFist == 2 && comFist == 1)
|| (perFist == 3 && comFist == 2)) {// 赢的叛决
System.out.println("恭喜,你赢了!");
person.score++;
} else {
System.out.println("不好意思,你输了!");
computer.score++;
}
count++;
System.out.print("\n是否继续?(y/n):");
con = sc.next();
}
result();
}
public void result() {
System.out.println("------------------------------------");
System.out.println("\t" + person.name + " VS " + computer.name);
System.out.println("\t双方对战了" + count + "局!");
System.out.println("\t姓名\t积分");
System.out.println("\t" + person.name + "\t" + person.score);
System.out.println("\t" + computer.name + "\t" + computer.score);
if (person.score == computer.score) {
System.out.println("\t平局!");
} else if (person.score > computer.score) {
System.out.println("\t恭喜你赢了!");
} else {
System.out.println("\t很遗憾,你输了!");
}
System.out.println("------------------------------------");
}
}
创建测试类(Test)
public class GameTest {
public static void main(String[] args) {
Game game=new Game();
game.startGame();
}
}