import java.util.Random; import java.util.Scanner; /** * 简单游戏示例 - 猜数字游戏 * 这是一个展示Java基础编程能力的示例项目 */ public class NumberGuessingGame { private Random random; private Scanner scanner; private int targetNumber; private int maxAttempts; private int currentAttempt; public NumberGuessingGame() { this.random = new Random(); this.scanner = new Scanner(System.in); this.maxAttempts = 7; this.currentAttempt = 0; } /** * 初始化游戏 */ public void initializeGame() { targetNumber = random.nextInt(100) + 1; // 1-100之间的随机数 currentAttempt = 0; System.out.println("🎮 欢迎来到猜数字游戏!"); System.out.println("我已经想了一个1-100之间的数字,你有" + maxAttempts + "次机会来猜中它。"); System.out.println("================================="); } /** * 获取玩家输入 */ public int getPlayerGuess() { System.out.print("请输入你的猜测 (1-100): "); while (true) { try { int guess = scanner.nextInt(); if (guess < 1 || guess > 100) { System.out.print("请输入1-100之间的数字: "); } else { return guess; } } catch (Exception e) { System.out.print("请输入有效的数字: "); scanner.next(); // 清除无效输入 } } } /** * 检查猜测结果 */ public boolean checkGuess(int guess) { currentAttempt++; if (guess == targetNumber) { System.out.println("🎉 恭喜!你猜对了!"); System.out.println("你用了 " + currentAttempt + " 次机会。"); return true; } else if (guess < targetNumber) { System.out.println("📈 太小了!试试更大的数字。"); System.out.println("剩余机会: " + (maxAttempts - currentAttempt)); } else { System.out.println("📉 太大了!试试更小的数字。"); System.out.println("剩余机会: " + (maxAttempts - currentAttempt)); } return false; } /** * 显示游戏结果 */ public void showResult(boolean won) { if (!won) { System.out.println("💔 游戏结束!正确的数字是: " + targetNumber); } System.out.println("================================="); } /** * 询问是否继续游戏 */ public boolean askToContinue() { System.out.print("是否再玩一次?(y/n): "); String response = scanner.next().toLowerCase(); return response.equals("y") || response.equals("yes"); } /** * 主游戏循环 */ public void playGame() { boolean playing = true; while (playing) { initializeGame(); boolean won = false; while (currentAttempt < maxAttempts && !won) { int guess = getPlayerGuess(); won = checkGuess(guess); } showResult(won); playing = askToContinue(); } System.out.println("谢谢游玩!再见!👋"); } /** * 主方法 */ public static void main(String[] args) { NumberGuessingGame game = new NumberGuessingGame(); game.playGame(); } }