3){ $room = Redis::get('T1'); if($room){ $robot = Redis::lpop('robot_list'); $message = [ "type" => 'gotomatch', "client_id" => $robot, ]; if($robot && Gateway::isOnline($robot)){ Gateway::sendToClient($robot, json_encode($message)); echo "启动机器人: {$robot}\n"; } } } sleep(1); $match_times++; continue; } $match_times = 0; $info = []; $questions = []; $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::del($room['room_id'] . '_info'); Redis::del($room['room_id'] . '_questions'); Gateway::sendToGroup($room['room_id'], json_encode($message)); echo "清理数据 {$room['room_id']}\n"; echo "匹配成功: {$data['client_id']} 、 {$room['client_id']}\n"; //设置session Gateway::setSession($room['client_id'], ['room_id'=>$room['room_id']]); Gateway::setSession($data['client_id'], ['room_id'=>$room['room_id']]); //发送题目 $question = Question::inRandomOrder()->select('question_id','title')->where("is_released",1)->first(); $options = Option::select('option_id','title')->where("question_id",$question->question_id)->get($question->question_id); $info['question'] = $question; $info['options'] = $options; $info['questions_count'] = 1; $questions[] = $info; Redis::set($room['room_id'] . '_questions', json_encode($questions)); $message = [ "type" => 'question', "msg" => "获取题目成功", "info" => $info, ]; Gateway::sendToGroup($room['room_id'], json_encode($message)); echo "发送题目成功: {$room['room_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; } } } }