用java写一个不需要数据库直接登录的飞翔小鸟游戏
时间: 2023-12-18 19:05:17 浏览: 29
好的,我可以为您提供一个简单的示例代码,但需要注意的是,这个游戏不需要数据库,但是需要文件存储来保存分数和游戏状态。
代码如下:
```java
import java.util.Scanner;
import java.io.*;
public class FlappyBird {
private static String filename = "score.txt"; // 用于保存分数的文件名
private static int score = 0; // 分数
private static int highScore = 0; // 最高分数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到飞翔小鸟游戏!");
// 读取最高分数
try {
File file = new File(filename);
if (file.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
if (line != null) {
highScore = Integer.parseInt(line);
}
reader.close();
} else {
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
System.out.println("请选择操作:");
System.out.println("1. 开始游戏");
System.out.println("2. 查看最高分数");
System.out.println("3. 退出游戏");
int choice = scanner.nextInt();
switch (choice) {
case 1:
startGame();
break;
case 2:
System.out.println("最高分数是:" + highScore);
break;
case 3:
// 保存最高分数
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(String.valueOf(highScore));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("谢谢游玩!");
return;
default:
System.out.println("无效操作!");
break;
}
}
}
private static void startGame() {
score = 0;
System.out.println("游戏开始!");
while (true) {
System.out.println("按下空格键跳跃,其他键退出游戏");
int ch = getch();
if (ch == 32) {
System.out.println("小鸟跳跃!");
score++;
if (score > highScore) {
highScore = score;
}
} else {
System.out.println("游戏结束,得分:" + score);
return;
}
}
}
private static int getch() {
try {
if (System.console() != null) {
return System.console().reader().read();
} else {
return System.in.read();
}
} catch (IOException e) {
return -1;
}
}
}
```
这个游戏使用了文件存储来保存最高分数和当前分数,文件名为“score.txt”。在游戏开始前,程序会读取这个文件来获取最高分数。在游戏结束后,程序会将当前分数与最高分数进行比较,如果当前分数更高,则更新最高分数并保存到文件中。
这个游戏只是一个简单的示例,您可以根据自己的需求进行修改和扩展。