• Bot代码的执行(微服务)


    负责接收一段代码,把代码扔到我们的队列当中、每一次我们去运行一段代码
    运行结束之后、把我们的结果返回给我们的服务器

    先把依赖复制过来、我们需要动态的把用户传过来的Java代码编译然后执行
    需要加入依赖joor-java-8、用Java的代码的写法举例子
    未来自己实现的时候可以换成任意语言、在这个线程里面是有一堆的bot代码等待执行
    然后我们会有一个队列、每次我们从队列中取出一个bot代码来执行
    执行的时候用的是一个Java的包会方便的去帮我们动态编译一段Java代码
    未来可以在云端把他换成一个docker、你在云端自动启动一个docker容器
    给docker设置一个内存上限200M再去docker中动态执行一段Java代码用timeout
    去限制某一个程序的执行时间、这样又安全又可以支持其他语言
    所以这里我们用Java一个包来动态执行一段Java代码
    开一个线程用我们的joor去动态执行一段代码

     

    实现Service和Controller

    实现完service之后
    去实现我们的controller、怎么将SpringBoot和docker关联?
    SpringBoot里面可以直接执行shell命令
    注意要用127.0.0.1因为我们的config里写的是127.0.0.1

    前端加入选择框

    每一步的传递都需要加上额外的参数
    botid、前端先加上一个框
    中间加上一个复选框、需要动态的获得我们的bot列表
    这样我们的bot就传过来了、我们需要把bot的信息传回到前端

    把前面每一个通信都加上BotId

    前面通信的时候每一次通信都是没有加botid的
    userid、我们需要把前面每一个通信都加上botid 对应service层也要加上
    发的时候收的时候都需要传我们的id

    判断人或者机器+编码

    在创建完地图执行nextstep的时候
    判断一下当前的玩家是人还是代码、如果是代码的话就需要像我们的微服务发送一
    段代码、然后让她自动去算、如果是人来操作的话就要等待用户的输入
    所以这里需要判断一下如果player的botid=-1的话表示是由人来操作
    编码的时候我们随意编只要把我们的编码编成字符串就可以
    第一段传的是地图信息、中间用#号隔开

    消费者生产者模型

    微服务可以不断的去接收用户的一个输入
    当接收的代码比较多的时候、我们应该把他们所有接收到的代码放到一个队列里面
    我们每接收到一个任务、消费者是一个单独的线程
    苦力不断是完成任务,每来一个任务检测队列是否为空如果队列不空,从对头拿出
    代码执行、执行完之后再去检查

    consume里面开一个新的线程

    consume里面开一个新的线程
    如果被awit阻塞住后就会被唤醒、然后执行
    实现一下consume操作、需要在consume里面开一个新的线程
    这样我们就可以从前端动态的传一份代码过来传完之后动态的编译一遍
    编译完之后我们就可以动态的调用它编译后的结果

    代码执行,此项目只支持java代码的执行,用的是joor java 8实现

    可扩展为docker实现,设置内存上限,时间,用命令可执行所有语言代码,并具备一定安全性,因为docker与运行环境隔绝

    让BotRunning System获得到前端选择的Bot

    新建Bot执行微服务项目 

    右键backendcloud->新建->模块

    导包

    改pom

    1. org.springframework.boot
    2. spring-boot-starter-web
    3. org.springframework.boot
    4. spring-boot-starter-test
    5. test
    6. org.springframework.boot
    7. spring-boot-starter-security
    8. 2.7.1
    9. org.projectlombok
    10. lombok
    11. 1.18.24
    12. provided
    13. org.jooq
    14. joor-java-8
    15. 0.9.14

    BotRunningSystem接收前端选择的botId

    文件结构

    botrunningsystem
        config
            RestTemplateConfig.java
            SecurityConfig.java
        controller
            BotRunningController.java
        service
            impl
                BotRunningServiceImpl.java
            BotRunningService.java
        BotRunningSystemApplication.java

    将BotRunningSystem/Main.java 更名为 BotRunningSystemApplication.java

     

    1. @SpringBootApplication
    2. public class BotRunningSystemApplication {
    3. public static void main(String[] args) {
    4. SpringApplication.run(BotRunningSystemApplication.class, args);
    5. }
    6. }

    接口

    1. public interface BotRunningService {
    2. String addBot(Integer userId, String botCode, String input);
    3. }

    接口实现

    1. @Service
    2. public class BotRunningServiceImpl implements BotRunningService {
    3. @Override
    4. public String addBot(Integer userId, String botCode, String input) {
    5. System.out.println("add bot: " + userId + " " + botCode + " " + input);
    6. return "add bot success";
    7. }
    8. }

    控制器

    1. @RestController
    2. public class BotRunningController {
    3. @Autowired
    4. private BotRunningService botRunningService;
    5. @PostMapping("/bot/add/")
    6. public String addBot(@RequestParam MultiValueMap data) {
    7. Integer userID = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));
    8. String botCode = data.getFirst("bot_code");
    9. String input = data.getFirst("input");
    10. return botRunningService.addBot(userID, botCode, input);
    11. }
    12. }

    权限控制(网关)

    1. @Configuration
    2. @EnableWebSecurity
    3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    4. @Override
    5. protected void configure(HttpSecurity http) throws Exception {
    6. http.csrf().disable()
    7. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    8. .and()
    9. .authorizeRequests()
    10. .antMatchers("/bot/add/").hasIpAddress("127.0.0.1")
    11. .antMatchers(HttpMethod.OPTIONS).permitAll()
    12. .anyRequest().authenticated();
    13. }
    14. }

    服务间发送消息的RestTemplate

    1. @Configuration
    2. public class RestTemplateConfig {
    3. @Bean
    4. public RestTemplate getRestTemplate() {
    5. return new RestTemplate();
    6. }
    7. }

    端口配置

    在resources新建文件

    1. Application.properties
    2. server.port=3002

    前端选择Bot

    匹配界面

    添加选择操作方式

    1. MatchGround.vue

    后端接收bot

    BackEnd接收Bot
    WebSocketServer接收到匹配请求,将bot传给匹配服务

    1. @Component
    2. // url链接:ws://127.0.0.1:3000/websocket/**
    3. @ServerEndpoint("/websocket/{token}") // 注意不要以'/'结尾
    4. public class WebSocketServer {
    5. ...
    6. private void startMatching(Integer botId) {
    7. System.out.println("start matching!");
    8. MultiValueMap data = new LinkedMultiValueMap<>();
    9. data.add("user_id", this.user.getId().toString());
    10. data.add("rating", this.user.getRating().toString());
    11. data.add("bot_id", botId.toString());
    12. restTemplate.postForObject(addPlayerUrl, data, String.class);
    13. }
    14. ...
    15. @OnMessage
    16. public void onMessage(String message, Session session) {
    17. ...
    18. if("start-matching".equals(event)) {
    19. startMatching(data.getInteger("bot_id"));
    20. }
    21. ...
    22. }
    23. ...
    24. }

    Matching System接收Bot

    Matching System接收到backend传的botId,将bot传给BotRunningSystem服务

    控制器

    1. @RestController
    2. public class MatchingController {
    3. @Autowired
    4. private MatchingService matchingService;
    5. // 参数不能使用普通map,MultiValueMap和普通map的区别时,这个是一个键对应多个值
    6. @PostMapping("/player/add/")
    7. public String addPlayer(@RequestParam MultiValueMap data) {
    8. ...
    9. Integer botId = Integer.parseInt(Objects.requireNonNull(data.getFirst("bot_id")));
    10. return matchingService.addPlayer(userId, rating, botId);
    11. }
    12. ...
    13. }

    接口

    1. public interface MatchingService {
    2. String addPlayer(Integer userId, Integer rating, Integer botId);
    3. ...
    4. }

    接口实现

    1. @Service
    2. public class MatchingServiceImpl implements MatchingService {
    3. public static final MatchingPool matchingPool = new MatchingPool();
    4. @Override
    5. public String addPlayer(Integer userId, Integer rating, Integer botId) {
    6. System.out.println("Add Player: " + userId + " " + rating + " " + botId);
    7. matchingPool.addPlayer(userId, rating, botId);
    8. return "add player success";
    9. }
    10. ...
    11. }

    匹配池

    1. // 匹配池是多线程的
    2. @Component
    3. public class MatchingPool extends Thread {
    4. ...
    5. public void addPlayer(Integer userId, Integer rating, Integer botId) {
    6. // 在多个线程(匹配线程遍历players时,主线程调用方法时)会操作players变量,因此加锁
    7. lock.lock();
    8. try {
    9. players.add(new Player(userId, rating, botId, 0));
    10. } finally {
    11. lock.unlock();
    12. }
    13. }
    14. ...
    15. }

    匹配池的Player

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Player {
    5. private Integer userId;
    6. private Integer rating;
    7. private Integer botId;
    8. private Integer waitingTime;
    9. }

    匹配池返回结果加上botId

    1. // 匹配池是多线程的
    2. @Component
    3. public class MatchingPool extends Thread {
    4. ...
    5. private void sendResult(Player a, Player b) { // 返回匹配结果
    6. System.out.println("send result: " + a + " " + b);
    7. MultiValueMap data = new LinkedMultiValueMap<>();
    8. data.add("a_id", a.getUserId().toString());
    9. data.add("a_bot_id", a.getBotId().toString());
    10. data.add("b_id", b.getUserId().toString());
    11. data.add("b_bot_id", b.getBotId().toString());
    12. restTemplate.postForObject(startGameUrl, data, String.class);
    13. }
    14. ...
    15. }

    BackEnd接收匹配成功返回的botId

    StartGameController.java

    1. @RestController
    2. public class StartGameController {
    3. ...
    4. @PostMapping("/pk/start/game/")
    5. public String startGame(@RequestParam MultiValueMap data) {
    6. Integer aId = Integer.parseInt(Objects.requireNonNull(data.getFirst("a_id")));
    7. Integer aBotId = Integer.parseInt(Objects.requireNonNull(data.getFirst("a_bot_id")));
    8. Integer bId = Integer.parseInt(Objects.requireNonNull(data.getFirst("b_id")));
    9. Integer bBotId = Integer.parseInt(Objects.requireNonNull(data.getFirst("b_bot_id")));
    10. return startGameService.startGame(aId, aBotId, bId, bBotId);
    11. }
    12. }

    StartGameService.java

    1. public interface StartGameService {
    2. String startGame(Integer aId, Integer aBotId, Integer bId, Integer bBotId);
    3. }

    StartGameServiceImpl.java

    1. @Service
    2. public class StartGameServiceImpl implements StartGameService {
    3. @Override
    4. public String startGame(Integer aId, Integer aBotId, Integer bId, Integer bBotId) {
    5. System.out.println("start gameL: " + aId + " " + bId);
    6. WebSocketServer.startGame(aId, aBotId, bId, bBotId);
    7. return "start game success";
    8. }
    9. }

    WebSocketServer.java

    1. @Component
    2. // url链接:ws://127.0.0.1:3000/websocket/**
    3. @ServerEndpoint("/websocket/{token}") // 注意不要以'/'结尾
    4. public class WebSocketServer {
    5. ...
    6. public static BotMapper botMapper;
    7. ...
    8. @Autowired
    9. public void setBotMapper(BotMapper botMapper) {
    10. WebSocketServer.botMapper = botMapper;
    11. }
    12. ...
    13. public static void startGame(Integer aId, Integer aBotId, Integer bId, Integer bBotId) {
    14. User a = userMapper.selectById(aId), b = userMapper.selectById(bId);
    15. Bot botA = botMapper.selectById(aBotId), botB = botMapper.selectById(bBotId);
    16. Game game = new Game(
    17. 13,
    18. 14,
    19. 20,
    20. a.getId(),
    21. botA,
    22. b.getId(),
    23. botB);
    24. ...
    25. }
    26. ...
    27. }

    Player.java

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Player {
    5. private Integer id;
    6. private Integer botId; // -1表示亲自出马,否则表示用AI打
    7. private String botCode;
    8. ...
    9. }

    WebSocketServer.java

    将RestTemplate变成public,若是代码输入则屏蔽人的输入

    1. @Component
    2. // url链接:ws://127.0.0.1:3000/websocket/**
    3. @ServerEndpoint("/websocket/{token}") // 注意不要以'/'结尾
    4. public class WebSocketServer {
    5. ...
    6. public static RestTemplate restTemplate;
    7. private void move(int direction) {
    8. if(game.getPlayerA().getId().equals(user.getId())) {
    9. if(game.getPlayerA().getBotId().equals(-1)) // 亲自出马则接收输入
    10. game.setNextStepA(direction);
    11. } else if(game.getPlayerB().getId().equals(user.getId())) {
    12. if(game.getPlayerB().getBotId().equals(-1))
    13. game.setNextStepB(direction);
    14. }
    15. }
    16. ...
    17. }

    Game.java

    1. public class Game extends Thread {
    2. ...
    3. private static final String addBotUrl = "http://127.0.0.1:3002/bot/add/";
    4. public Game(
    5. Integer rows,
    6. Integer cols,
    7. Integer inner_walls_count,
    8. Integer idA,
    9. Bot botA,
    10. Integer idB,
    11. Bot botB
    12. ) {
    13. this.rows = rows;
    14. this.cols = cols;
    15. this.inner_walls_count = inner_walls_count;
    16. this.g = new int[rows][cols];
    17. Integer botIdA = -1, botIdB = -1;
    18. String botCodeA = "", botCodeB = "";
    19. if(botA != null) {
    20. botIdA = botA.getId();
    21. botCodeA = botA.getContent();
    22. }
    23. if(botB != null) {
    24. botIdB= botB.getId();
    25. botCodeB = botB.getContent();
    26. }
    27. playerA = new Player(idA, botIdA, botCodeA, rows - 2, 1, new ArrayList<>());
    28. playerB = new Player(idB, botIdB, botCodeB, 1, cols - 2, new ArrayList<>());
    29. }
    30. private String getInput(Player player) { // 将当前局面信息编码成字符串
    31. // 地图#my.sx#my.sy#my操作#you.sx#you.sy#you操作
    32. Player me, you;
    33. if(playerA.getId().equals(player.getId())) {
    34. me = playerA;
    35. you = playerB;
    36. } else {
    37. me = playerB;
    38. you = playerA;
    39. }
    40. return getMapString() + "#" +
    41. me.getSx() + "#" +
    42. me.getSy() + "#(" +
    43. me.getStepsString() + ")#" + // 加()是为了预防操作序列为空
    44. you.getSx() + "#" +
    45. you.getSy() + "#(" +
    46. you.getStepsString() + ")";
    47. }
    48. private void sendBotCode(Player player) {
    49. if(player.getBotId().equals(-1)) return;
    50. MultiValueMap data = new LinkedMultiValueMap<>();
    51. data.add("user_id", player.getId().toString());
    52. data.add("bot_code", player.getBotCode());
    53. data.add("input", getInput(player));
    54. WebSocketServer.restTemplate.postForObject(addBotUrl, data, String.class);
    55. }
    56. // 接收玩家的下一步操作
    57. private boolean nextStep() {
    58. // 每秒五步操作,因此第一步操作是在200ms后判断是否接收到输入。
    59. try {
    60. Thread.sleep(200);
    61. } catch (InterruptedException e) {
    62. throw new RuntimeException(e);
    63. }
    64. sendBotCode(playerA);
    65. sendBotCode(playerB);
    66. ...
    67. }
    68. ...
    69. }

    BotRunning System的实现

     

    思路:

    评测器是一个经典的生产者消费者模型,此服务生产者会将任务放进一个队列中,
    消费者是单独的一个线程,当有任务就会从队头立即执行;并且关键问题是评测
    器的执行代码不能单纯的用sleep 1s去判断是否有任务,这样很影响评测体验,
    因此需要用到Condition Variable,当有任务执行,无任务等待。

    文件结构

     matchingsystem
        service
            impl
                utils
                    Bot.java
                    BotPool.java
                    Consumer.java
        utils
            Bot.java
            BotInterface.java

    Bot的实现

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Bot {
    5. Integer userId;
    6. String botCode;
    7. String input;
    8. }

     

    BotPoll的实现

    虽然队列没用消息队列,但是因为我们写了条件变量与锁的操作,所以等价于消息队列

    1. public class BotPool extends Thread {
    2. // 以下的锁和条件变量加不加static都可以,因为BotPool只有一个
    3. private final ReentrantLock lock = new ReentrantLock();
    4. private final Condition condition = lock.newCondition();
    5. private final Queue bots = new LinkedList<>();
    6. public void addBot(Integer userId, String botCode, String input) {
    7. lock.lock();
    8. try {
    9. bots.add(new Bot(userId, botCode, input));
    10. condition.signalAll();
    11. } finally {
    12. lock.unlock();
    13. }
    14. }
    15. private void consume(Bot bot) {
    16. }
    17. @Override
    18. public void run() {
    19. while(true) {
    20. lock.lock();
    21. if(bots.isEmpty()) {
    22. try {
    23. // 若执行了await会自动释放锁
    24. condition.await();
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. lock.unlock();
    28. break;
    29. }
    30. } else {
    31. Bot bot = bots.remove();
    32. lock.unlock();
    33. // 耗时操作,因此要在释放锁之后执行
    34. consume(bot);
    35. }
    36. }
    37. }

    BotRunningServiceImpl.java

    加任务

    1. @Service
    2. public class BotRunningServiceImpl implements BotRunningService {
    3. public static final BotPool botPool = new BotPool();
    4. @Override
    5. public String addBot(Integer userId, String botCode, String input) {
    6. System.out.println("add bot: " + userId + " " + botCode + " " + input);
    7. botPool.addBot(userId, botCode, input);
    8. return "add bot success";
    9. }
    10. }

     BotPool线程的启动

    1. @SpringBootApplication
    2. public class BotRunningSystemApplication {
    3. public static void main(String[] args) {
    4. BotRunningServiceImpl.botPool.start();
    5. SpringApplication.run(BotRunningSystemApplication.class, args);
    6. }
    7. }

    BotInterface.java

    用户写Bot实现的接口

    1. BotInterface.java
    2. public interface BotInterface {
    3. Integer nextMove(String input);
    4. }

    Bot.java

    1. public class Bot implements BotInterface {
    2. @Override
    3. public Integer nextMove(String input) {
    4. return 0; // 向上走
    5. }
    6. }

    Consumer的实现

    docker与沙箱分别有什么区别

    1. public class Consumer extends Thread {
    2. private Bot bot;
    3. public void startTimeout(long timeout, Bot bot) {
    4. this.bot = bot;
    5. this.start();
    6. // 在 程序运行结束后 或 程序在指定timeout时间后还未执行完毕 直接中断代码执行
    7. try {
    8. this.join(timeout);
    9. this.interrupt();
    10. } catch (InterruptedException e) {
    11. e.printStackTrace();
    12. } finally {
    13. this.interrupt();
    14. }
    15. }
    16. private String addUid(String code, String uid) { // 在code中的Bot类名后添加uid
    17. int k = code.indexOf(" implements BotInterface");
    18. return code.substring(0, k) + uid + code.substring(k);
    19. }
    20. @Override
    21. public void run() {
    22. UUID uuid = UUID.randomUUID();
    23. String uid = uuid.toString().substring(0, 8);
    24. BotInterface botInterface = Reflect.compile(
    25. "com.kob.botrunningsystem.utils.Bot" + uid,
    26. addUid(bot.getBotCode(), uid)
    27. ).create().get();
    28. Integer direction = botInterface.nextMove(bot.getInput());
    29. System.out.println("move-direction: " + bot.getUserId() + " " + direction);
    30. }
    31. }

    调用Consumer

    1. public class BotPool extends Thread {
    2. ...
    3. private void consume(Bot bot) {
    4. Consumer consumer = new Consumer();
    5. consumer.startTimeout(2000, bot);
    6. }
    7. ...
    8. }

    前端Bug的修改

    在游戏结束后,点到其他页面再点回pk页面,结果没有消失

    1. PkIndexView.vue

    将Bot执行结果传给前端

    BackEnd接收Bot代码的结果

    文件结构

    backend
        controller
            pk
                ReceiveBotMoveController.java
        service
            impl
                pk
                    ReceiveBotMoveServiceImpl.java
            pk
                ReceiveBotMoveService.java
     

    接口

    1. public interface ReceiveBotMoveService {
    2. String receiveBotMove(Integer userId, Integer direction);
    3. }

     WebSocketServer操作类

    将game改为public

    1. ...
    2. @Component
    3. // url链接:ws://127.0.0.1:3000/websocket/**
    4. @ServerEndpoint("/websocket/{token}") // 注意不要以'/'结尾
    5. public class WebSocketServer {
    6. ...
    7. public Game game = null;
    8. ...
    9. }

    接口实现

    1. @Service
    2. public class ReceiveBotMoveServiceImpl implements ReceiveBotMoveService {
    3. @Override
    4. public String receiveBotMove(Integer userId, Integer direction) {
    5. System.out.println("receive bot move: " + userId + " " + direction + " ");
    6. if(WebSocketServer.users.get(userId) != null) {
    7. Game game = WebSocketServer.users.get(userId).game;
    8. if(game != null) {
    9. if(game.getPlayerA().getId().equals(userId)) {
    10. game.setNextStepA(direction);
    11. } else if(game.getPlayerB().getId().equals(userId)) {
    12. game.setNextStepB(direction);
    13. }
    14. }
    15. }
    16. return "receive bot move success";
    17. }
    18. }

    控制器

    1. @RestController
    2. public class ReceiveBotMoveController {
    3. @Autowired
    4. private ReceiveBotMoveService receiveBotMoveService;
    5. @PostMapping("/pk/receive/bot/move/")
    6. public String receiveBotMove(@RequestParam MultiValueMap data) {
    7. Integer userId = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));
    8. Integer direction = Integer.parseInt(Objects.requireNonNull(data.getFirst("direction")));
    9. return receiveBotMoveService.receiveBotMove(userId, direction);
    10. }
    11. }

    权限控制(网关)

    放行接口

    1. @Configuration
    2. @EnableWebSecurity
    3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    4. ...
    5. @Override
    6. protected void configure(HttpSecurity http) throws Exception {
    7. http.csrf().disable()
    8. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    9. .and()
    10. .authorizeRequests()
    11. // 放行这两个接口
    12. .antMatchers("/user/account/token/", "/user/account/register/", "/getKaptcha").permitAll()
    13. .antMatchers("/pk/start/game/", "/pk/receive/bot/move/").hasIpAddress("127.0.0.1")
    14. .antMatchers(HttpMethod.OPTIONS).permitAll()
    15. .anyRequest().authenticated();
    16. http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    17. }
    18. ...
    19. }

    BotRunningSystem返回Bot执行结果

    Consumer.java

    1. package com.kill9.botsystem.service.impl.utils;
    2. import com.kill9.botsystem.utils.BotInterface;
    3. import org.joor.Reflect;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Component;
    6. import org.springframework.util.LinkedMultiValueMap;
    7. import org.springframework.util.MultiValueMap;
    8. import org.springframework.web.client.RestTemplate;
    9. import java.util.UUID;
    10. @Component
    11. public class Consumer extends Thread{
    12. private Bot bot;
    13. private static RestTemplate restTemplate;
    14. private final static String receiveBotMoveUrl = "http://127.0.0.1:3000/pk/receive/bot/move";
    15. @Autowired
    16. public void setRestTemplate(RestTemplate restTemplate){
    17. Consumer.restTemplate = restTemplate;
    18. }
    19. public void startTimeOut(long timeout,Bot bot) {
    20. this.bot = bot;
    21. //开一个新的线程去执行run
    22. this.start();
    23. //当前线程继续执行join ,等待时间超过timeout
    24. try{
    25. this.join(timeout);
    26. }catch (InterruptedException e){
    27. e.printStackTrace();
    28. }finally {
    29. this.interrupt();//中断当前线程
    30. }
    31. }
    32. private String addUid(String code,String uid){
    33. //在code中的Bot类名 后添加Uid
    34. int k = code.indexOf(" implements com.kill9.botsystem.utils.BotInterface");
    35. return code.substring(0,k)+uid+code.substring(k);
    36. }
    37. @Override
    38. public void run() {
    39. //动态编译一个代码 如果类重名的话,只会编译一次 ,为了能够让类名不一样 + uuid
    40. UUID uuid = UUID.randomUUID();
    41. //前8位
    42. String uid = uuid.toString().substring(0,8);
    43. BotInterface botInterface = Reflect.compile(
    44. "com.kill9.botsystem.utils.Bot"+uid,
    45. addUid(bot.getBotCode(), uid)
    46. ).create().get();
    47. Integer direction = botInterface.nextMove(bot.getInput());
    48. System.out.println("move-d:" + bot.getUserId() + " "+ direction);
    49. MultiValueMap data = new LinkedMultiValueMap<>();
    50. data.add("user_id",bot.getUserId().toString());
    51. data.add("direction",direction.toString());
    52. //结果返回给backend服务器
    53. restTemplate.postForObject(receiveBotMoveUrl,data,String.class);
    54. }
    55. }

     

    厉害的bot代码:

    1. public class Bot implements BotInterface {
    2. static class Cell {
    3. public int x, y;
    4. public Cell(int x, int y) {
    5. this.x = x;
    6. this.y = y;
    7. }
    8. }
    9. // 检查当前回合,蛇的长度是否会增加
    10. private boolean check_tail_increasing(int step) {
    11. if(step <= 10) return true;
    12. return step % 3 == 1;
    13. }
    14. public List getCells(int sx, int sy, String steps) {
    15. steps = steps.substring(1, steps.length() - 1);
    16. List res = new ArrayList<>();
    17. int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
    18. int x = sx, y = sy;
    19. int step = 0;
    20. res.add(new Cell(x, y));
    21. for(int i = 0; i < steps.length(); i++) {
    22. int d = steps.charAt(i) - '0';
    23. x += dx[d];
    24. y += dy[d];
    25. res.add(new Cell(x, y));
    26. if(!check_tail_increasing(++step)) {
    27. res.remove(0);
    28. }
    29. }
    30. return res;
    31. }
    32. @Override
    33. public Integer nextMove(String input) {
    34. // 地图#my.sx#my.sy#(my操作)#you.sx#you.sy#(you操作)
    35. String[] strs = input.split("#");
    36. int[][] g = new int[13][14];
    37. for(int i = 0, k = 0; i < 13; i++) {
    38. for(int j = 0; j < 14; j++, k++) {
    39. if(strs[0].charAt(k) == '1') {
    40. g[i][j] = 1;
    41. }
    42. }
    43. }
    44. int aSx = Integer.parseInt(strs[1]), aSy = Integer.parseInt(strs[2]);
    45. int bSx = Integer.parseInt(strs[4]), bSy = Integer.parseInt(strs[5]);
    46. List aCells = getCells(aSx, aSy, strs[3]);
    47. List bCells = getCells(bSx, bSy, strs[6]);
    48. for(Cell c : aCells) g[c.x][c.y] = 1;
    49. for(Cell c : bCells) g[c.x][c.y] = 1;
    50. int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
    51. for(int i = 0; i < 4; i++) {
    52. int x = aCells.get(aCells.size() - 1).x + dx[i];
    53. int y = aCells.get(aCells.size() - 1).y + dy[i];
    54. if(x >= 0 && x < 13 && y >= 0 && y < 14 && g[x][y] == 0) {
    55. return i;
    56. }
    57. }
    58. return 0;
    59. }
    60. }

  • 相关阅读:
    (一). 贝叶斯滤波器
    【前端设计模式】之原型模式
    【LeetCode热题100】--73.矩阵置零
    LIN总线帧结构及各场干扰 上
    折半搜索-oier复健练习题目
    企业微信代开发应用登录操作
    Python的常用排序算法实现
    在Linux上安装RStudio工具并实现本地远程访问【内网穿透】
    拖拽(高度自定义)
    µC/OS-II---两个系统任务
  • 原文地址:https://blog.csdn.net/weixin_49884716/article/details/127970775