用java编写一个小游戏
时间: 2023-08-22 11:06:42 浏览: 38
好的,我可以为您提供一个简单的Java文本游戏的示例。这个游戏叫“猜数字”。
首先,让我们编写一个类来处理游戏逻辑:
```
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
private int answer;
private int numGuesses;
private Scanner scanner;
public GuessingGame() {
Random rand = new Random();
answer = rand.nextInt(100) + 1;
numGuesses = 0;
scanner = new Scanner(System.in);
}
public void play() {
int guess;
boolean correct = false;
System.out.println("Welcome to the guessing game!");
System.out.println("I'm thinking of a number between 1 and 100.");
while (!correct) {
System.out.print("Guess a number: ");
guess = scanner.nextInt();
numGuesses++;
if (guess == answer) {
correct = true;
} else if (guess < answer) {
System.out.println("Too low!");
} else {
System.out.println("Too high!");
}
}
System.out.println("Congratulations, you guessed the number in " + numGuesses + " tries!");
}
}
```
在这个类中,我们使用了一个`Random`类来生成一个1到100之间的随机整数。我们使用`Scanner`类来接收玩家的猜测,并在每次猜测后更新计数器。如果玩家猜对了,游戏结束并打印出玩家猜测的次数。
现在,我们可以编写一个`main`方法来启动这个游戏:
```
public class Main {
public static void main(String[] args) {
GuessingGame game = new GuessingGame();
game.play();
}
}
```
现在您可以编译和运行这个程序,开始玩猜数字游戏了!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)