这里有2个小游戏(第一个数猜拳游戏,第二个是猜数字游戏)这是一个猜拳游戏,一开始写的时候没有限定输入的字符,后期觉得得先判断下只能输入1,2,3这三个数。import java.util.Random;
import java.util.Scanner;
public class DemoOne {
public static void main(String[] args) {
Random random = new Random();
int ran = random.nextInt(3) + 1;
Scanner scanner = new Scanner(System.in);
while (true) {
int sca = scanner.nextInt();
if (sca!=1&&sca!=2&&sca!=3){
System.out.println("输入有误");
continue;
}
if (sca == 1) {//石头
if (ran == 1) {
System.out.println("电脑出" + ran);
System.out.println("石头对石头平局");
} else if (ran == 2) {
System.out.println("电脑出" + ran);
System.out.println("石头对剪刀,玩家胜利");
} else if (ran == 3) {
System.out.println("电脑出" + ran);
System.out.println("石头对布,电脑胜利");
}
}
if (sca == 2) {//剪刀
if (ran == 1) {
System.out.println("电脑出" + ran);
System.out.println("剪刀对石头电脑胜利");
} else if (ran == 2) {
System.out.println("电脑出" + ran);
System.out.println("剪刀对剪刀,平局");
} else if (ran == 3) {
System.out.println("电脑出" + ran);
System.out.println("剪刀对布,玩家胜利");
}
}
if (sca == 3) {//布
if (ran == 1) {
System.out.println("电脑出" + ran);
System.out.println("布对石头玩家胜利");
} else if (ran == 2) {
System.out.println("电脑出" + ran);
System.out.println("布对剪刀,电脑胜利");
} else if (ran == 3) {
System.out.println("电脑出" + ran);
System.out.println("布对布,平局");
}
}
}
}
}
==================================================================================================
这个是猜数字游戏[1,100],一开始猜的话是没有次数限制的,后期添加了次数限制。import java.sql.SQLOutput;
import java.util.Random;
import java.util.Scanner;
public class Demo04RandomGame {
public static void main(String[] args) {
Random random = new Random();
int ran = random.nextInt(100) + 1;//[1,100]数
Scanner scanner = new Scanner(System.in);
System.out.println("请输入1到100的数字");
int scn = 0;
while (scn != ran) {
for (int i = 0; i < 3; i++) {
scn = scanner.nextInt();
if (scn > ran) {
System.out.println("偏大");
} else if (scn < ran) {
System.out.println("偏小");
} else {
System.out.println("猜对了");
break;
}
}
System.out.println("游戏结束");
break;
}
}
}
|
|