40行java小游戏源代码
时间: 2023-10-05 20:04:19 浏览: 58
java小游戏源代码
以下是一个简单的 Java 小游戏——“猜数字”(Guess Number)的代码示例,共计 40 行:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int numberOfTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
while (win == false) {
System.out.print("Guess a number between 1 and 100: ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess < numberToGuess) {
System.out.println("Your guess is too low.");
} else if (guess > numberToGuess) {
System.out.println("Your guess is too high.");
}
}
System.out.println("Congratulations! You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + numberOfTries + " tries to guess the number.");
}
}
```
这个游戏生成一个 1 到 100 之间的随机整数,玩家需要猜测这个数字。程序会提示玩家输入猜测的数字,并根据玩家的输入给出相应的提示(猜测的数字太高或太低)。如果玩家猜对了数字,游戏结束并输出猜测次数。
阅读全文