Java代码编写猜拳小游戏
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Boolean action = true;
while(action){
// 产生随机数
Random random = new Random();
// 将产生的随机数控制在只能在[1,3]之间,并且是随机数是整型类型
int computerFalse = random.nextInt(3) + 1;
//当随机数等于1时
if (computerFalse == 1) {
// 将整形变量的computerFalse的转换成字符串型
String computerTrue = computerFalse + "";
// 将转换成字符串类型的变量赋值为石头
computerTrue = "石头";
String playOne = "剪刀";
String playTwo = "布";
// 接收用户从键盘中输入的值
Scanner sc = new Scanner(System.in);
System.out.println("让我们来猜拳吧!请输入石头/剪刀/布");
System.out.print("请输入你想要出的拳头:");
// 用字符串型变量接收用户从键盘输入的字符串
String player = sc.next();
if (player.equals(computerTrue)) {
System.out.println("您和电脑真的是心有灵犀");
}else if (computerTrue.equals(computerTrue) & player.equals(playOne)) {
System.out.println("真的很抱歉,您输给电脑了");
}else if (computerTrue.equals(computerTrue) & player.equals(playTwo)){
System.out.println("您真厉害,竟然赢了电脑");
}else {
System.out.println("你输入错误的信息,程序退出!");
break;
}
}
if (computerFalse == 2) {
String computerTrue = computerFalse + "";
computerTrue = "布";
String playOne = "剪刀";
String playTwo = "石头";
Scanner sc = new Scanner(System.in);
System.out.println("让我们来猜拳吧!请输入石头/剪刀/布");
System.out.print("请输入你想要出的拳头:");
String player = sc.next();
if (player.equals(computerTrue)) {
System.out.println("您和电脑真的是心有灵犀!");
}else if (computerTrue.equals(computerTrue) & player.equals(playOne)) {
System.out.println("您真厉害,竟然赢了电脑!");
}else if (computerTrue.equals(computerTrue) & player.equals(playTwo)){
System.out.println("真的很抱歉,您输给电脑了!");
}else {
System.out.println("你输入错误的信息,程序退出!");
break;
}
}
if (computerFalse == 3) {
String computerTrue = computerFalse + "";
computerTrue = "剪刀";
String playOne = "石头";
String playTwo = "布";
Scanner sc = new Scanner(System.in);
System.out.println("让我们来猜拳吧!请输入石头/剪刀/布");
System.out.print("请输入你想要出的拳头:");
String player = sc.next();
if (player.equals(computerTrue)) {
System.out.println("您和电脑真的是心有灵犀!");
}else if (computerTrue.equals(computerTrue) & player.equals(playOne)) {
System.out.println("您真厉害,竟然赢了电脑!");
}else if (computerTrue.equals(computerTrue) & player.equals(playTwo)){
System.out.println("真的很抱歉,您输给电脑了!");
}else {
System.out.println("你输入错误的信息,程序退出!");
break;
}
}
Scanner sc = new Scanner(System.in);
System.out.print("请输入继续/退出:");
String playerTell = sc.next();
String playerTellFalse = "退出";
String playTellTrue = "继续";
if (playerTell.equals(playerTellFalse)) {
System.out.println("游戏已经退出,程序结束运行!");
action = false;
}else if (playerTell.equals(playTellTrue)) {
action = true;
}else {
System.out.println("您输入的信息错误,游戏结束!");
action = false;
}
}
}
}