1、猜数字游戏简易文字游戏
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = new Random().nextInt(100);
System.out.println("开始猜数字游戏,输入数字后按enter");
while (true) {
int inputNum = scanner.nextInt();
if (num > inputNum) {
System.out.println("猜错了,当前数字小于正确答案 当前猜测数字:" + inputNum);
} else if (num < inputNum) {
System.out.println("猜错了,当前数字大于正确答案 当前猜测数字:" + inputNum);
} else {
System.out.println("答案正确 游戏结束...... " + num);
break;
}
}
scanner.close();
}
2、石头剪刀布简易文字游戏
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("开始石头剪刀布游戏,输入(石头、剪刀、布)后按enter进行游戏,输入(退出)后按enter退出游戏");
ArrayList<String> gameValue = Lists.newArrayList("石头", "剪刀", "布");
Pattern pattern = Pattern.compile("石头|剪刀|布");
while (true) {
String inputStr = scanner.next();
if ("退出".equals(inputStr)) break;
if (!pattern.matcher(inputStr).find()) {
System.out.println("无效的游戏输入值:" + inputStr);
continue;
}
int index = new Random().nextInt(gameValue.size());
String gv = gameValue.get(index);
System.out.println("电脑出拳:" + gv + " 玩家出拳:" + inputStr);
gameRule(inputStr, gv);
}
scanner.close();
}
private static void gameRule(String inputStr, String gv) {
if (gv.equals(inputStr)) {
System.out.println("平局!!");
return;
}
switch (inputStr) {
case "石头": {
if ("剪刀".equals(gv)) {
System.out.println("恭喜您本局胜利!!");
} else {
System.out.println("很遗憾您本局输了!!");
}
break;
}
case "剪刀": {
if ("布".equals(gv)) {
System.out.println("恭喜您本局胜利!!");
} else {
System.out.println("很遗憾您本局输了!!");
}
break;
}
case "布": {
if ("石头".equals(gv)) {
System.out.println("恭喜您本局胜利!!");
} else {
System.out.println("很遗憾您本局输了!!");
}
}
}
}