71 lines
2.1 KiB
Java
71 lines
2.1 KiB
Java
package cn.airnan.dg.service;
|
|
|
|
import cn.airnan.dg.DrawAndGuessApplication;
|
|
import cn.airnan.dg.configs.Global;
|
|
import cn.airnan.dg.entity.Topic;
|
|
import com.alibaba.fastjson2.JSON;
|
|
import com.alibaba.fastjson2.JSONArray;
|
|
import com.alibaba.fastjson2.JSONObject;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.io.InputStream;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
/**
|
|
* 题目相关业务逻辑
|
|
*/
|
|
@Slf4j
|
|
@Service
|
|
public class TopicService {
|
|
|
|
/**
|
|
* 从文件加载题库
|
|
*/
|
|
public static void loadTopics() {
|
|
try (InputStream inputStream = DrawAndGuessApplication.class.getResourceAsStream("/topic.json")) {
|
|
if (inputStream != null) {
|
|
String content = new String(inputStream.readAllBytes());
|
|
JSONArray jsonArray = JSON.parseArray(content);
|
|
for (Object obj : jsonArray) {
|
|
JSONObject jsonObject = (JSONObject) obj;
|
|
for (String key : jsonObject.keySet()) {
|
|
String value = jsonObject.getString(key);
|
|
Global.TOPICS.add(new Topic(key, value));
|
|
}
|
|
}
|
|
log.info("共加载{}条题目", Global.TOPICS.size());
|
|
}
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 随机取出N道题目
|
|
*
|
|
* @param n 取出的题目数量
|
|
* @return 题目列表
|
|
*/
|
|
public List<Topic> randomTopics(int n) {
|
|
Map<Integer, String> map = new HashMap();
|
|
List<Topic> news = new ArrayList();
|
|
if (Global.TOPICS.size() <= n) {
|
|
return Global.TOPICS;
|
|
} else {
|
|
while (map.size() < n) {
|
|
int random = (int) (Math.random() * Global.TOPICS.size());
|
|
if (!map.containsKey(random)) {
|
|
map.put(random, "");
|
|
news.add(Global.TOPICS.get(random));
|
|
}
|
|
}
|
|
return news;
|
|
}
|
|
}
|
|
|
|
}
|