wuheng 2 gadi atpakaļ
revīzija
19dfa88b13

+ 33 - 0
.gitignore

@@ -0,0 +1,33 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/

+ 97 - 0
pom.xml

@@ -0,0 +1,97 @@
+<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>com.example</groupId>
+    <artifactId>gobang-api</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>gobang-api</name>
+    <description>gobang-api</description>
+    <properties>
+        <maven.compiler.source>11</maven.compiler.source>
+        <maven.compiler.target>11</maven.compiler.target>
+        <java.version>11</java.version>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+        <spring-boot.version>2.7.6</spring-boot.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-websocket</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2</artifactId>
+            <version>2.0.31</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>com.hexadevlabs</groupId>
+            <artifactId>gpt4all-java-binding</artifactId>
+            <version>1.1.3</version>
+        </dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-dependencies</artifactId>
+                <version>${spring-boot.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.8.1</version>
+                <configuration>
+                    <source>11</source>
+                    <target>11</target>
+                    <encoding>UTF-8</encoding>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>${spring-boot.version}</version>
+                <configuration>
+                    <mainClass>com.example.gobangapi.GobangApiApplication</mainClass>
+                    <skip>true</skip>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>repackage</id>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 16 - 0
src/main/java/com/example/gobangapi/GobangApiApplication.java

@@ -0,0 +1,16 @@
+package com.example.gobangapi;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.scheduling.annotation.EnableScheduling;
+
+@SpringBootApplication
+@EnableScheduling
+public class GobangApiApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(GobangApiApplication.class, args);
+    }
+
+}

+ 8 - 0
src/main/java/com/example/gobangapi/config/Constant.java

@@ -0,0 +1,8 @@
+package com.example.gobangapi.config;
+
+public class Constant {
+    public static final String HALL = "hall";
+    public static final String ROOM = "room";
+    public static final String BEGIN = "begin";
+    public static final String POINT = "point";
+}

+ 22 - 0
src/main/java/com/example/gobangapi/config/RefreshDataConfig.java

@@ -0,0 +1,22 @@
+package com.example.gobangapi.config;
+
+import com.example.gobangapi.utils.GoBangUtils;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+@Component
+public class RefreshDataConfig {
+
+    @Scheduled(cron = "0/1 * * * * ?")
+    public void room(){
+        GoBangUtils.sendRoomData();
+    }
+
+    @Scheduled(cron = "0/1 * * * * ?")
+    public void hall(){
+        GoBangUtils.sendHallData();
+    }
+}

+ 15 - 0
src/main/java/com/example/gobangapi/config/WebsocketConfig.java

@@ -0,0 +1,15 @@
+package com.example.gobangapi.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.server.standard.ServerEndpointExporter;
+
+@Configuration
+public class WebsocketConfig {
+
+    @Bean
+    public ServerEndpointExporter getEndpointExporter(){
+        return new ServerEndpointExporter();
+    }
+
+}

+ 35 - 0
src/main/java/com/example/gobangapi/controller.java

@@ -0,0 +1,35 @@
+package com.example.gobangapi;
+
+import com.example.gobangapi.utils.GoBangUtils;
+import org.springframework.stereotype.Component;
+
+import javax.websocket.*;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+
+@ServerEndpoint("/game/{username}")
+@Component
+public class controller {
+
+    @OnOpen
+    public void open(@PathParam("username") String username, Session session){
+        GoBangUtils.open( username, session );
+    }
+
+    @OnClose
+    public void close( Session session ){
+        GoBangUtils.close(session);
+    }
+
+    @OnMessage
+    public void onMsg(String message, Session session){
+        GoBangUtils.onMsg(message, session);
+    }
+
+    @OnError
+    public void onErr(Throwable throwable, Session session){
+        throwable.printStackTrace();
+        GoBangUtils.close(session);
+    }
+
+}

+ 24 - 0
src/main/java/com/example/gobangapi/doman/CheckerBoardData.java

@@ -0,0 +1,24 @@
+package com.example.gobangapi.doman;
+
+import lombok.Data;
+
+import java.util.HashMap;
+import java.util.List;
+
+@Data
+public class CheckerBoardData {
+    private List<Integer> a;
+    private List<Integer> b;
+    private List<Integer> c;
+    private List<Integer> d;
+    private List<Integer> e;
+    private List<Integer> f;
+    private List<Integer> g;
+    private List<Integer> h;
+    private List<Integer> i;
+    private List<Integer> j;
+    private List<Integer> k;
+    private List<Integer> l;
+    private List<Integer> m;
+    private List<Integer> n;
+}

+ 11 - 0
src/main/java/com/example/gobangapi/doman/GameMessage.java

@@ -0,0 +1,11 @@
+package com.example.gobangapi.doman;
+
+import lombok.Data;
+
+@Data
+public class GameMessage {
+    String instruct;
+    CheckerBoardData data;
+    GobangRoomItem room;
+    int roomId;
+}

+ 22 - 0
src/main/java/com/example/gobangapi/doman/GobangRoomItem.java

@@ -0,0 +1,22 @@
+package com.example.gobangapi.doman;
+
+import lombok.Data;
+
+import java.util.ArrayList;
+
+@Data
+public class GobangRoomItem {
+    public GobangRoomItem(int id){
+        this.setRoomId(id);
+    }
+    Integer roomId = 0;
+    Integer status = 0;
+    Integer backState = 0;
+    Integer whiteState = 0;
+    String backUsername = "";
+    String whiteUsername = "";
+    String backSessionId = null;
+    String whiteSessionId = null;
+    CheckerBoardData data = new CheckerBoardData();
+    ArrayList<String> sid = new ArrayList<>();
+}

+ 11 - 0
src/main/java/com/example/gobangapi/doman/HallMessage.java

@@ -0,0 +1,11 @@
+package com.example.gobangapi.doman;
+
+import lombok.Data;
+
+import java.util.concurrent.CopyOnWriteArrayList;
+
+@Data
+public class HallMessage {
+    String instruct;
+    CopyOnWriteArrayList<GobangRoomItem> data;
+}

+ 13 - 0
src/main/java/com/example/gobangapi/doman/UserListItem.java

@@ -0,0 +1,13 @@
+package com.example.gobangapi.doman;
+
+import lombok.Data;
+
+import javax.websocket.Session;
+
+@Data
+public class UserListItem {
+    Session session;
+    String username;
+    int roomId;
+    String position;
+}

+ 318 - 0
src/main/java/com/example/gobangapi/utils/GoBangUtils.java

@@ -0,0 +1,318 @@
+package com.example.gobangapi.utils;
+
+import com.alibaba.fastjson2.JSON;
+import com.example.gobangapi.config.Constant;
+import com.example.gobangapi.doman.GameMessage;
+import com.example.gobangapi.doman.GobangRoomItem;
+import com.example.gobangapi.doman.HallMessage;
+import com.example.gobangapi.doman.UserListItem;
+
+import javax.websocket.Session;
+import java.io.IOException;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+public class GoBangUtils {
+
+    public static List<GobangRoomItem> room = Arrays.asList(new GobangRoomItem[]{
+            new GobangRoomItem(1), new GobangRoomItem(2), new GobangRoomItem(3),
+            new GobangRoomItem(4), new GobangRoomItem(5), new GobangRoomItem(6),
+            new GobangRoomItem(7), new GobangRoomItem(8), new GobangRoomItem(9)
+    });
+    public static CopyOnWriteArrayList<GobangRoomItem> rooms = new CopyOnWriteArrayList(room);
+    public static ConcurrentHashMap<String, String> hall = new ConcurrentHashMap();
+    public static ConcurrentHashMap<String, UserListItem> userList = new ConcurrentHashMap();
+
+    /**
+     * 打开连接的时候 用户存储用户列表
+     * @param username
+     * @param session
+     */
+    public static void open(String username, Session session){
+        UserListItem userItem = userList.get(username);
+        if (Objects.isNull( userItem )) {
+            userItem = new UserListItem();
+            userItem.setUsername(username);
+            userItem.setSession(session);
+            userList.put( username, userItem );
+        } else {
+            try {
+                session.close();
+            } catch (IOException ignored) {
+                ignored.printStackTrace();
+            }
+        }
+    }
+
+    /**
+     * 关闭的时候从用户列表删除用户
+     * @param session
+     */
+    public static void close( Session session ){
+        for (String key : userList.keySet()) {
+            if ( userList.get(key).getSession().equals(session.getId()) ) {
+                try {
+                    userList.get(key).getSession().close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+                userList.remove(key);
+            }
+        }
+    }
+
+    /**
+     * 处理消息
+     * @param message
+     * @param session
+     */
+    public static void onMsg(String message, Session session){
+        GameMessage revMessage = JSON.parseObject(message, GameMessage.class);
+        switch ( revMessage.getInstruct() ) {
+            /**
+             * 用户切入大厅
+             */
+            case Constant.HALL:
+                hallpush(session);
+                HallMessage hallMessage = new HallMessage();
+                hallMessage.setData(rooms);
+                hallMessage.setInstruct(Constant.HALL);
+                sendUser(hallMessage, session);
+                break;
+            /**
+             * 用户切入房间
+             */
+            case Constant.ROOM:
+                GameMessage gameMessage = new GameMessage();
+                GobangRoomItem room = getRoom(revMessage.getRoomId());
+                if ( Objects.isNull(room) ) {
+                    System.out.println( "错误数据查不到房间:" + revMessage.getRoomId() );
+                    return;
+                }
+                roompush(session, revMessage.getRoomId());
+                gameMessage.setData(room.getData());
+                gameMessage.setRoom(room);
+                gameMessage.setInstruct(Constant.ROOM);
+                gameMessage.setRoomId(room.getRoomId());
+                sendUser(gameMessage, session);
+                break;
+            case Constant.BEGIN:
+                UserListItem user = getUser(session);
+                GobangRoomItem beginRoom = getRoom(user.getRoomId());
+                if ( (beginRoom.getBackSessionId().equals(session.getId()) ||
+                        beginRoom.getWhiteSessionId().equals(session.getId())) ) {
+
+                    if ( beginRoom.getBackSessionId().equals(session.getId()) ) {
+                        beginRoom.setBackState(2);
+                    } else if ( beginRoom.getWhiteSessionId().equals(session.getId()) ) {
+                        beginRoom.setWhiteState(2);
+                    }
+
+                    if ( beginRoom.getBackState() == 2 && beginRoom.getWhiteState() == 2 ) {
+                        if ( !beginRoom.getStatus().equals(1) ) {
+                            beginRoom.setStatus(1);
+                        }
+                    }
+
+                    beginRoom.setData(revMessage.getData() );
+
+                }
+                break;
+            case Constant.POINT:
+                UserListItem pointUser = getUser(session);
+                GobangRoomItem pointRoom = getRoom(pointUser.getRoomId());
+                if ( (pointRoom.getBackSessionId().equals(session.getId()) ||
+                        pointRoom.getWhiteSessionId().equals(session.getId())) ) {
+                    if ( pointRoom.getBackSessionId().equals(session.getId()) ) {
+                        if (pointRoom.getStatus() == 1) {
+                            pointRoom.setData(revMessage.getData());
+                        }
+                        pointRoom.setStatus(2);
+                    } else if ( pointRoom.getWhiteSessionId().equals(session.getId()) ) {
+                        if (pointRoom.getStatus() == 2) {
+                            pointRoom.setData(revMessage.getData());
+                        }
+                        pointRoom.setStatus(1);
+                    }
+                }
+                break;
+        }
+    }
+
+    /**
+     * 进入房间
+     * @param session
+     */
+    public static void roompush(Session session, int roomId){
+        GobangRoomItem room = getRoom(roomId);
+        if ( Objects.isNull(room) ) {
+            System.out.println( "错误数据查不到房间:" + roomId );
+            return;
+        }
+
+        UserListItem user = getUser(session);
+        roompop(session);
+        ArrayList<String> sids = room.getSid();
+        if ( Objects.nonNull(sids) ) {
+            sids.add(session.getId());
+        }
+        if ( Objects.isNull(room.getBackSessionId()) && Objects.nonNull(user) ) {
+            room.setBackUsername(user.getUsername());
+            room.setBackSessionId(user.getSession().getId());
+            room.setBackState(1);
+        } else if ( Objects.isNull(room.getWhiteSessionId()) && Objects.nonNull(user) ) {
+            room.setWhiteUsername(user.getUsername());
+            room.setWhiteSessionId(user.getSession().getId());
+            room.setWhiteState(1);
+        }
+        hallpop(session);
+        if ( Objects.nonNull(user) ) {
+            user.setPosition(Constant.ROOM);
+            user.setRoomId(roomId);
+        } else {
+            System.out.println( "错误用户---查不到用户:" + session.getId() );
+        }
+    }
+
+    /**
+     * 进入大厅
+     * @param session
+     */
+    public static void hallpush(Session session){
+        hall.put(session.getId(), (new Date()).toString());
+        UserListItem user = getUser(session);
+        roompop(session);
+        if ( Objects.nonNull(user) ) {
+            user.setPosition(Constant.HALL);
+            user.setRoomId(0);
+        } else {
+            System.out.println( "错误用户---查不到用户:" + session.getId() );
+        }
+    }
+
+    /**
+     * 离开房间
+     * @param session
+     */
+    private static void roompop(Session session){
+        for (GobangRoomItem room : rooms) {
+            ArrayList<String> sids = room.getSid();
+            if ( Objects.nonNull(sids) ) {
+                sids.removeIf(sid -> sid.equals(session.getId()));
+            }
+            if ( Objects.nonNull(room.getBackSessionId()) &&
+                room.getBackSessionId().equals(session.getId())) {
+                room.setBackUsername("");
+                room.setBackState(0);
+                room.setBackSessionId(null);
+                room.setStatus(0);
+            }
+            if ( Objects.nonNull(room.getWhiteSessionId()) &&
+                room.getWhiteSessionId().equals(session.getId())) {
+                room.setWhiteUsername("");
+                room.setWhiteState(0);
+                room.setWhiteSessionId(null);
+                room.setStatus(0);
+            }
+        }
+    }
+
+    /**
+     * 离开大厅
+     * @param session
+     */
+    private static void hallpop(Session session){
+        hall.remove(session.getId());
+    }
+
+    /**
+     * 发送消息
+     * @param o
+     * @param session
+     */
+    private static void sendUser( Object o, Session session){
+        try {
+            if ( Objects.isNull(session) || !session.isOpen() ) {
+                return;
+            }
+            synchronized (session.getId()) {
+                session.getBasicRemote().sendText(JSON.toJSONString(o));
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 刷新房间数据
+     */
+    public static void sendRoomData(){
+        for (GobangRoomItem item: rooms) {
+            GameMessage gameMessage = new GameMessage();
+            gameMessage.setData(item.getData());
+            gameMessage.setRoom(item);
+            gameMessage.setInstruct(Constant.ROOM);
+            gameMessage.setRoomId(item.getRoomId());
+            ArrayList<String> sids = item.getSid();
+            if ( Objects.nonNull(sids) ) {
+                for (String sid : sids) {
+                    sendUser(gameMessage, getUserBySid(sid));
+                }
+            }
+        }
+    }
+
+    /**
+     * 刷新大厅数据
+     */
+    public static void sendHallData(){
+        HallMessage hallMessage = new HallMessage();
+        for (String sid: hall.keySet() ) {
+            hallMessage.setData(rooms);
+            hallMessage.setInstruct(Constant.HALL);
+            sendUser( hallMessage, getUserBySid(sid) );
+        }
+    }
+
+    /**
+     * 根据sessionId 取Session
+     * @return
+     */
+    private static Session getUserBySid(String sid) {
+        for (Map.Entry<String, UserListItem> item : userList.entrySet()) {
+            if ( item.getValue().getSession().getId().equals(sid)) {
+                return item.getValue().getSession();
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 用户列表查找用户
+     * @param session
+     * @return
+     */
+    private static UserListItem getUser(Session session ){
+        for (String key : userList.keySet()) {
+            if ( userList.get(key).getSession().getId().equals(session.getId()) ) {
+                return userList.get(key);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 查找房间
+     * @param roomId
+     * @return
+     */
+    private static GobangRoomItem getRoom(int roomId) {
+        for (GobangRoomItem item: rooms) {
+            if ( item.getRoomId().equals(roomId) ) {
+                return item;
+            }
+        }
+        return null;
+    }
+}

+ 62 - 0
src/test/java/com/example/gobangapi/GobangApiApplicationTests.java

@@ -0,0 +1,62 @@
+package com.example.gobangapi;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.example.gobangapi.doman.GobangRoomItem;
+import com.hexadevlabs.gpt4all.LLModel;
+import org.junit.jupiter.api.Test;
+
+//@SpringBootTest
+class GobangApiApplicationTests {
+
+    @Test
+    void contextLoads() {
+
+        //String prompt = "### Human:\nWhat is the meaning of life\n### Assistant:";
+        String prompt = "Hello";
+        String modelFilePath = "C:\\baidunetdiskdownload\\ggml-gpt4all-j-v1.3-groovy.bin";
+        //String modelFilePath = "C:\\baidunetdiskdownload\\ggml-guanaco-65B_q4.bin";
+
+        try (LLModel model = new LLModel(Path.of(modelFilePath))) {
+
+            LLModel.GenerationConfig config = LLModel.config()
+                    .withNPredict(4096).build();
+            String fullGeneration = model.generate(prompt, config, true);
+            System.out.println( "fullGeneration :" + fullGeneration );
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+
+    ConcurrentHashMap<String, ArrayList<String>> map = new ConcurrentHashMap();
+
+    ArrayList<String> list1 =  new ArrayList<>( Arrays.asList(new String[]{"1", "2", "3", "4", "5"}) );
+    ArrayList<String> list2 =  new ArrayList<>( Arrays.asList(new String[]{"6", "7", "8", "9", "0"}) );
+    ArrayList<String> list3 =  new ArrayList<>( Arrays.asList(new String[]{"11", "12", "13", "14", "15"}) );
+
+    @Test
+    void t(){
+
+
+        map.put("a", list1);
+        map.put("b", list2);
+        map.put("c", list3);
+
+        for (String key : map.keySet()) {
+            ArrayList<String> item = map.get(key);
+            for (String id : item) {
+                if (id.equals("3")) {
+                    item.remove("5");
+                    System.out.println(map);
+                }
+            }
+        }
+
+    }
+
+}