整体思路:首先定义各种局数,用户先猜拳,然后电脑随机猜拳,最后判断俩者猜拳的大小从而决出输赢
Random类的简单应用,.nextInt的用法(int值在0到自己所定义的数字范围,不包含自己所定义的数字)
public static void main(String[] args) {
int winyonghu = 0;
int windiannao = 0;
int pingju = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("欢迎来到游戏中心");
System.out.println("请用户猜拳,1.石头 2.剪刀 3.布");
int yonghu = scanner.nextInt();
int diannao = new Random().nextInt(3) + 1;
System.out.println("您的出拳是"+choose(yonghu) );
System.out.println("电脑出拳是"+choose(diannao) );
if (yonghu - diannao == 0) {
pingju++;
} else if (yonghu - diannao == -1) {
winyonghu++;
} else if (yonghu - diannao == -2) {
windiannao++;
} else if (yonghu - diannao == 1) {
windiannao++;
} else {
winyonghu++;
}
System.out.println("您赢了" + winyonghu + "次");
System.out.println("电脑赢了" + windiannao + "次");
System.out.println("平局了" + pingju + "次");
}
}
public static String choose(int b) {
if (b == 1) {
return "石头";
}
if (b == 2) {
return "剪刀";
}
if (b == 3) {
return "布";
}
return "";
}
输出结果:
欢迎来到游戏中心
请用户猜拳,1.石头 2.剪刀 3.布
1
您的出拳是石头
电脑出拳是布
您赢了0次
电脑赢了1次
平局了0次
欢迎来到游戏中心
请用户猜拳,1.石头 2.剪刀 3.布