<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>用户主页</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="full-screen" content="yes"/> <!--部分原生机子-->
<meta name="screen-orientation" content="portrait"/> <!--UC浏览器-->
<meta name="x5-fullscreen" content="true"/> <!--QQ浏览器-->
<meta name="360-fullscreen" content="true"/> <!--360浏览器-->

<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
  {!!Html::style('plugins/layui/css/main.css')!!}
    {!!Html::style('plugins/layui/css/animate.min.css')!!}
  <script>
(function(f,j){var i=document,d=window;var b=i.documentElement;var c;var h=i.querySelector('meta[name="viewport"]');var e="width=device-width,initial-scale=1,maximum-scale=1.0,user-scalable=no";if(h){h.setAttribute("content",e)}else{h=i.createElement("meta");h.setAttribute("name","viewport");h.setAttribute("content",e);if(b.firstElementChild){b.firstElementChild.appendChild(h)}else{var a=i.createElement("div");a.appendChild(h);i.write(a.innerHTML)}}function g(){var k=b.getBoundingClientRect().width;if(!j){j=540}if(k>j){k=j}var l=k*100/f;b.style.fontSize=l+"px"}g();d.addEventListener("resize",function(){clearTimeout(c);c=setTimeout(g,300)},false);d.addEventListener("pageshow",function(k){if(k.persisted){clearTimeout(c);c=setTimeout(g,300)}},false);if(i.readyState==="complete"){i.body.style.fontSize="16px"}else{i.addEventListener("DOMContentLoaded",function(k){i.body.style.fontSize="16px"},false)}})(750,750);
</script>
</head>
<body> 
<div class="g-doc">
  <div class="popbg"></div>
    <div class="g-inner welcome">
      <button id="start_game" class="layui-btn" >匹配对手</button>
      <a href="javascript:;" class="rulebtn" ></a>
      <div class="popwind">
        <div class="art">
        <p>1.随机匹配对手<br />
          2.在50秒内完成5道题目<br />
          3.10秒内完成答题，答对加分，答错不扣分<br />
          4.每题满分100分，慢一秒答题扣10分<br />
          5.最终得分高为胜者，获得奖励</p>
          
        </div>
        <a href="javascript:;" class="close"></a>
      </div>
      <div class="cov covtit1"></div>
      <div class="cov covtit2"></div>
    </div>
    <div class="g-inner gstart">
       <span class="cov covxlz">星力值：560</span>
      <div class="loading amt">
        <div class="loader">
          <div class="face">
            <div class="circle"></div>
          </div>
          <div class="face">
            <div class="circle"></div>
          </div>

        </div>
      </div>

      <div class="cov cov1 amt"><span class="userface" id="avatar"></span>
        <b id="username" class="name"></b>
        <span class="num amt" id="py1_score">0</span>
      </div>
      <div class="cov cov2 amt">
        
        <input type="hidden" id="user_id" name="user_id">
        <input type="hidden" id="duishou" name="duishou">
      </div>
      <div class="cov cov3 amt" id="Jvs">匹配中
        <div class="con" style="display: none;">
          <div class="percent-circle percent-circle-left">
            <div class="left-content "></div>
          </div>
          <div class="percent-circle percent-circle-right">
            <div class="right-content "></div>
          </div>
          <div class="text-circle">0%</div>
        </div>
      </div>
      <div class="cov cov4 amt">
        <span class="userface" id="py2_avatar" ></span>
        <b id="py2_username" class="name"></b>
        <span class="num amt"  id="py2_score">0</span>
      </div>
      <div class="qs-item" >
        <span class="tit" id="Jqtitle"></span>
        <ul class="list" id="question">
          <!-- <li class="item item1 on">四川</li>
          <li class="item item2">新疆</li>
          <li class="item item3">西藏</li> -->
        </ul>
        <div class="page" id="Jpage"></div>
      </div>
      <div class="result">
        <span class="icon top-icon success" id="Jresult"></span>
        <span class="live" id="Jlastmsg">初级玩家</span>
        <a href="http://183.234.61.252:8090/Home/User/Index"><span class="btn btn1">再来一局</span></a>
        <span class="btn btn2" href="http://183.234.61.252:8090/Home/User/Index">查看等级</span>
      </div>

    </div>
    
  </div> 
{!!Html::script('plugins/layui/layui.js')!!}
<script>
layui.use(['form','jquery'], function(){
  var form = layui.form;
  var $ = layui.$;
  var game_ready = false;
  var client_id = '';
  var room_id = '';
  var cur_question = 1;
  var is_end = 0;
  var question_id=0;
  var ts;
  var sum=5;
  var angle = 0 ;
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  var leftContent  = document.querySelector(".left-content");
var rightContent  = document.querySelector(".right-content");
var textCircle   = document.querySelector(".text-circle");

//先是leftContent旋转角度从0增加到180度，
//然后是rightContent旋转角度从0增加到180度


 
   $(".welcome .rulebtn").click(function(argument) {
      $(".popwind").show();
      $(".popbg").show();

   })
   $(".welcome .popwind .close").click(function(argument) {
      $(".popwind").hide();
      $(".popbg").hide();
   })
  //获取用户信息
  $.get('/Home/User/Info',{},function(responsedata){
    if(responsedata.code == 10001){
        layer.msg(responsedata.msg, {
          time: 1000 //2秒关闭（如果不配置，默认是3秒）
        }, function(){
          window.location.href = 'index.html';
        }); 
    }
    console.log(responsedata)
    $("#username").html(responsedata.info.username);
    $("#avatar").html('<img src="' + responsedata.info.avatar + '" class="layui-circle">');
    $("#user_id").val(responsedata.info.user_id);
  },'json');
function daoshu(argument) {
    clearInterval(ts);
     sum = 9;
     angle = 0;
    leftContent.setAttribute('style', 'transform: rotate(0deg)');
    rightContent.setAttribute('style', 'transform: rotate(0deg)');
    ts = setInterval(function() {
        if (sum >= 0) textCircle.innerHTML = sum;
        sum = sum - 1;
        $("#Jvs .con").show();
        angle += 36;
        if (angle <= 360) {
            if (angle > 180) {
                rightContent.setAttribute('style', 'transform: rotate(' + (angle - 180) + 'deg)')
            } else {
                leftContent.setAttribute('style', 'transform: rotate(' + angle + 'deg)')
            }
        }
        if (sum < -1) {
            answer();
            sum = 9;
            angle = 0;
            leftContent.setAttribute('style', 'transform: rotate(0deg)');
            rightContent.setAttribute('style', 'transform: rotate(0deg)')
        }
    }, 1000)
}
  //绑定通信
  // ws = new WebSocket("ws://www.dt.com:6390");
  ws = new WebSocket("ws://183.234.61.252:8282");
  // 服务端主动推送消息时会触发这里的onmessage
  ws.onmessage = function(e){
      // json数据转换成js对象
      var data = eval("("+e.data+")");
      var type = data.type || '';
      switch(type){
          // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
          case 'init':
              client_id = data.client_id;
              // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
              $.post('/Home/User/Bind', {client_id: data.client_id}, function(responsedata){
                game_ready = true;
                layer.msg(responsedata.msg, {
                  time: 1000 //2秒关闭（如果不配置，默认是3秒）
                }); 
              }, 'json');
              break;
          case 'match':
              console.log(data);
              layer.msg("匹配成功，正在进入房间...", {
                time: 1000 //2秒关闭（如果不配置，默认是3秒）
              });
              $(".g-doc .g-inner").removeClass("gstart");
              $(".g-doc .g-inner").addClass("doing");
              //设置player值
              if(data.info.players[0]['user_id'] == $("#user_id").val()){
                $("#py1_avatar").html('<img src="' + data.info.players[0]['avatar'] + '" class="layui-circle">');
                $("#py1_username").html(data.info.players[0]['username'] + '（我）');
                $("#py2_avatar").html('<img src="' + data.info.players[1]['avatar'] + '" class="layui-circle">');
                $("#py2_username").html(data.info.players[1]['username']);
                $("#duishou").val(data.info.players[1]['user_id']);
              }else{
                $("#py1_avatar").html('<img src="' + data.info.players[1]['avatar'] + '" class="layui-circle">');
                $("#py1_username").html(data.info.players[1]['username']+'（我）');
                $("#py2_avatar").html('<img src="' + data.info.players[0]['avatar'] + '" class="layui-circle">');
                $("#py2_username").html(data.info.players[0]['username']);
                $("#duishou").val(data.info.players[0]['user_id']);
              }
            
              // if(data.info.room_id){
              //   room_id = data.info.room_id;
                
              //   getQuestion(data.info.room_id, cur_question);
                
                
              // }
              $("#py1_score").html(0);
              $("#py2_score").html(0);
              break;
          case 'answer':
              console.log(data);
              if(data.user_id == $("#user_id").val()){
                var score = parseInt($("#py1_score").html());
                if(data.is_true == 1){
                  $("#py1_score").html(score+300);
                  $(".cur_answer").addClass("cur_true");
                }else{
                  $(".cur_answer").addClass("cur_error");
                }
              }else{
                if(data.is_true == 1){
                  var score = parseInt($("#py2_score").html());
                  $("#py2_score").html(score+300);
                }
              }
              var py1_score = parseInt($("#py1_score").html());
                var py2_score = parseInt($("#py2_score").html());
                if(data.is_end == 1){
                  //结算
                   clearInterval(ts)
                   $(".g-doc .g-inner").addClass("end");
                   $("#Jvs").hide();
                  
                   
                  if(py1_score > py2_score){
                    layer.msg('恭喜你获得胜利', {icon: 1, time: 2000}, function(){
                    });
                    $("#Jresult").removeClass("faild");
                    $("#Jresult").addClass("success");
                    $("#Jlastmsg").html("恭喜你获得胜利")
                  }else if(py1_score == py2_score){
                    layer.msg('打成平手', {icon: 2, time: 2000}, function(){
                    });
                    $("#Jlastmsg").html("打成平手")
                    $("#Jresult").removeClass("success");
                    $("#Jresult").removeClass("faild");
                    $("#Jresult").html($("#avatar").html())
                  }else{
                    layer.msg('您输了比赛', {icon: 5, time: 2000}, function(){
                    });
                    $("#Jlastmsg").html("您输了比赛")
                    $("#Jresult").removeClass("success");
                    $("#Jresult").addClass("faild");
                  }
                  
                  //返回逻辑
                  data.is_end = 0;
                  cur_question = 1;
                  room_id = 0;
                   
                  
                 
                  return false;
                }
                // if(data.cur_quc == 2&&data.is_end!=1){
                //   if(a)clearTimeout(a)
                //   var a =setTimeout(function(argument) {
                //     getQuestion(room_id, cur_question);
                //   },1000)
                //   clearInterval(ts)
                  
                // }
                
            
              //设置player值
              break;
          // 当mvc框架调用GatewayClient发消息时直接alert出来
          case "question":
            loadQuestion(data);
          default :
             // alert(e.data);
      }
  };

  //开始匹配
  $("#start_game").click(function(){
    if(!game_ready){
      layer.msg("未链接服务器，请重新链接", {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      return;
    }
    $(".welcome").hide();
    $(".gstart").show();
    var url = "/Home/Game/Join";
    $.post(url,{client_id:client_id},function(responsedata){
      layer.msg(responsedata.msg, {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      if(responsedata.code == 0){
       
        
          
      }
    },'json');
  });

  //开始匹配
  $("#out_game").click(function(){
    if(!game_ready){
      layer.msg("未链接服务器，请重新链接", {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      return;
    }
    var url = "/Home/Game/Out";
    $.post(url,{client_id:client_id},function(responsedata){
      layer.msg(responsedata.msg, {
        time: 1000 //2秒关闭（如果不配置，默认是3秒）
      }); 
      if(responsedata.code == 0){
        // $(".g-doc .doing").addClass("doing");
      }
    },'json');
  });

  //获取题目
  function loadQuestion(responsedata) {
   
       question_id= responsedata.info.question.question_id;
        $("#Jqtitle").html(responsedata.info.question.title );
        var question="";
        var answers = responsedata.info.options
        for(var i in answers){
          question += '<li class="item item'+i+' answer layui-btn layui-btn-primary"   data-id="'+answers[i].option_id+'">'+answers[i].title+'</li>';
        }
        $("#question").html(question);
        $("#Jpage").html(responsedata.info.questions_count+"/5")
       // is_end = responsedata.info.question.is_end;
         daoshu();
      
  }
  var getQuestion = function getQuestion(room_id, index) {
    var url = '/Home/Game/Question';
    $.get(url, {room_id:room_id, cur_question:index}, function(responsedata){
       loadQuestion(responsedata);
    },'json').fail(function () {
          layer.msg("服务器繁忙"); 
              clearInterval(ts)
   })}
    var answer=function(answerId) {
      
      answerId= answerId?answerId:$("#question .answer").eq(0).attr("data-id");//默认第一题为答案
      var url = '/Home/Game/Answer';
      
      $.post(url, {option_id:answerId,cur_question:cur_question,client_id:client_id,is_end:is_end,question_id:question_id}, function(responsedata){
        console.log(responsedata);
        //clearInterval(ts)
      });
      cur_question = cur_question + 1;
    }



  $("#question").on('click', '.answer',function(){
    var answerId = $(this).data("id");
     if($(".cur_answer").length > 0){
        return false;
      }
      $(this).addClass("cur_answer");
    answer(answerId);
  });

});
</script>
</body>
</html>