Java 实现小游戏双人匹配机制

博主介绍:小黄鸭技术

擅长领域:Java、实用工具、运维

系列专栏:开发工具 Java之路 八股文之路

如果文章写作时有错误的地方,请各位大佬指正,一起进步!!!

欢迎大家点赞➕收藏⭐➕评论支持博主                          

采用队列Queue和线程Thread扫描的方式找出玩家匹配组队,只提供一个思路,实际业务逻辑和代码强壮度需要看具体业务逻辑和测试结果。

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.Queue;


/**
 * 实现匹配器匹配功能 利用Spring启动时注入Bean开始扫描队列
 *
 * @author 
 * @date 2022-11-02 13:11
 */
@Component
@Log4j2
public class Matcher {
    
    //匹配队列
    private final Queue firstQueue = new LinkedList<>();
    //匹配队列
    private final Queue secondQueue = new LinkedList<>();
    //匹配队列
    private final Queue thirdQueue = new LinkedList<>();


    // 把玩家放到匹配队列中
    public void add(Integer userId, Integer type) {
        //按照不同类型进行分组
        if (type == 1) {
            synchronized (firstQueue) {
                firstQueue.offer(userId);
                firstQueue.notify();
            }
            log.info("把玩家 " + userId+ " 加入到 队列 中!");
        } else if (type == 2) {
            synchronized (secondQueue) {
                secondQueue.offer(userId);
                secondQueue.notify();
            }
            log.info("把玩家 " + userId + " 加入到 队列 中!");
        } else {
            synchronized (thirdQueue) {
                thirdQueue.offer(userId);
                thirdQueue.notify();
            }
            log.info("把玩家 " + userId + " 加入到 队列 中!");
        }
    }

    public Matcher() {
        // 创建三个线程, 分别针对这三个匹配队列, 进行操作.
        Thread t1 = new Thread(() -> {
            while (true) {
                handlerMatch(firstQueue);
            }
        });
        t1.start();

        Thread t2 = new Thread(() -> {
            while (true) {
                handlerMatch(secondQueue);
            }
        });
        t2.start();

        Thread t3 = new Thread(() -> {
            while (true) {
                handlerMatch(thirdQueue);
            }
        });
        t3.start();
    }

    private void handlerMatch(Queue matchQueue) {
        synchronized (matchQueue) {
            try {
                // 1. 检测队列中元素个数是否达到 2
                while (matchQueue.size() < 2) {
                    matchQueue.wait();
                }
                // 2. 尝试从队列中取出两个玩家
                Integer player1 = matchQueue.poll();
                Integer player2 = matchQueue.poll();
                log.info("匹配出两个玩家: " + player1 + "," + player2);
                //3.防止重复匹配到自己
                if (player1.equals(player2)){
                    matchQueue.offer(player1);
                    return;
                }
                // 4. 给玩家反馈信息: 你匹配到对手了 可以利用websocket来给前端发消息实现通知
                log.info("匹配成功");
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

}

 欢迎大家点赞➕收藏⭐➕评论支持博主   

你可能感兴趣的:(Java之路,java)