gamematch.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use GatewayWorker\Lib\Gateway;
  5. use Illuminate\Support\Facades\Redis;
  6. class gamematch extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'game:match';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = '启动游戏匹配';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return mixed
  33. */
  34. public function handle()
  35. {
  36. //注册地址
  37. Gateway::$registerAddress = '127.0.0.1:1238';
  38. //循环匹配
  39. while (1) {
  40. $data = Redis::lpop('match_list');
  41. if(!$data){
  42. echo "未找到匹配\n";
  43. sleep(1);
  44. continue;
  45. }
  46. $data = json_decode($data, 1);
  47. $room = Redis::get($data['level']);
  48. if($room){
  49. Redis::del($data['level']);
  50. $room = json_decode($room, 1);
  51. //获取玩家ClientID
  52. if($room['client_id'] == $data['client_id'] || $room['user_id'] == $data['user_id']){
  53. continue;
  54. }
  55. // $player_1_ = Gateway::getClientIdByUid($room['uid']);
  56. Gateway::joinGroup($room['client_id'], $room['room_id']);
  57. // $player_2 = Gateway::getClientIdByUid($data['uid']);
  58. Gateway::joinGroup($data['client_id'], $room['room_id']);
  59. //组合玩家信息
  60. $players = [
  61. $data,
  62. $room
  63. ];
  64. //发送可以开始消息
  65. $message = [
  66. "type" => 'match',
  67. "msg" => "匹配成功",
  68. "info" => ['room_id'=>$room['room_id'],"players"=>$players],
  69. ];
  70. //清理房间数据
  71. Redis::set($room['room_id'] . '_info','');
  72. Redis::set($room['room_id'] . '_questions','');
  73. Gateway::sendToGroup($room['room_id'], json_encode($message));
  74. echo "匹配成功: {$data['client_id']} 、 {$room['client_id']}\n";
  75. }else{
  76. //新建一个房间
  77. $room_id = $this->get_room_id();
  78. $room = ['room_id'=>$room_id, "user_id"=>$data['user_id'], "avatar"=>$data['avatar'], "username"=>$data['username'],'client_id'=>$data['client_id']];
  79. Redis::set($data['level'], json_encode($room));
  80. }
  81. }
  82. }
  83. public function get_room_id()
  84. {
  85. while (1) {
  86. $room_id = 'room_' . rand(10000,99999);
  87. $count = Gateway::getUidCountByGroup($room_id);
  88. if(!$count){
  89. return $room_id;
  90. }
  91. }
  92. }
  93. }