123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use GatewayWorker\Lib\Gateway;
- use Illuminate\Support\Facades\Redis;
- class gamematch extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'game:match';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = '启动游戏匹配';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- public function handle()
- {
- //注册地址
- Gateway::$registerAddress = '127.0.0.1:1238';
- //循环匹配
- while (1) {
- $data = Redis::lpop('match_list');
- if(!$data){
- echo "未找到匹配\n";
- sleep(1);
- continue;
- }
- $data = json_decode($data, 1);
- $room = Redis::get($data['level']);
- if($room){
- Redis::del($data['level']);
- $room = json_decode($room, 1);
- //获取玩家ClientID
- if($room['client_id'] == $data['client_id'] || $room['user_id'] == $data['user_id']){
- continue;
- }
- // $player_1_ = Gateway::getClientIdByUid($room['uid']);
- Gateway::joinGroup($room['client_id'], $room['room_id']);
- // $player_2 = Gateway::getClientIdByUid($data['uid']);
- Gateway::joinGroup($data['client_id'], $room['room_id']);
- //组合玩家信息
- $players = [
- $data,
- $room
- ];
- //发送可以开始消息
- $message = [
- "type" => 'match',
- "msg" => "匹配成功",
- "info" => ['room_id'=>$room['room_id'],"players"=>$players],
- ];
- //清理房间数据
- Redis::set($room['room_id'] . '_info','');
- Redis::set($room['room_id'] . '_questions','');
- Gateway::sendToGroup($room['room_id'], json_encode($message));
- echo "匹配成功: {$data['client_id']} 、 {$room['client_id']}\n";
- }else{
- //新建一个房间
- $room_id = $this->get_room_id();
- $room = ['room_id'=>$room_id, "user_id"=>$data['user_id'], "avatar"=>$data['avatar'], "username"=>$data['username'],'client_id'=>$data['client_id']];
- Redis::set($data['level'], json_encode($room));
- }
- }
- }
- public function get_room_id()
- {
- while (1) {
- $room_id = 'room_' . rand(10000,99999);
- $count = Gateway::getUidCountByGroup($room_id);
- if(!$count){
- return $room_id;
- }
- }
- }
- }
|