package 人机猜拳;
import java.util.Scanner;
public class game {
user user = null;//玩家1 用户
computer computer = null;//玩家2 电脑
//初始化方法
Scanner input = new Scanner(System.in);
public void init() {
//创建玩家对象
user = new user();
computer = new computer();
System.out.println("************");
System.out.println("****猜拳开始***");
System.out.println("************");
System.out.println("出拳规则:1.剪刀 2.石头 3.布");
System.out.println("请选择对方角色(1.刘备 2.孙权 3.曹操)");
int num = input.nextInt();
switch(num) {
case 1:
computer.name = "刘备";
break;
case 2:
computer.name = "孙权";
break;
case 3:
computer.name = "曹操";
break;
}
System.out.print("请输入你的姓名");
user.name= input.next();
System.out.print(user.name + "VS"+computer.name +"对战");
}
public void game() {
//调用init方法,对游戏进行初始化
this.init();
System.out.println("要开始吗?(y/n):");
String answer = input.next();
int count = 0;//表示对战次数
while(answer.equals("y")) {
//调用用户和电脑的出拳方法
count++;
int userNum = user.showfist(input);
int computerNum = computer.showfist();
if(userNum ==3 && computerNum==1 ) {
computer.score++;
System.out.println("你输了");
}else if(userNum ==1 && computerNum==3 ) {
user.score++;
System.out.println("你赢了!");
}else if(userNum > computerNum) {
user.score++;
System.out.println("你赢了");
}else if(userNum < computerNum) {
computer.score++;
System.out.println("你输了");
}else {
System.out.println("平局");
}
System.out.print("是否开始下一轮(y/n):");
answer = input.next();
}
System.out.println("-----------");
System.out.println(user.name + "VS" +computer.name);
System.out.println("对战次数"+count);
System.out.println("姓名\t得分");
System.out.println(user.name+"\t"+user.score);
System.out.println(computer.name+"\t"+computer.score);
if(user.score>computer.score) {
System.out.println("恭喜您,你赢了!");
}else if(user.score < computer.score) {
System.out.println("你个笨笨,输了");
}else {
System.out.println("平局");
}
}
}
package 人机猜拳;
import java.util.Random;
import java.util.Scanner;
public class computer {
String name;//姓名
int score;//得分
public int showfist() {
Random r = new Random();
int num = r.nextInt(3)+1;
String fist = "";
switch (num) {
case 1:
fist = "剪刀";
break;
case 2:
fist = "石头";
break;
case 3:
fist = "布";
break;
}
System.out.println("电脑出拳:" + fist);
return num;
}
}
package 人机猜拳;
import java.util.Scanner;
public class user {
String name;//姓名
int score;//得分
public int showfist(Scanner input) {
System.out.println("请出拳:1.剪刀 2.石头 3.布 (输入相应的数字:)");
int num = input.nextInt();
String fist = "" ;
switch(num) {
case 1:
fist = "剪刀";
break;
case 2:
fist = "石头";
break;
case 3:
fist = "布";
break;
}
System.out.println("你出拳:"+fist);
return num;
}
}
package 人机猜拳;
public class test {
public static void main(String[] args) {
// Scanner input = new Scanner(System.in);
// new user().showfist(input);
// new computer().showfist();
new game().game();
}
}