GuessGame.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package homework.p08_guessgame;
  2. import java.util.Random;
  3. /**
  4. * @author WanJl
  5. * @version 1.0
  6. * @title GuessGame
  7. * @description
  8. *
  9. *
  10. * @create 2026/7/22
  11. */
  12. public class GuessGame {
  13. /**
  14. * 目标数字(系统随机生成)
  15. */
  16. private int target;
  17. /**
  18. * 最大范围(如 100 表示 1~100)
  19. */
  20. private int maxRange;
  21. /**
  22. * 已猜次数
  23. */
  24. private int attempts;
  25. public GuessGame(int maxRange) {
  26. Random random=new Random();
  27. this.maxRange = maxRange;
  28. //并将 attempts 初始化为 0
  29. this.attempts=0;
  30. target=random.nextInt(this.maxRange)+1;
  31. }
  32. /**
  33. * 猜数字的方法
  34. * @param num
  35. * @return
  36. */
  37. public String guess(int num){
  38. //已猜次数加1
  39. this.attempts++;
  40. if (num>target){
  41. return "猜大了";
  42. }else if(num<this.target){
  43. return "猜小了";
  44. }else{
  45. return "猜对了";
  46. }
  47. }
  48. /**
  49. * 返回已猜次数
  50. * @return
  51. */
  52. public int getAttempts(){
  53. return this.attempts;
  54. }
  55. public int getTarget() {
  56. return target;
  57. }
  58. public void setTarget(int target) {
  59. this.target = target;
  60. }
  61. public int getMaxRange() {
  62. return maxRange;
  63. }
  64. public void setMaxRange(int maxRange) {
  65. this.maxRange = maxRange;
  66. }
  67. public void setAttempts(int attempts) {
  68. this.attempts = attempts;
  69. }
  70. }