在Spring中实现带多参数的POST请求:猜字游戏接口开发
实现Spring REST猜单词接口
我来帮你一步步实现这个符合需求的猜单词REST接口,咱们从基础类定义到接口逻辑逐一梳理:
1. 完善Game类与状态枚举
首先补全你提到的Game类,同时定义GameStatus枚举来管理游戏状态:
public enum GameStatus { ACTIVE, WIN, LOSE } public class Game { private final String gameId; private final String word; private String guessedWord; private Set<Character> guessedChars; private GameStatus status; private int incorrectGuesses; // 初始化游戏:将目标单词转为下划线占位符 public Game(String gameId, String word) { this.gameId = gameId; this.word = word.toLowerCase(); this.guessedWord = "_".repeat(word.length()); this.guessedChars = new HashSet<>(); this.status = GameStatus.ACTIVE; this.incorrectGuesses = 0; } // 核心逻辑:处理用户的单次猜测 public void processGuess(char guess) { // 游戏已结束则直接返回,不处理后续逻辑 if (status != GameStatus.ACTIVE) { return; } guess = Character.toLowerCase(guess); // 跳过已猜过的字符 if (guessedChars.contains(guess)) { return; } guessedChars.add(guess); if (word.contains(String.valueOf(guess))) { // 猜对了,更新占位符字符串 StringBuilder updatedGuessedWord = new StringBuilder(guessedWord); for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == guess) { updatedGuessedWord.setCharAt(i, guess); } } guessedWord = updatedGuessedWord.toString(); // 检查是否完全猜中,更新状态为WIN if (!guessedWord.contains("_")) { status = GameStatus.WIN; } } else { // 猜错了,错误次数+1 incorrectGuesses++; // 这里可自定义失败阈值,比如错误6次判定为LOSE if (incorrectGuesses >= 6) { status = GameStatus.LOSE; } } } // Getter方法,对外暴露必要字段 public String getGameId() { return gameId; } public String getGuessedWord() { return guessedWord; } public int getIncorrectGuesses() { return incorrectGuesses; } public GameStatus getStatus() { return status; } }
2. 定义请求DTO
为了规范接口参数接收,创建一个DTO来匹配你需要的请求格式{game: 'cdaeaa', guess: 'e'}:
public class GuessRequest { private String game; // 对应游戏ID private String guess; // 用户猜测的单个字符 // Getter & Setter public String getGame() { return game; } public void setGame(String game) { this.game = game; } public String getGuess() { return guess; } public void setGuess(String guess) { this.guess = guess; } }
3. 实现REST控制器
编写Controller处理/guess接口,这里用HashMap模拟游戏存储(生产环境建议用Redis或数据库实现持久化):
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class GameController { // 模拟游戏存储容器,key为gameId private final Map<String, Game> gameStore = new HashMap<>(); // 可选:新增创建游戏接口(需先创建游戏才能进行猜测) @PostMapping("/create-game") public Game createGame(String gameId, String word) { Game game = new Game(gameId, word); gameStore.put(gameId, game); return game; } // 核心猜词接口 @PostMapping("/guess") public Map<String, Object> handleGuess(@RequestBody GuessRequest request) { // 1. 校验请求参数 String gameId = request.getGame(); String guessStr = request.getGuess(); if (guessStr == null || guessStr.length() != 1) { return Map.of("error", "猜测字符必须是单个字母"); } char guess = guessStr.charAt(0); // 2. 获取对应游戏实例 Game game = gameStore.get(gameId); if (game == null) { return Map.of("error", "未找到ID为" + gameId + "的游戏"); } // 3. 处理猜测逻辑 game.processGuess(guess); // 4. 构造符合要求的响应格式 return Map.of( "gameId", game.getGameId(), "word", game.getGuessedWord(), "incorrect", game.getIncorrectGuesses(), "status", game.getStatus().name() ); } }
4. 测试示例
- 先调用创建游戏接口初始化游戏:
POST /create-game?gameId=cdaeaa&word=apple
- 调用猜词接口,请求体为:
{ "game": "cdaeaa", "guess": "e" }
- 得到的响应结果为:
{ "gameId": "cdaeaa", "word": "_pp_e", "incorrect": 0, "status": "ACTIVE" }
额外提示
- 生产环境优化:HashMap仅用于本地测试,多实例部署时需改用Redis或数据库存储游戏状态
- 参数校验:可结合Spring Validation注解(如
@NotBlank)加强参数合法性校验 - 错误处理:用
@ControllerAdvice实现全局异常处理,返回更友好的错误响应
内容的提问来源于stack exchange,提问作者ohbrobig
相关产品推荐
相关产品推荐

