Browse Source

更新接口逻辑

郑晓宇 6 years ago
parent
commit
b089655698

+ 7 - 41
app/Admin/routes.php

@@ -20,50 +20,16 @@ Route::group([
     $router->get('api/ftpServer', 'ApiController@ftpServer');
     $router->get('api/getIptvChannelListByKey', 'ApiController@getIptvChannelListByKey');
 
-
     //问题
     $router->resource('question', 'QuestionController');
     //选项
     $router->resource('option', 'OptionController');
-    
-    //影片
-    $router->put('movie/relationProgram', 'MovieController@relationProgram');
-    $router->put('movie/pushMovie', 'MovieController@pushMovie');
-    $router->resource('movie', 'MovieController');
-
-    $router->get('program/getProgramListByKey', 'ProgramController@getProgramListByKey');
-    $router->put('program/relationSeries', 'ProgramController@relationSeries');
-    $router->resource('program', 'ProgramController');
-    
-    $router->get('series/getSeriesListByKey', 'SeriesController@getSeriesListByKey');
-    $router->put('series/addToPushTask', 'SeriesController@addToPushTask');
-    $router->resource('series', 'SeriesController');
-    
-    // FTP 
-    $router->get('ftpserver/{id}/sync', 'FtpserverController@sync');
-    $router->resource('ftpserver', 'FtpserverController');
-
-    // 合作公司
-    $router->resource('company', 'CompanyController');
-
-    // 渠道
-    $router->resource('iptvchannel', 'IptvChannelController');
-
-    // 注入点
-    $router->resource('injection', 'InjectionController');
-
-    // 标签
-    $router->resource('tag', 'TagController');
-
-    // 标签类型
-    $router->resource('tagtype', 'TagTypeController');
-
-    // 图片
-    $router->resource('picture', 'PictureController');
-
-    //推送任务
-    $router->get('pushtask/getTaskListByKey', 'PushTaskController@getTaskListByKey');
-    $router->get('pushtask/{id}/start', 'PushTaskController@start');
-    $router->resource('pushtask', 'PushTaskController');
+    //用户
+    $router->resource('user', 'UserController');
+    //房间
+    $router->resource('room', 'RoomController');
+    $router->resource('roomquestion', 'RoomQuestionController');
+    $router->resource('roomanswer', 'RoomAnswerController');
+    $router->resource('roomuser', 'RoomUserController');
 
 });

+ 147 - 66
app/Console/Commands/gamematch.php

@@ -7,6 +7,9 @@ use GatewayWorker\Lib\Gateway;
 use Illuminate\Support\Facades\Redis;
 use App\Model\Question;
 use App\Model\Option;
+use App\Model\User;
+use Ramsey\Uuid\Uuid;
+use App\Jobs\Distribute;
 
 class gamematch extends Command
 {
@@ -46,22 +49,24 @@ class gamematch extends Command
         $match_times = 0;
         //循环匹配
         while (1) {
-            $data = Redis::lpop('match_list');
-            if(!$data){
-                echo "未找到匹配\n";
-                if($match_times > 3){
-                    $room = Redis::get('T1');
-                    if($room){
-                        $robot = Redis::spop('robot_list');
-                        $message = [
-                            "type" => 'gotomatch',
-                            "client_id" => $robot,
-                        ];
-                        if($robot && Gateway::isOnline($robot)){
-                            Gateway::sendToClient($robot, json_encode($message));
-                            echo "启动机器人: {$robot}\n";
-                        }
+            $user_id = Redis::lpop('match_list');
+            if(!$user_id){
+                if($match_times > 5){
+                    //获取是否有房间未满人
+                    $room_id = $this->get_free_room();
+                    if(!$room_id){
+                        echo "未找到匹配房间\n";
+                        continue;
                     }
+                    //获取离线机器人
+                    $user = User::inRandomOrder()->select('user_id','name')->where("is_robot",1)->where("is_login",0)->first();
+                    if(!$user){
+                        echo "没有离线机器人\n";
+                        sleep(1);
+                        continue;
+                    }
+                    //发布启动机器人
+                    Redis::publish("startRobot", $user->user_id);
                 }
                 sleep(1);
                 $match_times++;
@@ -69,73 +74,149 @@ class gamematch extends Command
             }
             $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']){
+            $room_id = $this->get_free_room();
+            $user = User::select('user_id', 'avatar', 'name', 'win_rate')->where("user_id", $user_id)->first();
+            $user_client_id = Gateway::getClientIdByUid($user_id);
+            if($user->is_robot && !$user->is_login){
+                if(Gateway::isUidOnline($user_id)){
+                    //更新用户登陆状态
+                    unset($update_data);
+                    $update_data = [
+                        "is_login" => 1,
+                        "client_id" => $user_client_id,
+                    ];
+                    User::where("user_id", $user_id)->update($update_data);
+                }else{
                     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
+            }
+            if($room_id){
+                //获取房间信息
+                $room = Room::where("room_id", $room_id)->first();
+                //把当前用户加入当前房间
+                Gateway::joinGroup($user_client_id, $room_id);
+                RoomUser::insert([
+                    'user_id' => $user_id, 
+                    'room_id' => $room_id, 
+                    'state' => 1,
+                ]);
+                $info['user'] = [
+                    "user_id" => $user_id,
+                    "name" => $user->name,
+                    "avatar" => $user->avatar,
+                    "win_rate" => $user->win_rate,
                 ];
+                //获取房间玩家信息
+                $group_users = Gateway::getUidListByGroup($room_id);
+                if(count($group_users) > 0 && count($group_users) < $room->user_limit){
+                    //清理不在房间的用户
+                    RoomUser::whereNotIn('user_id', array_values($group_users))->delete();
+                }
+                $info['players'] = User::select('user_id', 'avatar', 'name', 'win_rate')->whereIn("user_id", array_values($group_users))->get();
                 //发送可以开始消息
                 $message = [
-                    "type" => 'match',
-                    "msg" => "匹配成功",
-                    "info" => ['room_id'=>$room['room_id'],"players"=>$players],
+                    "type" => 'player_join',
+                    "msg" => "玩家加入房间",
+                    "info" => $info
                 ];
-                //清理房间数据
-                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']]);
+                Gateway::sendToGroup($room_id, json_encode($message));
+                echo "玩家加入房间: {$user_id}\n";
+                //判断对战是否开启标志
+                if(count($group_users) == $room->user_limit){
+                    unset($update_data);
+                    $update_data['is_full'] = 1;
+                    $update_data['start_at'] = date('Y-m-d H:i:s');
+                    Room::where("room_id", $room_id)->update($update_data);
+                }
 
+                //执行发题
+                Distribute::dispatch($room_id)->onQueue('distribute');
+                
                 //发送题目
-                $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";
+                // $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));
+                $room_id = Room::insertGetId([
+                    'title' => 'room_' . $user->name . date('YmdHis'),
+                    'is_full' => 0,
+                    'is_end' => 0,
+                    'start_at' => 0,
+                    'user_limit' => 2,
+                    'nickname' => $user->name,
+                    'user_id' => $user_idc,
+                    'created_at' => date('Y-m-d H:i:s'),
+                    'updated_at' => date('Y-m-d H:i:s'),
+                ]);
+                RoomUser::insert([
+                    "user_id" => $user_id,
+                    "room_id" => $room_id,
+                    "state" => 1,
+                ]);
+                //把当前用户加入当前房间 保险点获取用户最新 client_id
+                Gateway::joinGroup($user_client_id, $room_id);
+                echo "玩家新建房间: {$user_id}\n";
+                //当前用户信息
+                $info['user'] = [
+                    "user_id" => $user_id,
+                    "name" => $user->name,
+                    "avatar" => $user->avatar,
+                    "win_rate" => $user->win_rate,
+                ];
+                //获取房间玩家信息
+                $group_users = Gateway::getUidListByGroup($room_id);
+                $info['players'] = User::select('user_id', 'avatar', 'name', 'win_rate')->whereIn("user_id", array_values($group_users))->get();
+                //发送可以开始消息
+                $message = [
+                    "type" => 'player_join',
+                    "msg" => "玩家加入房间",
+                    "info" => $info
+                ];
+                Gateway::sendToGroup($room_id, json_encode($message));
             }
         }
     }
 
-    public function get_room_id()
+    /**
+     * 获取正在匹配的房间
+     */
+    public function get_free_room()
     {
+        //注册地址
+        Gateway::$registerAddress = '127.0.0.1:1238';
         while (1) {
-            $room_id = 'room_' . rand(10000,99999);
-            $count = Gateway::getUidCountByGroup($room_id);
-            if(!$count){
-                return $room_id;
+            $room = Room::select("room_id")->where("is_full",0)->where("is_end","<>",1)->first();
+            if($room){
+                $users = RommUser::select("user_id")->where("room_id", $room->room_id)->where("state", 1)->get();
+                foreach ($users as $user) {
+                    //检查当前room玩家是否还在房间中
+                    $is_online = Gateway::isUidOnline($user->user_id);
+                    if(!$is_online){
+                        //把当前房间关闭
+                        $update_data["is_end"] = 1;
+                        Room::where("room_id", $room->room_id)->update($update_data);
+                        unset($update_data);
+                        //取消用户在房间的状态
+                        $update_data['state'] = 2;
+                        RoomUser::where("room_id", $room->room_id)->update($update_data);
+                        continue;
+                    }
+                }
+                return $room->room_id;
+            }else{
+                return false;
             }
         }
     }

+ 51 - 36
app/Console/Commands/robot.php

@@ -5,6 +5,8 @@ namespace App\Console\Commands;
 use Illuminate\Console\Command;
 use App\Model\Question;
 use App\Model\Option;
+use App\Model\User;
+use App\Model\RoomUser;
 use GuzzleHttp\Client;
 use GuzzleHttp\Cookie\CookieJar;
 use Workerman\Worker;
@@ -19,7 +21,7 @@ class robot extends Command
      *
      * @var string
      */
-    protected $signature = 'game:robot {username?}';
+    protected $signature = 'game:robot {user_id?}';
 
     /**
      * The console command description.
@@ -45,33 +47,38 @@ class robot extends Command
      */
     public function handle()
     {
-        $username = $this->argument('username');
-        if(!$username){
-            $users = array("晚桐","书蝶","北俞","时宛","花染");
-            $rand_user = rand(0,4);
-            $username = $users[$rand_user];
+        //获取机器人信息
+        $user_id = $this->argument('user_id');
+        if(!$user_id){
+            $user = User::inRandomOrder()->select('user_id','name')->where("is_robot",1)->where("is_login",0)->first();
+        }else{
+            $user = User::select('user_id','name')->where("is_robot",1)->where("is_login",0)->first();
+        }
+        if(!$user){
+            echo "未找到机器人";
+            die;
         }
         $worker = new Worker();
-        $worker->onWorkerStart = function($worker) use($username){
+        $worker->onWorkerStart = function($worker) use($user){
             //定义请求客户端
             $room_id = ''; //定义当前机器人加入的room_id
             $client_id = ''; //定义当前机器人client_id
             $client = new Client([
                 'cookies' => true,
                 'verify' => false,
-            ]); 
+            ]);
             $response = $client->request('POST', 'http://183.234.61.252:8090/Home/User/Login',[
                 'form_params' => [
-                    'username' => $username,
+                    'username' => $user->name,
                 ]
             ]);
             $response = $client->request('GET', 'http://183.234.61.252:8090/Home/User/Info');
-            $robot = $response->getBody()->getContents();
+            // $robot = $response->getBody()->getContents();
 
             $con = new AsyncTcpConnection('ws://183.234.61.252:8282');
             $con->onConnect = function($con) use($client) {
             };
-            $con->onMessage = function($con, $data) use($client, &$room_id, &$client_id){
+            $con->onMessage = function($con, $data) use($client, &$room_id, &$client_id, $user){
                 //注册地址
                 Gateway::$registerAddress = '127.0.0.1:1238';
                 //格式化参数
@@ -85,10 +92,24 @@ class robot extends Command
                         ]
                     ]);
                     echo "client: {$client_id} 成功绑定socket\n";
-
+                    $update_data = [
+                        "is_login" => 1,
+                        "client_id" => $client_id,
+                    ];
+                    //更新机器人登陆状态
+                    User::where("user_id", $user->user_id)->update($update_data);
                     //记录当前在线机器人
-                    Redis::sadd('robot_list', $client_id);
-                    Redis::lpush('online_robot_list', $client_id);
+                    // Redis::sadd('robot_list', $client_id);
+                    // Redis::lpush('online_robot_list', $client_id);
+
+                    //启动匹配
+                    $response = $client->request('POST', 'http://183.234.61.252:8090/Home/Game/Join',[
+                        'form_params' => [
+                            'client_id' => $client_id,
+                        ]
+                    ]);
+                    echo "{$client_id} 成功加入匹配\n";
+
                 }
                 //唤起匹配
                 if($json_data->type == 'gotomatch'){
@@ -99,6 +120,7 @@ class robot extends Command
                     ]);
                     echo "{$client_id} 成功加入匹配\n";
                 }
+
                 //匹配成功
                 if($json_data->type == 'match'){
                     $room_id = $json_data->info->room_id;
@@ -119,29 +141,22 @@ class robot extends Command
                         ]
                     ]);
                 }
-                //获得题目
-                if($json_data->type == 'answer'){
-                    if($json_data->is_end == 1){
-                        $room_id = '';
-                        echo "{$client_id} 回答问题成功重回队列\n";
-                        //重新加入机器人队列
-                        Redis::sadd('robot_list', $client_id);
-                    }
-                }
-                //获得题目
-                if($json_data->type == 'checkrobot'){
-                    if(!empty($room_id) && !empty($client_id)){
-                        $clients = Gateway::getClientIdListByGroup($room_id);
-                        if(count($clients) > 0 && count($clients) < 2){
-                            Gateway::leaveGroup($client_id, $room_id);
-                            //重新加入机器人队列
-                            Redis::sadd('robot_list', $client_id);
-                            echo "{$client_id} 离开房间:{$room_id}\n";
-                            echo "{$client_id} 成功重回队列\n";
-                            $room_id = '';
-                        }
-                    }
+
+                //结算
+                if($json_data->type == 'settlement'){
+                    $update_data = [
+                        "is_login" => 0,
+                        "client_id" => '',
+                    ];
+                    //更新机器人登陆状态
+                    User::where("user_id", $user->user_id)->update($update_data);
+                    unset($update_data);
+                    $update_data['state'] = 2;
+                    User::where("user_id", $user->user_id)->where("state", 1)->update($update_data);
+                    echo "已结算,关闭机器人";
+                    die;
                 }
+
             };
             $con->connect();
         };

+ 94 - 141
app/Home/Controllers/GameController.php

@@ -7,84 +7,17 @@ use Illuminate\Http\Request;
 use GatewayWorker\Lib\Gateway;
 use App\Model\Question;
 use App\Model\Option;
+use App\Model\RoomUser;
+use App\Model\RoomQuestion;
+use App\Model\RoomAnswer;
+use App\Model\Room;
 use Illuminate\Support\Facades\Redis;
+use App\Jobs\Settlement;
 
 class GameController extends Controller
 {
 
     /**
-     * 获取问题
-     */
-    public function Question(Request $request)
-    {
-        if(!$request->session()->has('user_id')){
-            $response['code'] = 400;
-            $response['msg'] = '请先登录';
-            return response()->json($response);
-        }
-        $room_id = $request->input('room_id');
-        if(!$room_id){
-            $response['code'] = 400;
-            $response['msg'] = '缺少房间参数';
-            return response()->json($response);
-        }
-        //第几题
-        $cur_question = $request->input('cur_question');
-        if(!$cur_question){
-            $cur_question = 1;
-        }
-        //防止并发问题加文件锁
-        $Lock_file = "{$room_id}_lock_file.txt";
-        $i = 1;
-        while ($i < 30) {
-            $fp = fopen($Lock_file, "a+");
-            if($fp===false){
-                sleep(1);
-            }else{
-                flock($fp,LOCK_EX);//获取独占锁
-            }
-            $i++;
-        }
-        //获取当前房间问题
-        $questions = Redis::get($room_id . '_questions');
-        if($questions){
-            $questions = json_decode($questions);
-        }else{
-            $questions = [];
-        }
-        if(isset($questions[$cur_question -1])){
-            $response['info'] = $questions[$cur_question - 1];
-        }else{
-            $questions_id = [];
-            foreach ($questions as $k => $v) {
-                $questions_id[] = $v->question->question_id;
-            }
-            // $questions_id = array_column($questions, 'question_id');
-            $question = Question::inRandomOrder()->select('question_id','title')->where("is_released",1)->whereNotIn("question_id", $questions_id)->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'] = count($questions) + 1; 
-            $questions[] = $info;
-            Redis::set($room_id . '_questions', json_encode($questions));
-            $response['info'] = $info;
-        }
-
-        //解锁
-        if($fp!==false){
-            @flock($fp,LOCK_UN);
-            clearstatcache();
-        }
-        @fclose($fp);
-        @unlink($Lock_file);
-
-        //设置返回数据
-        $response['code'] = 0;
-        $response['msg'] = '获取成功';
-        return response()->json($response);
-    }
-
-    /**
      * 回答问题
      */
     public function Answer(Request $request)
@@ -95,38 +28,22 @@ class GameController extends Controller
             return response()->json($response);
         }
 
-        $message['is_end'] = 0;  //是否结束答题标志
+        $answer_time = time();
         $question_id = $request->input('question_id');
         $option_id = $request->input('option_id');
         $user_id = $request->session()->get('user_id');
 
-        //检测用户断线
+        //注册gateway地址
         Gateway::$registerAddress = '127.0.0.1:1238';
-        //获取当前用户session
-        $client_ids = Gateway::getClientIdByUid($user_id);
-        $gateway_user = Gateway::getSession($client_ids[0]);
-        $room_id = $gateway_user['room_id'];
+        //获取房间号
+        $room_id = RoomUser::where(["user_id"=>$user_id,"state"=>1])->value('room_id');
 
         if(!$room_id){
             $response['code'] = 400;
-            $response['msg'] = '缺少房间参数';
+            $response['msg'] = '没有加入房间';
             return response()->json($response);
         }
 
-        //获取当前房间问题条数
-        $questions = Redis::get($room_id . '_questions');
-        if($questions){
-            $questions = json_decode($questions);
-            $questions_count = count($questions);
-        }else{
-            $questions_count = 0;
-        }
-        //获取当前组存活用户
-        $clients = Gateway::getUidListByGroup($room_id);
-        if(count($clients) < 2){
-          $message['is_end'] = 1;
-        }
-
         //判断答案逻辑
         $is_true = Option::where([
           ["question_id", $question_id],
@@ -134,61 +51,92 @@ class GameController extends Controller
           ["is_answer", 1],
         ])->count();
 
-        $scores = Redis::get($room_id.'_info');
-        if($scores){
-          $scores = json_decode($scores, 1);
+        //判断用户回答获取分数
+        if($is_true){
+            //获取当前题目开始时间
+            $start_at = RoomQuestion::where(["question_id" => $question_id, "room_id" => $room_id])->value('start_at');
+            $answer_diff = $answer_time - strtotime($start_at);
+            switch ($answer_diff) {
+                case '0':
+                case '1':
+                    $score = 100;
+                    break;
+                case '2':
+                case '3':
+                    $score = 80;
+                    break;
+                case '4':
+                case '5':
+                    $score = 60;
+                    break;
+                case '6':
+                case '7':
+                    $score = 40;
+                    break;
+                case '8':
+                case '9':
+                    $score = 20;
+                    break;
+                default:
+                    $score = 0;
+                    break;
+            }
         }else{
-          $scores = [];
+            $score = 0;
         }
-        if(!isset($scores[$user_id])){
-          $scores[$user_id] = 0;
+
+        //写入记录
+        $result = RoomAnswer::insert([
+            "question_id" => $question_id,
+            "option_id" => $option_id,
+            "room_id" => $room_id,
+            "score" => $score,
+            "created_at" => date('Y-m-d H:i:s'),
+            "updated_at" => date('Y-m-d H:i:s'),
+        ]);
+
+        if(!$result){
+            //发送消息
+            $response['code'] = 400;
+            $response['msg'] = '重复回答';
+            return response()->json($response);
         }
 
-        if($is_true  && !isset($scores['questions'][$question_id][$user_id])){
-            $scores[$user_id] = (int) $scores[$user_id] + 1;
+        if($score){
+            //增加总分
+            RoomUser::where([
+                "user_id" => $user_id,
+                "room_id" => $room_id,
+            ])->increment('score', $score);
         }
-        $scores['questions'][$question_id][$user_id] = $is_true; 
 
-        Redis::set($room_id . '_info', json_encode($scores));
-        $message['is_true'] = $is_true;
-        $message['scores'] = $scores;
+        $message['score'] = $score;
         $message['user_id'] = $user_id;
-        $message['online'] = count($clients);
         $message['type'] = 'answer';
-        $message['cur_quc'] = count($scores['questions'][$question_id]);
-        $message['client_id'] = $client_ids[0];
-        //问题超过或者到第4条为结束标志
-        if($questions_count > 4 && $message['cur_quc'] > 1){
-          $message['is_end'] = 1;
-        }
-
-        //发送消息
         Gateway::sendToGroup($room_id, json_encode($message));
-        $response['code'] = 0;
-        $response['msg'] = '回答成功';
 
-        //发送题目
-        if($message['is_end'] != 1 && $message['cur_quc'] > 1){
-            $questions_id = [];
-            foreach ($questions as $k => $v) {
-                $questions_id[] = $v->question->question_id;
+        //获取房间信息,最后一个回答触发结算程序
+        $room_user_limit = Room::where("room_id", $room_id)->value("user_limit");
+        //获取当前题目回答人数
+        $answer_user_count = RoomAnswer::where([
+            "room_id" => $room_id,
+            "question_id" => $question_id,
+        ])->count();
+        if($room_user_limit == $answer_user_count){
+            if(!isset($start_at)){
+                $start_at = RoomQuestion::where(["question_id" => $question_id, "room_id" => $room_id])->value('start_at');
             }
-            $question = Question::inRandomOrder()->select('question_id','title')->where("is_released",1)->whereNotIn("question_id", $questions_id)->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'] = $questions_count + 1;
-            $questions[] = $info;
-            Redis::set($room_id . '_questions', json_encode($questions));
-            $message = [
-                "type" => 'question',
-                "msg" => "获取题目成功",
-                "info" => $info,
-            ];
-            Gateway::sendToGroup($room_id, json_encode($message));
+            $next_date = date('YmdHis', strtotime("{$start_at} +10 seconds"));
+            //先删除固定结算任务队列
+            Redis::lrem("Game_settlement_{$next_date}", $room_id);
+            //执行结算队列
+            Settlement::dispatch($room_id)->onQueue('settlement');
         }
 
-        //用户退出房间关闭房间等逻辑 todo ...
+        //发送消息
+        $response['code'] = 0;
+        $response['msg'] = '回答成功';
+        //返回回答信息
         return response()->json($response);
     }
 
@@ -204,11 +152,16 @@ class GameController extends Controller
         }
 
         $user_id = $request->session()->get('user_id');
-        $username = $request->session()->get('username');
-        $avatar = $request->session()->get('avatar');
-        $client_id = $request->input('client_id');
-        $data = json_encode(['user_id'=>$user_id,'level'=>'T1','avatar'=>$avatar,'username'=>$username,'client_id'=>$client_id]);
-        Redis::lpush('match_list',$data);
+        //检查是否在房间中
+        $is_in_room = RommUser::where("user_id", $user_id)->where("state", 1)->count();
+        if($is_in_room){
+            $response['code'] = 400;
+            $response['msg'] = "已在房间中";
+            return response()->json($response);
+        }
+        //删除队列再加入匹配
+        Redis::lrem('match_list',$user_id);
+        Redis::rpush('match_list',$user_id);
 
         $response['code'] = 0;
         $response['msg'] = "已加入匹配队列";
@@ -216,7 +169,7 @@ class GameController extends Controller
     }
 
     /**
-     * 退出房间
+     * 取消匹配
      */
     public function Quit(Request $request)
     {

+ 114 - 61
app/Home/Controllers/UserController.php

@@ -5,72 +5,99 @@ namespace App\Home\Controllers;
 use App\Http\Controllers\Controller;
 use Illuminate\Http\Request;
 use GatewayWorker\Lib\Gateway;
+use GuzzleHttp\Client;
+use App\Model\User;
+use App\Model\Room;
+use App\Model\RoomUser;
 
 class UserController extends Controller
 {
 
     /**
-     * 用户首页
+     * 获取用户信息
      */
-    public function Index(Request $request)
+    public function Info(Request $request)
     {
-        if(!$request->session()->has('user_id')){
-            return redirect('Home/User/Login');
+        $cmcc_id = $request->input('user_id');
+        $mt = $request->input('mt');
+        if(!$cmcc_id || !$mt){
+            $response['code'] = 400;
+            $response['msg'] = '缺少参数';
+            return response()->json($response);
         }
-        return view('home.user');
-    }
+        
+        //请求用户信息
+        $client = new Client([
+            'verify' => false,
+        ]);
+        $ip = '211.139.191.175';
+        $port = '38083';
+        $req_time = date('YmdHis');
+        $sign = md5($cmcc_id . $req_time . $mt);
+        $params['req_param'] = [
+            "pub_info" => [
+                "req_src" => 1,
+                "ver" => "1.0",
+                "req_time" => $req_time,
+                "sign" => $sign,
+            ],
+            "page_info" => [
+                "current_page" => 1,
+                "page_size" => 10,
+            ],
+            "busi_info" => [],
+        ];
+        // $response = $client->request('POST', "http://{$ip}:{$port}/hgs/uc/queryusergameinfo",[
+        //     'form_params' => [
+        //         'username' => $user->name,
+        //     ]
+        // ]);
+        // $cmcc_user = $response->getBody()->getContents();
 
-    /**
-     * 登陆页面
-     */
-    public function Login(Request $request)
-    {
-        if($request->session()->has('user_id')){
-            return redirect('Home/User/Index');
+        //判断请求结果 todo ...
+
+        //记录用户信息 todo ...
+
+        //获取当前系统是否存在
+        $user = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->where("cmcc_id", $cmcc_id)->first();
+        if($user){
+
+        }else{
+            $date = date("Y-m-d H:i:s");
+            //记录用户信息
+            $user_id = User::insertGetId([
+                "name" => "测试用户_" . $cmcc_id,
+                "avatar" => "https://picsum.photos/200/200/?image=". rand(1, 300),
+                "cmcc_id" => $cmcc_id,
+                "mt" => $cmcc_id,
+                "win_count" => 0,
+                "lose_count" => 0,
+                "is_login" => 0,
+                "is_robot" => 0,
+                "created_at" => $date,
+                "updated_at" => $date,
+            ]);
+            $user = User::select('user_id', 'avatar', 'name', 'win_count', 'lose_count')->where("cmcc_id", $cmcc_id)->first();
         }
-        return view('home.login');
-    }
 
-    /**
-     * 登陆
-     */
-    public function doLogin(Request $request)
-    {
-        if(!$request->session()->has('user_id')){
-            $user_id = uniqid();
-            $request->session()->put('user_id', $user_id);
+        if($user->win_count == 0 || ($user->win_count == 0 && $user->lose_count == 0)){
+            $win_rate = 0;
         }else{
-            $user_id = $request->session()->get('user_id');
+            $win_rate = $user->win_count / ($user->win_count + $user->lose_count);
         }
 
-        $username = $request->input('username');
-        $user_id = $request->session()->get('user_id');
-        $request->session()->put('username', $username);
-        $avatar = rand(1,4);
-        $request->session()->put('avatar', "/img/tx{$avatar}.jpg");
+        //测试固定用户信息
+        $info['user_id'] = $user->user_id;
+        $info['name'] = $user->name;
+        $info['avatar'] = $user->avatar;
+        $info['win_rate'] = $win_rate;
+        $info['play_next'] = 1;
 
+        //设置session
+        $request->session()->put('user_id', $user->user_id);
         $response['code'] = 0;
-        $response['msg'] = '登陆成功';
-        return response()->json($response);
-    }
-
-    /**
-     * 获取用户信息
-     */
-    public function Info(Request $request)
-    {
-        if(!$request->session()->has('user_id')){
-            $response['code'] = 400;
-            $response['msg'] = '请先登录';
-            return response()->json($response);
-        }
-        
-        $data['user_id'] = $request->session()->get('user_id');
-        $data['username'] = $request->session()->get('username');
-        $data['avatar'] = $request->session()->get('avatar');
-        $response['code'] = 0;
-        $response['info'] = $data;
-        $response['msg'] = '获取成功';
+        $response['msg'] = '获取用户信息成功';
+        $response['info'] = $info;
         return response()->json($response);
     }
 
@@ -84,24 +111,50 @@ class UserController extends Controller
             $response['msg'] = '请先登录';
             return response()->json($response);
         }
-        
-        $user_id = $request->session()->get('user_id');
 
+        $user_id = $request->session()->get('user_id');
         $client_id = $request->input('client_id');
         //注册地址
         Gateway::$registerAddress = '127.0.0.1:1238';
-        $client_ids = Gateway::getClientIdByUid($user_id);
-        // if(count($client_ids) > 1){
-        //     $response['code'] = 400;
-        //     $response['msg'] = '禁止多个客户端链接';
-        //     return response()->json($response);
-        // }
-        // client_id与uid绑定
+        //异地登录机制
+        $user = User::where("user_id", $user_id)->first();
+        if($user->client_id != $client_id){
+            $message = [
+                "type" => "replace_login",
+                "msg" => "用户在其他地方登录了,当前用户端断开连接",
+            ];
+            Gateway::sendToClient($user->client_id, json_encode($message));
+            //断开旧ID
+            Gateway::closeClient($user->client_id);
+        }
+
+        //绑定用户ID
         Gateway::bindUid($client_id, $user_id);
-        if($request->session()->has('room_id')){
-            $room_id = $request->session()->get('room_id');
+        //更新用户最新client_id
+        $update_data['client_id'] = $client_id;
+        User::where("user_id", $user_id)->update($update_data);
+        $response['info']['in_game'] = 0;   //是否还在对战中
+        //判断用户是否还在对战
+        $room_id = RoomUser::where([
+            "user_id" => $user_id,
+            "state" => 1,
+        ])->value("room_id");
+        //查看房间状态
+        $room_state = Room::where("room_id", $room_id)->value("is_close");
+        if($room_id && !$room_state){
             Gateway::joinGroup($client_id, $room_id);
+            $response['info']['in_game'] = 1;
+        }elseif($room_id){
+            unset($update_data);
+            $update_data['state'] = 2;
+            //更新一下房间状态
+            RoomUser::where([
+                "user_id" => $user_id,
+                "room_id" => $room_id,
+                "state" => 1,
+            ])->update($update_data);
         }
+
         $response['code'] = 0;
         $response['msg'] = '服务连接成功';
         return response()->json($response);

+ 1 - 0
composer.json

@@ -13,6 +13,7 @@
         "laravel/tinker": "~1.0",
         "laravelcollective/html": "5.*",
         "predis/predis": "^1.1",
+        "ramsey/uuid": "^3.8",
         "workerman/gateway-worker": "^3.0"
     },
     "require-dev": {

+ 1 - 1
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "bb124522b0156792d94196e47a918d1c",
+    "content-hash": "f08cd8fe505e8d187b56b03a8cad0626",
     "packages": [
         {
             "name": "dnoegel/php-xdg-base-dir",

+ 1 - 1
config/admin.php

@@ -129,7 +129,7 @@ return [
     'upload' => [
 
         // Disk in `config/filesystem.php`.
-        'disk' => 'admin',
+        'disk' => 'local',
 
         // Image and file upload path under the disk above.
         'directory' => [