version-2.4[实现微服务执行Bot代码]

pull/1/head
dyh 3 years ago
parent 371e68cfdd
commit 1044fa0ff6

@ -41,7 +41,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.and()
.authorizeRequests()
.antMatchers("/user/account/token/", "/user/account/register/").permitAll()
.antMatchers("/pk/start/game/").hasIpAddress("127.0.0.1")
.antMatchers("/pk/start/game/","/pk/receive/bot/move/").hasIpAddress("127.0.0.1")
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();

@ -4,8 +4,10 @@ package com.kob.backend.consumer;
import com.alibaba.fastjson.JSONObject;
import com.kob.backend.consumer.utils.Game;
import com.kob.backend.consumer.utils.JwtAuthentication;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -17,9 +19,7 @@ import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{token}") // 注意不要以'/'结尾
@ -33,11 +33,12 @@ public class WebSocketServer {
//session维护链接
private Session session = null ;
//地图
private Game game ;
public Game game ;
//加入数据库
private static UserMapper userMapper;
public static RecordMapper recordMapper;
private static RestTemplate restTemplate;
public static RestTemplate restTemplate;
public static BotMapper botMapper;
@Autowired
public void setUserMapper(UserMapper userMapper){
WebSocketServer.userMapper = userMapper;
@ -46,6 +47,8 @@ public class WebSocketServer {
public void setRecordMapper(RecordMapper recordMapper) { WebSocketServer.recordMapper = recordMapper;}
@Autowired
public void setRestTemplate(RestTemplate restTemplate){ WebSocketServer.restTemplate = restTemplate ;}
@Autowired
public void setBotMapper(BotMapper botMapper){ WebSocketServer.botMapper = botMapper; }
private static final String addPlayerUrl = "http://127.0.0.1:3001/player/add/";
private static final String removePlayerUrl = "http://127.0.0.1:3001/player/remove/";
@ -70,19 +73,27 @@ public class WebSocketServer {
@OnClose
public void onClose() {
// 关闭链接
System.out.println("disconnexted!");
System.out.println("disconnected!");
if(this.user != null){
users.remove(this.user.getId());
}
}
//封装向前端传地图,操作等信息(匹配成功后调用)
public static void startGame(Integer aId,Integer bId){
public static void startGame(Integer aId,Integer aBotId,Integer bId,Integer bBotId){
User a =userMapper.selectById(aId),b = userMapper.selectById(bId);
Bot botA = botMapper.selectById(aBotId),botB = botMapper.selectById(bBotId);
//一局游戏的线程
Game game =new Game(13,14,20,a.getId(),b.getId());
Game game =new Game(
13,
14,
20,
a.getId(),
botA,
b.getId(),
botB
);
game.createMap();
//a,b共同的地图==>将地图赋给a,b对应的连接
if(users.get(a.getId()) != null)
@ -119,12 +130,13 @@ public class WebSocketServer {
}
//前端点击 开始匹配 触发--》加入一个用户进行匹配--->发送请求给matchingsystem
private void startMatching(){
private void startMatching(Integer botId){
System.out.println("start matching!");
//向另一个Spring Boot发送的数据
MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
data.add("user_id",this.user.getId().toString());
data.add("rating",this.user.getRating().toString());
data.add("bot_id", botId.toString());
restTemplate.postForObject(addPlayerUrl, data, String.class);
}
@ -136,11 +148,13 @@ public class WebSocketServer {
restTemplate.postForObject(removePlayerUrl,data,String.class);
}
public void move(int dirction){
public void move(int direction){
if(game.getPlayerA().getId().equals(user.getId())){//当前链接是A用户
game.setNextStepA(dirction);
if(game.getPlayerA().getBotId().equals(-1))//亲自出马--》当是AI时屏蔽玩家键盘输入
game.setNextStepA(direction);
} else if(game.getPlayerB().getId().equals(user.getId())){//当前链接是B用户
game.setNextStepB(dirction);
if(game.getPlayerB().getBotId().equals(-1))//亲自出马
game.setNextStepB(direction);
}
}
@ -151,7 +165,7 @@ public class WebSocketServer {
JSONObject data = JSONObject.parseObject(message);//解析message
String event = data.getString("event");//类似map
if("start-matching".equals(event)){
startMatching();
startMatching(data.getInteger("bot_id"));
} else if("stop-matching".equals(event)){
stopMatching();
} else if("move".equals(event)){

@ -2,7 +2,11 @@ package com.kob.backend.consumer.utils;
import com.alibaba.fastjson.JSONObject;
import com.kob.backend.consumer.WebSocketServer;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.Record;
import org.springframework.security.core.parameters.P;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.ArrayList;
import java.util.Date;
@ -26,15 +30,33 @@ public class Game extends Thread {
private String status = "playing";//playing-->finished
private String loser = "" ;//all平局AA输B:B输
public Game(Integer rows, Integer cols, Integer inner_walls_count,Integer idA, Integer idB) {
private final static String addBotUrl = "http://127.0.0.1:3002/bot/add/";
public Game(
Integer rows,
Integer cols,
Integer inner_walls_count,
Integer idA,
Bot botA,
Integer idB,
Bot botB
) {
this.rows = rows;
this.cols = cols;
this.inner_walls_count = inner_walls_count;
this.g = new int[rows][cols];
playerA = new Player(idA,this.rows - 2, 1, new ArrayList<>());
playerB = new Player(idB,1, this.cols - 2, new ArrayList<>());
Integer botIdA = -1,botIdB = -1;
String botCodeA = "",botCodeB = "";
if(botA != null){
botIdA = botA.getId();
botCodeA = botA.getContent();
}
if(botB != null){
botIdB = botB.getId();
botCodeB = botB.getContent();
}
playerA = new Player(idA,botIdA,botCodeA,this.rows - 2, 1, new ArrayList<>());
playerB = new Player(idB,botIdB,botCodeB,1, this.cols - 2, new ArrayList<>());
}
public Player getPlayerA(){
@ -143,7 +165,33 @@ public class Game extends Thread {
}
}
//获得input
private String getInput(Player player){
Player me,you ;
if(playerA.getId().equals(player.getId())){
me = playerA ;
you = playerB ;
} else {
me = playerB ;
you = playerA ;
}
return getMapString() + "#" +
me.getSx() + "#" +
me.getSy() + "#(" +
me.getStepsString() + ")#" +
you.getSx() + "#" +
you.getSy() + "#(" +
you.getStepsString() + ")" ;
}
private void sendBotCode(Player player){
if(player.getBotId().equals(-1)) return ;//亲自出马
MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
data.add("user_id",player.getId().toString());
data.add("bot_code",player.getBotCode());
data.add("input",getInput(player));
WebSocketServer.restTemplate.postForObject(addBotUrl,data,String.class);
}
private boolean nextStep(){//两名玩家的下一步
try {
@ -152,6 +200,11 @@ public class Game extends Thread {
e.printStackTrace();
}
sendBotCode(playerA);
sendBotCode(playerB);
//超时5s判断
for(int i = 1; i <= 50;i ++)
{
@ -288,7 +341,7 @@ public class Game extends Thread {
judge();//是否合法
if(this.status.equals("playing")){
sendMove();
} else if(this.status.equals("finished")){
} else {
sendResult();
break;//结束
}

@ -12,6 +12,8 @@ import java.util.List;
@AllArgsConstructor
public class Player {
private Integer id;
private Integer botId;//-1亲自出战
private String botCode;//代码
//起点
private Integer sx;
private Integer sy;

@ -1,22 +0,0 @@
package com.kob.backend.controller.pk;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/pk/")
public class BotInfoController {
@RequestMapping("getbotinfo/")
public Map<String, String> getBotInfor()
{
Map<String, String> bot1 = new HashMap<>();
bot1.put("name", "apple");
bot1.put("rating", "1500");
return bot1;
}
}

@ -1,14 +0,0 @@
package com.kob.backend.controller.pk;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping( "/")
public String index()
{
return "pk/index.html";
}
}

@ -0,0 +1,23 @@
package com.kob.backend.controller.pk;
import com.kob.backend.service.pk.ReceiveBotMoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
@RestController
public class ReceiveBotMoveController {
@Autowired
private ReceiveBotMoveService receiveBotMoveService;
@PostMapping("/pk/receive/bot/move/")
public String receiveBotMove(@RequestParam MultiValueMap<String,String> data){
Integer userId = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));
Integer direction = Integer.parseInt(Objects.requireNonNull(data.getFirst("direction")));
return receiveBotMoveService.receiveBotMove(userId,direction);
}
}

@ -15,9 +15,11 @@ public class StartGameController {
private StartGameService startGameService;
@PostMapping("/pk/start/game/")
public String StartGame(@RequestParam MultiValueMap<String,String> data){
public String startGame(@RequestParam MultiValueMap<String,String> data){
Integer aId = Integer.parseInt(Objects.requireNonNull(data.getFirst("a_id")));
Integer aBotId = Integer.parseInt(Objects.requireNonNull(data.getFirst("a_bot_id")));
Integer bId = Integer.parseInt(Objects.requireNonNull(data.getFirst("b_id")));
return startGameService.startGame(aId,bId);
Integer bBotId = Integer.parseInt(Objects.requireNonNull(data.getFirst("b_bot_id")));
return startGameService.startGame(aId,aBotId,bId,bBotId);
}
}

@ -0,0 +1,26 @@
package com.kob.backend.service.impl.pk;
import com.kob.backend.consumer.WebSocketServer;
import com.kob.backend.consumer.utils.Game;
import com.kob.backend.service.pk.ReceiveBotMoveService;
import org.springframework.stereotype.Service;
@Service
public class ReceiveBotMoveServiceImpl implements ReceiveBotMoveService {
@Override
public String receiveBotMove(Integer userId, Integer direction) {
System.out.println("receive bot move: " + userId + " " +direction);
if(WebSocketServer.users.get(userId)!=null){
Game game = WebSocketServer.users.get(userId).game;
if(game != null){
if(game.getPlayerA().getId().equals(userId)){//当前链接是A用户
game.setNextStepA(direction);
} else if(game.getPlayerB().getId().equals(userId)){//当前链接是B用户
game.setNextStepB(direction);
}
}
}
return "receive bot move success";
}
}

@ -7,9 +7,9 @@ import org.springframework.stereotype.Service;
@Service
public class StartGameServiceImpl implements StartGameService {
@Override
public String startGame(Integer aId, Integer bId) {
public String startGame(Integer aId,Integer aBotId ,Integer bId,Integer bBotId) {
System.out.println("start game: "+ aId+" "+bId);
WebSocketServer.startGame(aId,bId);
WebSocketServer.startGame(aId,aBotId,bId,bBotId);
return "start game success";
}
}

@ -1,4 +1,4 @@
package com.kob.backend.service.impl.bot;
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;

@ -1,4 +1,4 @@
package com.kob.backend.service.impl.bot;
package com.kob.backend.service.impl.user.bot;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;

@ -1,4 +1,4 @@
package com.kob.backend.service.impl.bot;
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;

@ -1,4 +1,4 @@
package com.kob.backend.service.impl.bot;
package com.kob.backend.service.impl.user.bot;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;

@ -0,0 +1,5 @@
package com.kob.backend.service.pk;
public interface ReceiveBotMoveService {
public String receiveBotMove(Integer userId,Integer direction);
}

@ -1,5 +1,5 @@
package com.kob.backend.service.pk;
public interface StartGameService {
public String startGame(Integer aId,Integer bId);
public String startGame(Integer aId,Integer aBotId,Integer bId,Integer bBotId);
}

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>backendcloud</artifactId>
<groupId>com.kob</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>botrunningsystem</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>joor-java-8</artifactId>
<version>0.9.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.7.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

@ -0,0 +1,14 @@
package com.kob.botrunningsystem;
import com.kob.botrunningsystem.service.impl.BotRunningServiceImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BotRunningSystemApplication {
public static void main(String[] args) {
BotRunningServiceImpl.botPool.start();//启动线程
SpringApplication.run(BotRunningSystemApplication.class,args);
}
}

@ -0,0 +1,13 @@
package com.kob.botrunningsystem.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}

@ -0,0 +1,23 @@
package com.kob.botrunningsystem.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/bot/add/").hasIpAddress("127.0.0.1")//新加
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();
}
}

@ -0,0 +1,24 @@
package com.kob.botrunningsystem.controller;
import com.kob.botrunningsystem.service.BotRunningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
@RestController
public class BotRunningController {
@Autowired
private BotRunningService botRunningService;
@PostMapping("/bot/add/")
public String addBot(@RequestParam MultiValueMap<String,String> data){
Integer userId = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));
String botCode = data.getFirst("bot_code");
String input = data.getFirst("input");
return botRunningService.addBot(userId,botCode,input);
}
}

@ -0,0 +1,5 @@
package com.kob.botrunningsystem.service;
public interface BotRunningService {
public String addBot(Integer userId,String botCode,String input);
}

@ -0,0 +1,18 @@
package com.kob.botrunningsystem.service.impl;
import com.kob.botrunningsystem.service.BotRunningService;
import com.kob.botrunningsystem.service.impl.utils.BotPool;
import org.springframework.stereotype.Service;
@Service
public class BotRunningServiceImpl implements BotRunningService {
public final static BotPool botPool = new BotPool();
@Override
public String addBot(Integer userId, String botCode, String input) {
// System.out.println("add bot: " + userId + " " + botCode + " " + input);
botPool.addBot(userId,botCode,input);
return "add bot success";
}
}

@ -0,0 +1,14 @@
package com.kob.botrunningsystem.service.impl.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bot {
private Integer userId;
private String botCode;
private String input;
}

@ -0,0 +1,50 @@
package com.kob.botrunningsystem.service.impl.utils;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BotPool extends Thread{
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();//条件变量
private final Queue<Bot> bots = new LinkedList<>();//消息队列-->add,remove-->锁
//添加一个任务-Bot
public void addBot(Integer userId,String botCode,String input){
lock.lock();//涉及到bots
try {
bots.add(new Bot(userId,botCode,input));
condition.signalAll();
} finally {
lock.unlock();
}
}
//消费一个任务
private void consume(Bot bot){
Consumer consumer = new Consumer();
consumer.startTimeout(2000,bot);
}
@Override
public void run() {
while (true){
lock.lock();
if(bots.isEmpty()){//空
try {
condition.await();//【消息队列空】阻塞当前线程,直到被唤醒(默认包含解锁)
} catch (InterruptedException e) {
e.printStackTrace();
lock.unlock();
break;
}
} else {
Bot bot = bots.remove();//取出当前任务+移除
lock.unlock();
consume(bot);//消耗任务,用时长,执行代码
}
}
}
}

@ -0,0 +1,65 @@
package com.kob.botrunningsystem.service.impl.utils;
import com.kob.botrunningsystem.utils.BotInterface;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.UUID;
@Component
public class Consumer extends Thread{
private static RestTemplate restTemplate ;
@Autowired
public void setRestTemplate(RestTemplate restTemplate){
Consumer.restTemplate = restTemplate;
}
private Bot bot;
private final static String receiveBotMoveUrl = "http://127.0.0.1:3000/pk/receive/bot/move/";
public void startTimeout(long timeout,Bot bot){
this.bot = bot;
this.start();
try {
this.join(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
this.interrupt();
}
}
private String addUid(String code,String uid){
int k = code.indexOf(" implements BotInterface");
return code.substring(0,k) + uid +code.substring(k);
}
@Override
public void run() {
UUID uuid = UUID.randomUUID();
String uid = uuid.toString().substring(0,8);
BotInterface botInterface = Reflect.compile(
"com.kob.botrunningsystem.utils.Bot" + uid,
addUid(bot.getBotCode(),uid)
).create().get();
Integer direction = botInterface.nextMove(bot.getInput());
System.out.println("move-direction: " + bot.getUserId() + " " + direction);
MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
data.add("user_id",bot.getUserId().toString());
data.add("direction",direction.toString());
restTemplate.postForObject(receiveBotMoveUrl,data,String.class);
}
}

@ -0,0 +1,8 @@
package com.kob.botrunningsystem.utils;
public class Bot implements com.kob.botrunningsystem.utils.BotInterface {
@Override
public Integer nextMove(String input) {
return 0;
}
}

@ -0,0 +1,5 @@
package com.kob.botrunningsystem.utils;
public interface BotInterface {
public Integer nextMove(String input);//下一步方向
}

@ -1,8 +1,6 @@
package com.kob.matchingsystem.controller;
import com.kob.matchingsystem.service.MatchingService;
import com.kob.matchingsystem.service.impl.MatchingServiceImpl;
import com.kob.matchingsystem.service.impl.utils.MatchingPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
@ -20,7 +18,8 @@ public class MatchingController {
public String addPlayer(@RequestParam MultiValueMap<String,String> data){
Integer userId = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));
Integer rating = Integer.parseInt(Objects.requireNonNull(data.getFirst("rating")));
return matchingService.addPlayer(userId,rating);
Integer botId = Integer.parseInt(Objects.requireNonNull(data.getFirst("bot_id")));
return matchingService.addPlayer(userId,rating,botId);
}
@PostMapping("/player/remove/")

@ -1,6 +1,6 @@
package com.kob.matchingsystem.service;
public interface MatchingService {
public String addPlayer(Integer userId,Integer rating);
public String addPlayer(Integer userId,Integer rating,Integer botId);
public String removePlayer(Integer userId);
}

@ -7,12 +7,12 @@ import org.springframework.stereotype.Service;
@Service
public class MatchingServiceImpl implements MatchingService {
//就一个线程
public static final MatchingPool matchingPool = new MatchingPool();
public final static MatchingPool matchingPool = new MatchingPool();
@Override
public String addPlayer(Integer userId, Integer rating) {
System.out.println("add player: "+userId+" "+rating);
matchingPool.addPlayer(userId,rating);
public String addPlayer(Integer userId, Integer rating,Integer botId) {
System.out.println("add player: "+userId+" "+rating+" "+botId);
matchingPool.addPlayer(userId,rating,botId);
return "add player success";
}

@ -24,10 +24,10 @@ public class MatchingPool extends Thread {
//两个线程访问1.匹配线程 2.传入参数的线程,开始匹配
public void addPlayer(Integer userId,Integer rating){
public void addPlayer(Integer userId,Integer rating,Integer botId){
lock.lock();
try {
players.add(new Player(userId,rating,0));
players.add(new Player(userId,rating,botId,0));
} finally {
lock.unlock();
}
@ -44,7 +44,7 @@ public class MatchingPool extends Thread {
}
players = newPlayers ;
} finally {
lock.lock();
lock.unlock();
}
}
@ -54,7 +54,7 @@ public class MatchingPool extends Thread {
}
}
private void matcingPlayers(){//匹配所有玩家
private void matchPlayers(){//匹配所有玩家
System.out.println("match players: "+players.toString());
boolean[] used = new boolean[players.size()];
for(int i = 0 ; i < players.size() ; i++){
@ -89,8 +89,10 @@ public class MatchingPool extends Thread {
private void sendResult(Player a,Player b){
System.out.println("send result: " + a + " " + b);
MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
data.put("a_id", Collections.singletonList(a.getUserId().toString()));
data.put("b_id", Collections.singletonList(b.getUserId().toString()));
data.add("a_id", a.getUserId().toString());
data.add("a_bot_id", a.getBotId().toString());
data.add("b_id", b.getUserId().toString());
data.add("b_bot_id",b.getBotId().toString());
restTemplate.postForObject(startGameUrl,data,String.class);
}
@ -102,13 +104,14 @@ public class MatchingPool extends Thread {
lock.lock();
try {
increaseWaitingTime();
matcingPlayers();
matchPlayers();
} finally {
lock.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
}

@ -10,5 +10,6 @@ import lombok.NoArgsConstructor;
public class Player {
private Integer userId;
private Integer rating;
private Integer botId;
private Integer waitingTime;//等待时间
}

@ -9,6 +9,7 @@
<modules>
<module>matchingsystem</module>
<module>backend</module>
<module>botrunningsystem</module>
</modules>
<name>backendcloud</name>
<description>backendcloud</description>

@ -3,7 +3,7 @@
<div class="row">
<!-- 自己 -->
<div class="col-6">
<div class="col-4">
<div class="user-photo">
<img :src="$store.state.user.photo" alt="">
</div>
@ -11,9 +11,17 @@
{{$store.state.user.username}}
</div>
</div>
<!-- 选择Bot -->
<div class="col-4">
<div class="user-select-bot">
<select class="form-select" aria-label="Default select example" v-model="select_bot">
<option value="-1" selected>亲自出马</option>
<option v-for="bot in bots" :key="bot.id" :value="bot.id">{{ bot.title }}</option>
</select>
</div>
</div>
<!-- 对手 -->
<div class="col-6">
<div class="col-4">
<div class="user-photo">
<img :src="$store.state.pk.opponent_photo" alt="">
</div>
@ -33,19 +41,23 @@
<script>
import { ref } from "vue"
import { useStore } from "vuex"
import $ from "jquery"
export default {
setup(){
const store = useStore();
let match_btn_info = ref("开始匹配")
let bots = ref([])
let select_bot = ref(-1)
const click_match_btn = ( )=>{
if(match_btn_info.value === "开始匹配"){
match_btn_info.value = "取消";
console.log(select_bot.value);
//
store.state.pk.socket.send(JSON.stringify({
event:"start-matching",
bot_id: select_bot.value,
}));
} else if(match_btn_info.value === "取消"){
match_btn_info.value = "开始匹配";
@ -56,9 +68,25 @@ export default {
}
}
const refresh_bots = () => {
$.ajax({
url: "http://127.0.0.1:3000/user/bot/getlist/",
type: "get",
headers: {
'Authorization': "Bearer " + store.state.user.token,
},
success(resp) {
bots.value = resp;
}
})
};
refresh_bots();
return {
match_btn_info,
click_match_btn,
bots,
select_bot,
}
}
}
@ -87,6 +115,12 @@ div.user-username {
color: white;
margin-top: 2vh;
}
div.user-select-bot {
padding-top: 20vh;
}
div.user-select-bot > select {
width: 60%;
margin: 0 auto;
}
</style>

@ -31,6 +31,7 @@ export default {
const store = useStore();
const restart = () => {
store.commit("updateStatus","matching");
store.commit("updateLoser","none");
store.commit("updateOpponent",{

@ -1,7 +1,7 @@
<template>
<PlayGround v-if="$store.state.pk.status === 'playing'"></PlayGround>
<MatchGround v-if="$store.state.pk.status === 'matching'"></MatchGround>
<ResultBoard v-if="$store.state.pk.loser !== 'none'"/>
<ResultBoard v-if="$store.state.pk.loser != 'none'"/>
</template>
<script>
@ -25,7 +25,7 @@ export default {
const socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;
let socket = null;
store.commit("updateLoser","none");
onMounted(()=>{
socket = new WebSocket(socketUrl);//Js
@ -91,6 +91,7 @@ export default {
onUnmounted(()=>{
socket.close();
store.commit("updateStatus", "matching");
})
}

Loading…
Cancel
Save