java猜数字1-100游戏编程,添加初级、中级、高级三个选择
时间: 2024-10-11 15:17:52 浏览: 28
[指南]猜数字小游戏JAVA程序报告.doc
在Java中,你可以创建一个猜数字游戏,让用户从1到100之间猜测,同时提供初级、中级、高级三个难度等级。以下是基本的游戏框架:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
enum DifficultyLevel {
EASY(1), MEDIUM(50), HARD(100);
private final int rangeStart;
DifficultyLevel(int rangeStart) {
this.rangeStart = rangeStart;
}
int getRangeStart() {
return rangeStart;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DifficultyLevel level;
int randomNumber, attempts = 0;
// 获取用户选择的难度级别
System.out.println("选择难度等级:");
System.out.println("1. 初级 (1-50)");
System.out.println("2. 中级 (51-100)");
System.out.println("3. 高级 (1-100)");
level = chooseDifficulty(scanner);
// 生成随机数
randomNumber = level.getRangeStart() + new Random().nextInt(level.getRangeEnd() - level.getRangeStart());
// 游戏循环
while (true) {
System.out.println("你在 " + level.getDescription() + " 难度下,有猜测机会。");
System.out.print("请输入你的猜测数字 (1-" + level.getRangeEnd() + "): ");
int guess = scanner.nextInt();
if (guess == randomNumber) {
System.out.println("恭喜,你猜对了!你一共尝试了 " + ++attempts + " 次。");
break;
} else if (guess < randomNumber) {
System.out.println("太小了,再试一次吧!");
} else {
System.out.println("太大了,再试试。");
}
}
scanner.close();
}
private static DifficultyLevel chooseDifficulty(Scanner scanner) {
System.out.print("你的选择是: ");
int input = scanner.nextInt();
switch (input) {
case 1:
return DifficultyLevel.EASY;
case 2:
return DifficultyLevel.MEDIUM;
case 3:
return DifficultyLevel.HARD;
default:
System.out.println("无效的选择,请重新输入!");
return chooseDifficulty(scanner);
}
}
// 描述等级的辅助方法
private static String getDescription(DifficultyLevel level) {
switch (level) {
case EASY:
return "1-50";
case MEDIUM:
return "51-100";
case HARD:
return "1-100";
}
}
}
```
在这个游戏中,玩家可以选择不同难度,然后电脑随机生成一个范围内的数字,直到玩家猜对为止。
阅读全文