Ejemplo n.º 1
0
    public void OnMatchJoined(JoinMatchResponse matchJoin)
    {
        if (matchJoin.success)
        {
            Debug.Log("Join match succeeded");
            if (_lobby.matchCreated)
            {
                Debug.LogWarning("Match already set up, aborting...");
                return;
            }

            MatchInfo matchInfo = new MatchInfo(matchJoin);
            Utility.SetAccessTokenForNetwork(matchJoin.networkId, new NetworkAccessToken(matchJoin.accessTokenString));
            _client = new NetworkClient();
            _client.RegisterHandler(MsgType.Connect, OnConnected);
            _client.RegisterHandler(MsgType.Disconnect, OnDisconnect);
            _client.RegisterHandler(MsgType.Error, OnError);
            _client.RegisterHandler(MsgType.AddPlayer, AddPlayerMessage);
            //_client.RegisterHandler(MsgType.Owner, OwnerMes);
            _client.RegisterHandler(100, MesFromServer);

            NetworkManager.singleton.StartClient(matchInfo);
            //_client.Connect(matchInfo);
        }
        else
        {
            Debug.LogError("Join match failed.");

        }
    }
Ejemplo n.º 2
0
    protected override void OnMatchInfoDownloaded(MatchInfo matchInfo)
    {
        if (matchInfo.state != "OK") {
            int matchId = eventInfo.matchId;
            StartCoroutine (DownloadMatchInfo (matchId));
            return;
        }

        Bot winner = matchInfo.GetWinner();

        if (winner == null) {
            winnerText.text = "Draw!";

            Bot[] bots = matchInfo.bots;

            player1Text.text = createText (bots[0].name, -1);
            player2Text.text = createText (bots[1].name, -1);
        } else {
            winnerText.text = winner.name + " wins!";

            Bot looser = matchInfo.GetLooser ();

            player1Text.text = createText (winner.name, 3);
            player2Text.text = createText (looser.name, 0);
        }

        int tournamentId = matchInfo.tournamentId;
        StartCoroutine(DownloadUpcomingMatches(tournamentId));
    }
Ejemplo n.º 3
0
 public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
 {
     foreach (var player in myTeam.Players)
     {
         player.ActionWait();
     }
 }
Ejemplo n.º 4
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            var pl1 = myTeam.Players.First(pl => pl.PlayerType == PlayerType.RightDefender);

            myTeam.DevMessage = string.Format("speed {0}", pl1.Velocity.Length);

            if (maxReached)
            {
                if (pl1.Velocity.Length > 0.05)
                {
                    pl1.ActionWait();
                    return;
                }

                myTeam.DevMessage += "\r\n0.05 minReached";
                maxReached = false;
                point = pl1.Position.X < Field.Borders.Center.X ? Field.EnemyGoal : Field.MyGoal;
            }

            if (pl1.Velocity.Length > 3 * 0.95)
            {
                myTeam.DevMessage += "\r\n0.95 maxReached";
                maxReached = true;
                prevVelocity = 0;
                pl1.ActionWait();
            }
            else
            {
                pl1.ActionGo(point);
                prevVelocity = pl1.Velocity.Length;
            }
        }
Ejemplo n.º 5
0
        // POST api/Match, request body contains client information serialized as XML or JSON
        public HttpResponseMessage PostAddPerson(MatchInfo matchSearch)
        {
            if (ModelState.IsValid)                                             // model class validation ok?
            {
                // check for duplicate
                // LINQ query - count number of people with ID
                int count = context.Match.Where(l => l.ID.ToUpper() == matchSearch.ID.ToUpper()).Count();
                if (count == 0)
                {
                    MatchInfo.Add(matchSearch);

                    // create http response with Created status code and listing serialised as content and Location header set to URI for new resource
                    var response = Request.CreateResponse<MatchInfo>(HttpStatusCode.Created, matchSearch);
                    string uri = Url.Link("DefaultApi", new { id = matchSearch.ID });         // name of default route in WebApiConfig.cs
                    response.Headers.Location = new Uri(uri);                                           // Location URI for newly created resource

                    return response;
                }
                else
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);                // 404
                }
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);                 // 400, malformed request
            }
        }
Ejemplo n.º 6
0
 public Pitch(Team my, Team enemy, Ball ball, MatchInfo info)
 {
     My = my;
     Enemy = enemy;
     Ball = ball;
     Info = info;
 }
Ejemplo n.º 7
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            foreach (Player player in myTeam.Players)
            {
                Player closestEnemy = player.GetClosest(enemyTeam);

                if (ball.Owner == player)  //Allways shoots for the enemy goal.
                    player.ActionShootGoal();
                else if (player.CanPickUpBall(ball))  //Picks up the ball if posible.
                    player.ActionPickUpBall();
                else if (player.CanTackle(closestEnemy))  //Tackles any enemy that is close.
                    player.ActionTackle(closestEnemy);
                else  //If the player cannot do anything urgently usefull, move to a good position.
                {
                    if (player == ball.GetClosest(myTeam))  //If the player is closest to the ball, go for it.
                        player.ActionGo(ball);
                    else if (player.PlayerType == PlayerType.Keeper)  //The keeper protects the goal.
                        player.ActionGo(new Vector(50, Math.Max(Math.Min(ball.Position.Y, Field.MyGoal.Bottom.Y), Field.MyGoal.Top.Y))); //The keeper positions himself 50 units out from the goal                                                                                                            //at the same height as the ball, although never leaving the goal
                    else if (player.PlayerType == PlayerType.LeftDefender)
                        player.ActionGo(new Vector(Field.Borders.Width * 0.2, ball.Position.Y));  //The left defender helps protect the goal
                    else if (player.PlayerType == PlayerType.RightDefender)
                        player.ActionGo(Field.MyGoal.GetClosest(enemyTeam));   //The right defender chases the enemy closest to myGoal
                    else if (player.PlayerType == PlayerType.RightForward)
                        player.ActionGo((Field.Borders.Center + Field.Borders.Bottom + ball.Position) / 3);  //Right forward stays in position on the midline, untill the ball comes close.
                    else if (player.PlayerType == PlayerType.LeftForward)
                        player.ActionGo((Field.Borders.Center + Field.Borders.Top + ball.Position) / 3);   //Left forward stays in position on the midline, untill the ball comes close.
                    else if (player.PlayerType == PlayerType.CenterForward)
                        player.ActionGo((Field.Borders.Center + Field.EnemyGoal.Center + ball.Position) / 3);    //Center forward stays in position on the enemy side of the field.
                }
            }
        }
Ejemplo n.º 8
0
 public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
 {
     foreach (var player in myTeam.Players)
     {
         if (player.CanPickUpBall(ball))
         {
             player.ActionPickUpBall();
         }
         else if (player == ball.Owner)
         {
             player.ActionShootGoal();
         }
         else if (ball.Owner != null && ball.Owner.Team != myTeam && player.CanTackle(ball.Owner))
         {
             player.ActionTackle(ball.Owner);
         }
         else if (WallPositions[player.PlayerType].GetDistanceTo(player) > 1.0)
         {
             player.ActionGo(WallPositions[player.PlayerType]);
         }
         else
         {
             player.ActionWait();
         }
     }
 }
Ejemplo n.º 9
0
 public Game(MatchInfo info, Ball ball, Team enemy, Team my, bool inAttack)
 {
     Info = info;
     Ball = ball;
     Enemy = enemy;
     My = my;
     InAttack = inAttack;
 }
Ejemplo n.º 10
0
 public MatchInfo checkMatches(GameObject obj)
 {
     MatchInfo info = new MatchInfo();
     List<GameObject> horizontal = (List<GameObject>)checkMatchesHorizontal(obj);
     info.addRange(horizontal);
     List<GameObject> vertical = (List<GameObject>)checkMatchesVertical(obj);
     info.addRange(vertical);
     return info;
 }
Ejemplo n.º 11
0
		public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
		{
			var info = TurnInfo.Create(myTeam, enemyTeam, ball, matchInfo);

			var queue = info.Own.Players.ToList();

			foreach (var role in Roles)
			{
				queue.Remove(role.Apply(info, queue));
			}
			Scenario.DefaultFieldplay.Apply(info, queue);
		}
Ejemplo n.º 12
0
        public static void Assign(Team my, Team enemy, Ball ball, MatchInfo info)
        {
            My = my;
            Enemy = enemy;
            Ball = ball;
            Info = info;

            LogInfoEnabled = true;

            ballFuturePosition = DistanceUtils.BuildBallFuturePosition(50);
            closest = null;
        }
Ejemplo n.º 13
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            foreach (Player player in myTeam.Players)                                       //Loop over all players in my team.
            {
                Player closestEnemy = player.GetClosest(enemyTeam);                         //Gets the closest enemy player.

                if (ball.Owner == player)                                                   //If this player has the ball.
                    player.ActionShootGoal();                                               //Tell this player to shoot towards the goal, at maximum strength!
                else if (player.CanPickUpBall(ball))
                    player.ActionPickUpBall();
                else player.ActionGo(ball.Position);                                                 //Worst case just go for the ball
            }                                                           //Return myTeam with the teams actions.
        }
Ejemplo n.º 14
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            Pitch.Assign(myTeam, enemyTeam, ball, matchInfo);

            var height = (int)Field.MyGoal.Height;
            var step = height/(myTeam.Players.Count + 1);

            var roles = Enumerable.Range(1, myTeam.Players.Count)
                                  .Zip(myTeam.Players, Tuple.Create)
                                  .Select(p => new GateStander(p.Item2.PlayerType, new Vector(0, Field.MyGoal.Y + p.Item1*step)));
                                  
            foreach (var role in roles)
                role.DoAction();
        }
    private void MatchCallback(bool success, string extendedInfo, MatchInfo responseData)
    {
        if (responseData != null && success)
        {
            MatchInfo hostInfo = responseData;
            NetworkServer.Listen(hostInfo, 9000);

            NetworkManager.singleton.StartHost(hostInfo);
        }
        else
        {
            Debug.LogError("Create match failed");
        }
    }
Ejemplo n.º 16
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            var pitch = new Pitch(myTeam, enemyTeam, ball, matchInfo);

            var height = (int)Field.MyGoal.Height;
            var step = height/(myTeam.Players.Count + 1);

            var roles = Enumerable.Range(1, myTeam.Players.Count)
                .Select(p => new GateStanderRole(new Vector(0, Field.MyGoal.Y + p*step)))
                .Zip(myTeam.Players, Tuple.Create);

            foreach (var role in roles)
                role.Item1.DoAction(role.Item2, pitch);
        }
Ejemplo n.º 17
0
    //this method is called when your request for creating a match is returned
    private void OnInternetMatchCreate(CreateMatchResponse matchResponse)
    {
        if (matchResponse != null && matchResponse.success)
        {
            //Debug.Log("Create match succeeded");

            Utility.SetAccessTokenForNetwork(matchResponse.networkId, new NetworkAccessToken(matchResponse.accessTokenString));
            MatchInfo hostInfo = new MatchInfo(matchResponse);
            NetworkServer.Listen(hostInfo, 9000);

            NetworkManager.singleton.StartHost(hostInfo);
        }
        else
        {
            Debug.LogError("Create match failed");
        }
    }
Ejemplo n.º 18
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            Pitch.Assign(myTeam, enemyTeam, ball, matchInfo);

            if (matchInfo.EnemyTeamScored || matchInfo.MyTeamScored)
            {
                Pitch.Log("=======================================");
                Pitch.Log("Someone scored, game stage set to reset");
                Pitch.Log("=======================================");
                Pitch.Stage = GameStage.Reset;
            }

            SetGameState();

            foreach (var assignedRole in assignedRoles)
                assignedRole.DoAction();
        }
Ejemplo n.º 19
0
    public void OnMatchCreate(CreateMatchResponse matchResponse)
    {
        if (matchResponse.success)
        {
            Debug.Log("Create match succeeded.");
            _lobby.matchCreated = true;
            MatchInfo matchInfo  = new MatchInfo(matchResponse);
            Utility.SetAccessTokenForNetwork(matchResponse.networkId, new NetworkAccessToken(matchResponse.accessTokenString));

            NetworkManager.singleton.StartHost(matchInfo) ;
            NetworkServer.Listen(new MatchInfo(matchResponse), 9000);
        }
        else
        {
            Debug.LogError ("Create match failed.");
        }
    }
Ejemplo n.º 20
0
		public static TurnInfo Create(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
		{
			var info = new TurnInfo()
			{
				Own = myTeam,
				Other = enemyTeam,
				Ball = ball,
				Match = matchInfo,
			};
			info.Path = BallPath.Create(info);
			info.CatchUps = info.Path.GetCatchUp(info.Players).OrderBy(c => c.Turn).ToList();
			info.HasPossession =
				myTeam.Players.Contains(ball.Owner) ||
				myTeam.Players.Any(p => p.CanPickUpBall(ball)) ||
				(info.CatchUps.Any() && myTeam.Players.Contains(info.CatchUps[0].Player));

			return info;
		}
Ejemplo n.º 21
0
        public void Action(Team myTeam, Team enemyTeam, Ball ball, MatchInfo matchInfo)
        {
            if (!inAttack && ball.Owner != null && ball.Owner.Team == myTeam)
            {
                inAttack = true;
            }
            if (inAttack && ball.Owner != null && ball.Owner.Team == enemyTeam)
            {
                inAttack = false;
            }

            var game = new Game(matchInfo, ball, enemyTeam, myTeam, inAttack);


            foreach (var kv in players)
            {
                kv.Value.DoAction(game, myTeam.Players.First(pl => pl.PlayerType == kv.Key));
            }
        }
Ejemplo n.º 22
0
 private void HandleJoinedMatch(bool success, string extendedInfo, MatchInfo responseData)
 {
     StartClient(responseData);
 }
Ejemplo n.º 23
0
    public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
    {
        base.OnMatchCreate(success, extendedInfo, matchInfo);

        mUL_CurrentMatchID = (ulong)matchInfo.networkId;
    }
 private void SetMatchInfo(MatchInfo matchInfo)
 {
     matchInfo.PrematchNotes = PrematchNotes;
 }
 public override void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
 {
     base.OnMatchJoined(success, extendedInfo, matchInfo);
     Debug.Log("Match is joined");
 }
 private void MatchMaker_OnJoinMatch(bool success, string extendedInfo, MatchInfo responseData)
 {
     OnMatchJoined(success, extendedInfo, responseData);
 }
Ejemplo n.º 27
0
 public void OnMatchCreate(bool success, string info, MatchInfo matchInfo)
 {
     MainMenu.connecting = false;
     manager.OnMatchCreate(success, info, matchInfo);
 }
Ejemplo n.º 28
0
 protected override void OnMatchInfoDownloaded(MatchInfo matchInfo)
 {
     mainPlayerName.text = matchInfo.bots [0].name;
     secondaryPlayerName.text = matchInfo.bots [1].name;
 }
Ejemplo n.º 29
0
 public void AddMatch(MatchInfo.MatchInfoId matchId, MatchInfo match)
 {
     A.CallTo(() => storage.GetMatch(matchId)).Returns(match);
 }
Ejemplo n.º 30
0
 public void Connect(MatchInfo matchInfo)
 {
     this.PrepareForConnect();
     this.ConnectWithRelay(matchInfo);
 }
Ejemplo n.º 31
0
 protected virtual bool EditMatch(MatchInfo match, bool readOnly)
 {
     return(fSwissMatchEdit.Edit(match, readOnly));
 }
Ejemplo n.º 32
0
    IEnumerator UpdateGridAfterMatch(MatchInfo match)
    {
        if(match.matchStartingY == match.matchEndingY)
        {
            //match Horizontal
            for(int x = match.matchStartingX; x <= match.matchEndingX; x++)
            {
                for(int y = match.matchStartingY; y < ySize - 1; y++)
                {
                    GridItem upperIndex = _item[x, y + 1];
                    GridItem current = _item[x, y];
                    _item[x, y] = upperIndex;
                    _item[x, y + 1] = current;
                    _item[x, y].OnItemPositionChanged(_item[x, y].x, _item[x, y].y - 1);
                }
                _item[x, ySize - 1] = InstantiateJewels(x, ySize - 1);
            }
        }
        else if( match.matchEndingX == match.matchStartingX)
        {
            int matchHeight = 1 + (match.matchEndingY - match.matchStartingY);
            for(int y = match.matchStartingY + matchHeight; y <= ySize - 1; y++)
            {
                GridItem lowerIndex = _item[match.matchStartingX, y - matchHeight];
                GridItem current = _item[match.matchStartingX, y];
                _item[match.matchStartingX, y - matchHeight] = current;
                _item[match.matchStartingX, y] = lowerIndex;
            }
            for(int y = 0; y < ySize - matchHeight; y++)
            {
                _item[match.matchStartingX, y].OnItemPositionChanged(match.matchStartingX, y);
            }
            for(int i = 0; i< match.match.Count; i++)
            {
                _item[match.matchStartingX,(ySize-1)-i] = InstantiateJewels(match.matchStartingX,(ySize-1)-i);
            }

            for (int x = 0; x < xSize; x++)
            {
                for (int y = 0; y < ySize; y++)
                {
                    MatchInfo matchInfo = GetMatchInformation(_item[x, y]);
                    if (matchInfo.validMatch)
                    {
                       // yield return new WaitForSeconds(delayBetweenMatches);
                        yield return StartCoroutine(DestroyItem(matchInfo.match));
                        yield return new WaitForSeconds(delayBetweenMatches);
                        yield return StartCoroutine(UpdateGridAfterMatch(matchInfo));
                    }
                }
            }

        }
    }
Ejemplo n.º 33
0
 MatchInfo GetMatchInformation(GridItem item)
 {
     MatchInfo m = new MatchInfo();
     m.match = null;
     List<GridItem> hMatch = SearchHorizontally(item);
     List<GridItem> vMatch = SearchVertically(item);
     if(hMatch.Count >= minItemForMatch && hMatch.Count > vMatch.Count)
     {
         m.matchStartingX = GetMinimumX(hMatch);
         m.matchEndingX = GetMaximumX(hMatch);
         m.matchStartingY = m.matchEndingY = hMatch[0].y;
         m.match = hMatch;
     }
     else if(vMatch.Count >= minItemForMatch)
     {
         m.matchStartingY = GetMinimumY(vMatch);
         m.matchEndingY = GetMaximumY(vMatch);
         m.matchStartingX = m.matchEndingX = vMatch[0].x;
         m.match = vMatch;
     }
     return m;
 }
Ejemplo n.º 34
0
 public void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
 {
     Debug.Log("Joined");
 }
Ejemplo n.º 35
0
 public void Connect(MatchInfo matchInfo)
 {
     PrepareForConnect();
     ConnectWithRelay(matchInfo);
 }
Ejemplo n.º 36
0
 private void OnMatchCreated(bool success, string extendedinfo, MatchInfo responsedata)
 {
     base.StartHost(responsedata);
 }
Ejemplo n.º 37
0
    //this method is called when your request to join a match is returned
    private void OnJoinInternetMatch(JoinMatchResponse matchJoin)
    {
        if (matchJoin.success)
        {
            Debug.Log("Able to join a match");

            if (Utility.GetAccessTokenForNetwork(matchJoin.networkId) == null)
                Utility.SetAccessTokenForNetwork(matchJoin.networkId, new NetworkAccessToken(matchJoin.accessTokenString));

            MatchInfo hostInfo = new MatchInfo(matchJoin);
            NetworkManager.singleton.StartClient(hostInfo);
            Debug.Log("client connect");
        }
        else
        {
            Debug.LogError("Join match failed");

        }
    }
Ejemplo n.º 38
0
        public override bool SeedPlayers()
        {
            SeedingArgs args = SeedingArgs.Empty;

            args.LastPlayerWithBay = 0;
            int round = 0;

            foreach (MatchInfo match in Competition.Matches.Values)
            {
                // Определяем какой игрок в последнием раунде играл с баем
                if (match.PlayerA.Id == 0 && match.Label.Round >= round)
                {
                    args.LastPlayerWithBay = match.PlayerB.Id;
                }
                if (match.PlayerB.Id == 0 && match.Label.Round >= round)
                {
                    args.LastPlayerWithBay = match.PlayerA.Id;
                }

                if (match.Label.Round > round)
                {
                    round = match.Label.Round;
                }
            }
            round++;
            // Список игрков для матчей
            CompetitionPlayerList players = new CompetitionPlayerList();

            foreach (CompetitionPlayerInfo player in GetPlayersToSeed())
            {
                if (round > 1)
                {
                    player.SeedNo = 0;
                }
                players.Add(player.Id, player);
            }
            args.PlayersToSeed = players;
            args.SeedOrder     = GetDrawOrder(args.PlayersToSeed.Count);
            args.SeedType      = Seeding.SeedType.Matches;
            args.AllowRating   = false;

            Dictionary <int, int> current_points = new Dictionary <int, int>(); // Текущее количество набранных игроками очков


            if (round == 1 || fGraphicalSeeding.Seed(args))
            {
                SeedPair[] new_mtchs = new SeedPair[players.Count / 2]; // Список новых матчей
                foreach (CompetitionPlayerInfo player in args.PlayersToSeed.Values)
                {
                    current_points.Add(player.Id, player.AvailablePoints);
                    int seed_index = player.SeedNo - 1;
                    if (seed_index >= 0)
                    {
                        int match_index = seed_index % new_mtchs.Length;
                        if (new_mtchs[match_index] == null)
                        {
                            new_mtchs[match_index] = new SeedPair(0, 0);
                        }
                        if (seed_index < new_mtchs.Length)
                        {
                            new_mtchs[match_index].playerIdA = player.Id;
                        }
                        else
                        {
                            new_mtchs[match_index].playerIdB = player.Id;
                        }
                    }
                }
                int match_no = 1;
                foreach (SeedPair pair in new_mtchs)
                {
                    MatchInfo match = CreateMatch(pair);

                    // Устанавливаем максимальное количество очков в партии
                    if (match.PlayerA.Id > 0 && match.PlayerB.Id > 0)
                    {
                        match.PlayerA.Tag = current_points[match.PlayerA.Id];
                        match.PlayerB.Tag = current_points[match.PlayerB.Id];
                    }

                    match.Label.Division = 1;
                    match.Label.Round    = round;
                    match.Label.MatchNo  = match_no;
                    TA.DB.Manager.DatabaseManager.CurrentDb.CreateMatch(Competition.Info.Id, match);
                    Competition.Matches.Add(match.Id, match);
                    match_no++;
                }
            }

            /**********************************************************************/

            /* int round = 0;
             *
             * int[] plrs = new int[players.Count];  // Список игроков для рассеивания
             * SeedPair[] mtchs = new SeedPair[Competition.Matches.Values.Count]; // Список сыгранных матчей
             * SeedPair[] new_mtchs = new SeedPair[players.Count / 2]; // Список новых матчей
             * Dictionary<int, int> current_points = new Dictionary<int, int>(); // Текущее количество набранных игроками очков
             * int index = 0;
             * foreach (CompetitionPlayerInfo player in players)
             * {
             *   plrs[index++] = player.Id;
             *   current_points.Add(player.Id, player.AvailablePoints);
             * }
             * index = 0;
             * foreach (MatchInfo match in Competition.Matches.Values)
             * {
             *   mtchs[index++] = new SeedPair(match.PlayerA.Id, match.PlayerB.Id);
             *   if (match.Label.Round > round)
             *       round = match.Label.Round;
             * }
             * round++;
             * // формируем пары для следующего раунда
             * if (!SwissSeeder.Seed(plrs, mtchs, new_mtchs, 0))
             *   throw new Exception("Draw error");
             *
             * // Создаем матчи и добавляем их в список матчей
             * int match_no = 1;
             * foreach (SeedPair pair in new_mtchs)
             * {
             *   MatchInfo match = CreateMatch(pair);
             *
             *   // Устанавливаем максимальное количество очков в партии
             *   if (match.PlayerA.Id > 0 && match.PlayerB.Id > 0)
             *   {
             *       match.PlayerA.Tag = current_points[match.PlayerA.Id];
             *       match.PlayerB.Tag = current_points[match.PlayerB.Id];
             *   }
             *
             *   match.Label.Division = 1;
             *   match.Label.Round = round;
             *   match.Label.MatchNo = match_no;
             *   TA.DB.Manager.DatabaseManager.CurrentDb.CreateMatch(Competition.Info.Id, match);
             *   Competition.Matches.Add(match.Id, match);
             *   match_no++;
             * }*/
            return(true);
        }
Ejemplo n.º 39
0
		internal async void CacheMatchInfo()
		{
			if(!_matchInfoCacheInvalid)
				return;
			_matchInfoCacheInvalid = false;
			MatchInfo matchInfo;
			while((matchInfo = HearthMirror.Reflection.GetMatchInfo()) == null || matchInfo.LocalPlayer == null || matchInfo.OpposingPlayer == null)
				await Task.Delay(1000);
			Log.Info($"{matchInfo.LocalPlayer.Name} vs {matchInfo.OpposingPlayer.Name}");
			_matchInfo = matchInfo;
			Player.Name = matchInfo.LocalPlayer.Name;
			Opponent.Name = matchInfo.OpposingPlayer.Name;
			Player.Id = matchInfo.LocalPlayer.Id;
			Opponent.Id = matchInfo.OpposingPlayer.Id;
		}
Ejemplo n.º 40
0
 public virtual void DeployHost(MatchInfo matchInfo)
 {
     NetworkManager.singleton.StartHost(matchInfo);
 }
Ejemplo n.º 41
0
    public void UpdateMatchInfo(MatchInfo matchInfo)
    {
        MatchInfo = matchInfo;

        //print(MatchInfo.StadiumName);
    }
Ejemplo n.º 42
0
        public TwoWayResult PlayMatch(Guid matchId)
        {
            var m = factory.GetGame(matchId, true);

            m.RestartMatch();
            //send the match info
            string player1ClientId = factory.GetPlayerPresence().GetClientId(m.Player1);
            string player2ClientId = factory.GetPlayerPresence().GetClientId(m.Player2);

            //verify the client id
            if (Context.ConnectionId != player1ClientId && Context.ConnectionId != player2ClientId)
            {
                //cannot determine the ID of the caller
                dynamic call = new ClientCall {
                    CallerId = Context.ConnectionId, ClientId = Context.ConnectionId
                };
                call.game.identityError();
                //Caller.identityError();
                return(new TwoWayResult(call));
            }
            //create a group for this match
            //base.GroupManager.AddToGroup(player1ClientId, string.Format("match_", id));
            //base.GroupManager.AddToGroup(player2ClientId, string.Format("match_", id));

            string player1Name = factory.GetPlayerPresence().GetPlayerNameByClientId(player1ClientId);
            string player2Name = factory.GetPlayerPresence().GetPlayerNameByClientId(player2ClientId);
            var    mi          = new MatchInfo
            {
                MatchId         = m.MatchId,
                Player1         = m.Player1,
                Player2         = m.Player2,
                Turn            = m.Turn,
                Player1ClientId = player1ClientId,
                Player2ClientId = player2ClientId,
                OponentClientId = player1ClientId == Context.ConnectionId ? player2ClientId : player1ClientId,
                PlayerId        = player1ClientId == Context.ConnectionId ? m.Player1 : m.Player2,
                MyPlayerName    = player1ClientId == Context.ConnectionId ? player1Name : player2Name,
                OtherPlayerName = player1ClientId == Context.ConnectionId ? player2Name : player1Name
            };
            Guid iam = player1ClientId == Context.ConnectionId ? m.Player1 : m.Player2;

            mi.Units = m.Units.Where(u => u.PlayerId == iam).Select(u =>
                                                                    new UnitInfo
            {
                UnitId    = u.UnitId,
                PlayerId  = u.PlayerId,
                Name      = u.Name,
                MaxHealth = u.MaxHealth,
                Health    = u.Health,
                Col       = u.Column,
                Row       = u.Row
            }
                                                                    ).ToArray();
            //send the match info to the player
            //Caller.matchReady(mi);
            dynamic call2 = new ClientCall {
                CallerId = Context.ConnectionId, ClientId = Context.ConnectionId
            };

            call2.game.matchReady(mi);
            return(new TwoWayResult(call2));
        }
Ejemplo n.º 43
0
        public static MatchInfo ParseMatchInfo(String json)
        {
            MatchInfo matchInfo = JsonConvert.DeserializeObject <MatchInfo>(json);

            return(matchInfo);
        }
Ejemplo n.º 44
0
 /// <summary>
 /// 新增比赛
 /// </summary>
 /// <param name="gameMatch"></param>
 public void InsertMatchInfo(MatchInfo gameMatch)
 {
     gameMatchData.InsertMatchInfo(gameMatch);
 }
 public void OnEventRaised(MatchInfo message)
 {
     Response.Invoke(message);
 }
Ejemplo n.º 46
0
 /// <summary>
 /// 更新比赛
 /// </summary>
 /// <param name="gameMatch"></param>
 public void UpdateMatchInfo(MatchInfo gameMatch)
 {
     gameMatchData.UpdateMatchInfo(gameMatch);
 }
Ejemplo n.º 47
0
 private void OnMatchCreated(bool success, string extendedInfo, MatchInfo responseData)
 {
     GlobalVariables.IsHost = true;
     myClient = StartHost();
 }
Ejemplo n.º 48
0
 public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
 {
     base.OnMatchCreate(success, extendedInfo, matchInfo);
     _currentMatchID = (System.UInt64)matchInfo.networkId;
 }
Ejemplo n.º 49
0
        /// <summary> 获取场次信息 </summary>
        /// <param name="type">0为未开始,1为开始,2为结束</param>
        public static List <MatchInfo> GetMatch(int type = 0)
        {
            var matchInfos = new List <MatchInfo>();

            try
            {
                using (var pass = MysqlHelper.ExecuteReader(string.Format("SELECT * FROM sessions INNER JOIN key_table on sessions.session_id=key_table.session_id and sessions.`status`={0}", type)))
                {
                    while (pass.HasRows)
                    {
                        try
                        {
                            if (pass.Read())
                            {
                                var info = new MatchInfo();
                                if (pass["session_id"] != DBNull.Value)
                                {
                                    info.SessionId = pass.GetInt32("session_id");
                                }
                                if (pass["create_date"] != DBNull.Value)
                                {
                                    info.CreateDate = pass.GetDateTime("create_date");
                                }
                                if (pass["session_name"] != DBNull.Value)
                                {
                                    info.SessionName = pass.GetString("session_name");
                                }
                                if (pass["session_date"] != DBNull.Value)
                                {
                                    info.SessionDate = pass.GetDateTime("session_date");
                                }
                                if (pass["date_start"] != DBNull.Value)
                                {
                                    info.DateStart = pass.GetDateTime("date_start");
                                }
                                if (pass["date_end"] != DBNull.Value)
                                {
                                    info.DateEnd = pass.GetDateTime("date_end");
                                }
                                if (pass["check_rule"] != DBNull.Value)
                                {
                                    info.CheckRule = pass.GetInt32("check_rule");
                                }
                                if (pass["status"] != DBNull.Value)
                                {
                                    info.Status = pass.GetInt32("status");
                                }
                                if (pass["remark"] != DBNull.Value)
                                {
                                    info.Remark = pass.GetString("remark");
                                }
                                if (pass["key_content"] != DBNull.Value)
                                {
                                    info.Key = pass.GetString("key_content");
                                }
                                matchInfos.Add(info);
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.ToSaveLog("GetMatch:");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToSaveLog("获取场次信息GetMatch:");
            }

            return(matchInfos);
        }
Ejemplo n.º 50
0
        public override void Close()
        {
            if (stream != null)
            {
                if (mode == CompressionMode.Decompress)
                {
                    readBuf = null;
                }
                else
                {
                    byte[] inputBuf = writeBuf.GetBuffer();
                    int bufPos = 0;
                    int bufStart = bufPos;
                    int bufSize = (int)writeBuf.Length;

                    BinaryWriter writer = new BinaryWriter(stream);
                    byte[] format = { (byte)'Z', (byte)'L', (byte)'C', (byte)'2' };
                    writer.Write(format);
                    writer.Write(bufSize);

                    int outPos = 0;
                    int j = 8;
                    int bufEndPos = bufSize;

                    MatchInfo[] matches = new MatchInfo[0x1000];
                    for (int i = 0; i < matches.Length; i++)
                        matches[i] = new MatchInfo();
                    MatchInfo[] matchMap = new MatchInfo[0x1000000];
                    int addPos = 0;

                    byte[] codeBlock = new byte[1+2*8];
                    while (true)
                    {
                        if (j==8)
                        {
                            writer.Write(codeBlock, 0, outPos);
                            codeBlock[0] = 0;
                            outPos = 1;
                            j = 0;
                        }
                        if (bufPos == bufEndPos) break;

                        int matchDist = 0;
                        int matchLen = 0;
                        MatchInfo m = matchMap[0xFFFFFF & BitConverter.ToInt32(inputBuf, bufPos)];
                        for (int p=0; m != null && p<50; p++) {
                            int len = 3;
                            while (inputBuf[m.pos + len] == inputBuf[bufPos + len] && len < 18) len++;

                            if (len > matchLen) {
                                matchLen = len;
                                matchDist = bufPos - m.pos;
                            }
                            m = m.prev;
                        }
                        if (bufPos + matchLen > bufEndPos) {
                            matchLen = bufEndPos - bufPos;
                        }

                        int bp = bufPos;
                        if (matchLen >= 3) {
                            codeBlock[0] |= (byte)(1<<(7-j));
                            codeBlock[outPos++] = (byte)matchDist;
                            codeBlock[outPos++] = (byte)(((matchDist&0xF00)>>4) + (matchLen-3));
                            bufPos += matchLen;
                        }
                        else {
                            codeBlock[outPos++] = inputBuf[bufPos++];
                        }
                        while(bp < bufPos) {
                            MatchInfo m2 = matches[addPos];

                            int index = (0xFFFFFF & BitConverter.ToInt32(inputBuf, bp));
                            if (m2.next != null) {
                                m2.next.prev = null;
                                m2.next = null;
                            }
                            else if (m2.pos > 0) {
                                matchMap[(0xFFFFFF & BitConverter.ToInt32(inputBuf, m2.pos))] = null;
                            }
                            m2.prev = matchMap[index];
                            matchMap[index] = m2;
                            if (m2.prev != null) {
                                m2.prev.next = m2;
                            }
                            m2.pos = bp;

                            bp++;
                            if (++addPos == 0x1000 - 18) addPos = 0;
                        }

                        j++;
                    }
                    writer.Write(codeBlock, 0, outPos);

                    writeBuf.Close();
                    writeBuf = null;
                }

                if (!leaveOpen)
                {
                    stream.Close();
                }

                stream = null;
            }
        }
Ejemplo n.º 51
0
 public void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
 {
     Debug.Log("Created");
 }
 private void OnJoinInternetMatch(bool success, string extendedInfo, MatchInfo responseData)
 {
     if (success)
     {
         MatchInfo hostInfo = responseData;
         NetworkManager.singleton.StartClient(hostInfo);
     }
     else
     {
         Debug.LogError("Join match failed");
     }
 }
Ejemplo n.º 53
0
    public static void CreateMatchInfo(MatchInfo match, out CDataGCCStrike15_v2_MatchInfo matchInfo, out ExtraMatchStats extraStats, System.Threading.CancellationToken cancelToken)
    {
        matchInfo  = null;
        extraStats = null;
        if (match.availableOffline)
        {
            CDataGCCStrike15_v2_MatchInfo tempMatchInfo = new CDataGCCStrike15_v2_MatchInfo();
            ExtraMatchStats tempExtraStats = new ExtraMatchStats();

            #region File Name Data
            ulong reservationId          = 0;
            bool  reservationIdSpecified = false;

            string[] fileNameSplits = match.fileName.Split('_');
            if (match.fileName.IndexOf("match730_") == 0 && fileNameSplits.Length == 4)
            {
                try
                {
                    reservationId          = Convert.ToUInt64(fileNameSplits[1]);
                    reservationIdSpecified = true;

                    WatchableMatchInfo watchablematchinfo = new WatchableMatchInfo();
                    watchablematchinfo.tv_port       = Convert.ToUInt32(fileNameSplits[2]);
                    watchablematchinfo.server_ip     = Convert.ToUInt32(fileNameSplits[3]);
                    tempMatchInfo.watchablematchinfo = watchablematchinfo;
                }
                catch (Exception)
                { }
            }
            #endregion

            using (FileStream fileStream = File.Open(match.GetMatchFilePath(), FileMode.Open, FileAccess.Read))
                using (DemoInfo.DemoParser dp = new DemoInfo.DemoParser(fileStream))
                {
                    #region Data Analysis
                    #region Match Info Variables
                    int matchStartTick = 0;

                    CMsgGCCStrike15_v2_MatchmakingServerRoundStats currentRoundStats = null;
                    Dictionary <uint, int>         totalAssists        = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalDeaths         = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalEnemyHeadshots = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalEnemyKills     = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalKills          = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalMvps           = new Dictionary <uint, int>();
                    Dictionary <uint, int>         totalScores         = new Dictionary <uint, int>();
                    List <List <DemoInfo.Player> > playerTeams         = new List <List <DemoInfo.Player> >();

                    //List<uint> accountIds = new List<uint>();
                    int[] totalTeamScore = new int[2];
                    #endregion

                    Action <uint> AddPlayerToCurrentRound = (accountId) =>
                    {
                        currentRoundStats.reservation.account_ids.Add(accountId);
                        currentRoundStats.assists.Add(0);
                        currentRoundStats.deaths.Add(0);
                        currentRoundStats.enemy_headshots.Add(0);
                        currentRoundStats.enemy_kills.Add(0);
                        currentRoundStats.kills.Add(0);
                        currentRoundStats.mvps.Add(0);
                        currentRoundStats.scores.Add(0);
                    };
                    Func <uint, int> GetPlayerIndex = (accountId) =>
                    {
                        int playerIndex = currentRoundStats.reservation.account_ids.IndexOf(accountId);
                        if (playerIndex < 0)
                        {
                            AddPlayerToCurrentRound(accountId);
                            playerIndex = currentRoundStats.reservation.account_ids.Count - 1;
                        }
                        return(playerIndex);
                    };

                    EventHandler <DemoInfo.MatchStartedEventArgs> matchStartedHandler = (obj, msea) =>
                    {
                        matchStartTick = dp.CurrentTick;

                        foreach (var player in dp.PlayerInformations)
                        {
                            if (player != null && player.SteamID > 0)
                            {
                                uint accountId = new SteamKit2.SteamID((ulong)player.SteamID).AccountID;

                                #region Extra Stats Data
                                tempExtraStats.accountIds.Add(accountId);
                                tempExtraStats.playerNames.Add(player.Name);
                                #endregion

                                var teamToAddTo = playerTeams.Find((team) => team.Exists((teamPlayer) => teamPlayer.Team == player.Team));
                                if (teamToAddTo == null)
                                {
                                    teamToAddTo = new List <DemoInfo.Player>();
                                    playerTeams.Add(teamToAddTo);
                                }
                                teamToAddTo.Add(player);
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundStartedEventArgs> roundStartedHandler = (obj, rsea) =>
                    {
                        #region Match Info Data
                        currentRoundStats = new CMsgGCCStrike15_v2_MatchmakingServerRoundStats();
                        tempMatchInfo.roundstatsall.Add(currentRoundStats);

                        currentRoundStats.team_scores.AddRange(totalTeamScore);

                        CMsgGCCStrike15_v2_MatchmakingGC2ServerReserve reservation = new CMsgGCCStrike15_v2_MatchmakingGC2ServerReserve();
                        currentRoundStats.reservation = reservation;
                        foreach (var player in dp.PlayerInformations)
                        {
                            if (player != null && player.SteamID > 0)
                            {
                                AddPlayerToCurrentRound(new SteamKit2.SteamID((ulong)player.SteamID).AccountID);
                            }
                        }
                        #endregion
                        #region Extra Stats Data
                        tempExtraStats.roundStartTicks.Add(dp.CurrentTick);
                        #endregion
                    };
                    EventHandler <DemoInfo.PlayerKilledEventArgs> playerKilledHandler = (obj, pkea) =>
                    {
                        if (currentRoundStats != null)
                        {
                            if (pkea.Victim?.SteamID > 0)
                            {
                                uint victimAccountId = new SteamKit2.SteamID((ulong)pkea.Victim.SteamID).AccountID;
                                int  victimIndex     = GetPlayerIndex(victimAccountId);
                                UnityEngine.Debug.Assert(victimIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + victimIndex + " accountId: " + victimAccountId + " name " + pkea.Victim.Name);
                                if (victimIndex > -1)
                                {
                                    if (!totalDeaths.ContainsKey(victimAccountId))
                                    {
                                        totalDeaths[victimAccountId] = 0;
                                    }
                                    currentRoundStats.deaths[victimIndex] = ++totalDeaths[victimAccountId];
                                }
                            }
                            if (pkea.Killer?.SteamID > 0)
                            {
                                uint killerAccountId = new SteamKit2.SteamID((ulong)pkea.Killer.SteamID).AccountID;
                                int  killerIndex     = GetPlayerIndex(killerAccountId);
                                UnityEngine.Debug.Assert(killerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + killerIndex + " accountId: " + killerAccountId + " name " + pkea.Killer.Name);
                                if (killerIndex > -1)
                                {
                                    if (!totalKills.ContainsKey(killerAccountId))
                                    {
                                        totalKills[killerAccountId] = 0;
                                    }
                                    currentRoundStats.kills[killerIndex] = ++totalKills[killerAccountId];

                                    bool enemyKill = pkea.Victim.TeamID != pkea.Killer.TeamID;
                                    if (!totalEnemyKills.ContainsKey(killerAccountId))
                                    {
                                        totalEnemyKills[killerAccountId] = 0;
                                    }
                                    currentRoundStats.enemy_kills[killerIndex] += enemyKill ? ++totalEnemyKills[killerAccountId] : 0;
                                    if (!totalEnemyHeadshots.ContainsKey(killerAccountId))
                                    {
                                        totalEnemyHeadshots[killerAccountId] = 0;
                                    }
                                    currentRoundStats.enemy_headshots[killerIndex] += enemyKill && pkea.Headshot ? ++totalEnemyHeadshots[killerAccountId] : 0;
                                }
                            }
                            if (pkea.Assister?.SteamID > 0)
                            {
                                uint assisterAccountId = new SteamKit2.SteamID((ulong)pkea.Assister.SteamID).AccountID;
                                int  assisterIndex     = GetPlayerIndex(assisterAccountId);
                                UnityEngine.Debug.Assert(assisterIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + assisterIndex + " accountId: " + assisterAccountId + " name " + pkea.Assister.Name);
                                if (assisterIndex > -1)
                                {
                                    if (!totalAssists.ContainsKey(assisterAccountId))
                                    {
                                        totalAssists[assisterAccountId] = 0;
                                    }
                                    currentRoundStats.assists[assisterIndex] = ++totalAssists[assisterAccountId];
                                }
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundMVPEventArgs> roundMVPHandler = (obj, rmea) =>
                    {
                        if (rmea.Player?.SteamID > 0)
                        {
                            uint playerAccountId = new SteamKit2.SteamID((ulong)rmea.Player.SteamID).AccountID;
                            if (!totalMvps.ContainsKey(playerAccountId))
                            {
                                totalMvps[playerAccountId] = 0;
                            }

                            int playerIndex = GetPlayerIndex(playerAccountId);
                            UnityEngine.Debug.Assert(playerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + playerIndex + " accountId: " + playerAccountId + " name " + rmea.Player.Name);
                            if (playerIndex > -1 && playerIndex < currentRoundStats.mvps.Count)
                            {
                                currentRoundStats.mvps[playerIndex] = ++totalMvps[playerAccountId];
                            }
                        }
                    };
                    EventHandler <DemoInfo.RoundEndedEventArgs> roundEndedHandler = (obj, reea) =>
                    {
                        #region Match Info Data
                        Debug.Assert(currentRoundStats != null, "How can you end a round without starting it!? @tick " + dp.CurrentTick);
                        if (currentRoundStats != null)
                        {
                            if (reea.Winner != DemoInfo.Team.Spectate)
                            {
                                int teamIndex = playerTeams.FindIndex((team) => team[0].Team == reea.Winner);
                                if (teamIndex > -1 && teamIndex < totalTeamScore.Length)
                                {
                                    currentRoundStats.team_scores[teamIndex] = ++totalTeamScore[teamIndex];
                                }
                            }
                            currentRoundStats.match_duration = (int)((dp.CurrentTick - matchStartTick) * dp.TickTime);

                            foreach (var player in dp.PlayerInformations)
                            {
                                if (player != null && player.SteamID > 0)
                                {
                                    uint playerAccountId = new SteamKit2.SteamID((ulong)player.SteamID).AccountID;
                                    int  playerIndex     = GetPlayerIndex(playerAccountId);
                                    Debug.Assert(playerIndex > -1, "How do we not have this player yet?? @tick " + dp.CurrentTick + " index: " + playerIndex + " accountId: " + playerAccountId + " name " + player.Name);
                                    currentRoundStats.scores[playerIndex] = player.AdditionaInformations.Score;
                                }
                            }
                        }
                        #endregion
                        #region Extra Stats Data
                        tempExtraStats.roundEndTicks.Add(dp.CurrentTick);
                        tempExtraStats.roundWinner.Add((int)reea.Winner);
                        #endregion
                    };
                    #endregion

                    dp.MatchStarted += matchStartedHandler;
                    dp.RoundStart   += roundStartedHandler;
                    dp.PlayerKilled += playerKilledHandler;
                    dp.RoundMVP     += roundMVPHandler;
                    dp.RoundEnd     += roundEndedHandler;

                    dp.ParseHeader();
                    while (dp.ParseNextTick() && !cancelToken.IsCancellationRequested)
                    {
                        match.infoProgress = dp.CurrentTick / (float)dp.Header.PlaybackFrames;
                    }

                    dp.MatchStarted -= matchStartedHandler;
                    dp.RoundStart   -= roundStartedHandler;
                    dp.PlayerKilled -= playerKilledHandler;
                    dp.RoundMVP     -= roundMVPHandler;
                    dp.RoundEnd     -= roundEndedHandler;

                    #region Last round stats
                    if (reservationIdSpecified)
                    {
                        currentRoundStats.reservationid = reservationId;
                    }
                    currentRoundStats.reservation.game_type = (uint)(GameType)Enum.Parse(typeof(GameType), dp.Map);

                    if (totalTeamScore[0] != totalTeamScore[1])
                    {
                        var winningTeam = (DemoInfo.Team)currentRoundStats.round_result;
                        currentRoundStats.match_result = (winningTeam == DemoInfo.Team.Terrorist ? 1 : 2); //1 is CT, 2 is T. I do the switching because of team switching at half
                    }
                    else
                    {
                        currentRoundStats.match_result = 0;
                    }
                    #endregion
                }

            if (cancelToken.IsCancellationRequested)
            {
                tempMatchInfo  = null;
                tempExtraStats = null;
            }
            matchInfo  = tempMatchInfo;
            extraStats = tempExtraStats;
        }
    }
 private void MatchMaker_OnCreateMatch(bool success, string extendedInfo, MatchInfo responseData)
 {
     OnMatchCreate(success, extendedInfo, responseData);
 }
Ejemplo n.º 55
0
    public void dieCryHasSound()
    {
        MatchInfo matchInfo = GameObject.FindObjectOfType <MatchInfo>();

        matchInfo.AudioClipPlayer(dieCryClip);
    }
Ejemplo n.º 56
0
    //  this method is called when your request to join a match is returned
    private void OnJoinInternetMatch(JoinMatchResponse matchJoin)
    {
        if (matchJoin.success)
        {
            Debug.Log("Able to join a match");

            if (Utility.GetAccessTokenForNetwork(matchJoin.networkId) == null)
                Utility.SetAccessTokenForNetwork(matchJoin.networkId, new NetworkAccessToken(matchJoin.accessTokenString));

            MatchInfo hostInfo = new MatchInfo(matchJoin);
            NetworkManager.singleton.StartClient(hostInfo);

            // myNBP.CmdSendPositionToServer(true);
            //  customNetworkBluePrint.CmdSendPositionToServer(true);

        }
        else
        {
            Debug.LogError("Join match failed");

        }
    }
Ejemplo n.º 57
0
    IEnumerator UpdateBoardIndices(MatchInfo match)
    {
        int minX = match.GetMinX(); // Minimum match horizontal position
        int maxX = match.GetMaxX(); // Maximum match horizontal position
        int minY = match.GetMinY(); // Minimum match vertical position
        int maxY = match.GetMaxY(); // Maximum match vertical position

        List <Item> fallingItems = new List <Item> {
        };                                              // List to hold items that must fall

        if (minY == maxY)                               // Horizontal match, we have to update several columns (for the remaining upper items)
        {
            for (int i = minX; i <= maxX; i++)          //Loop through horizontal positions
            {
                for (int j = minY; j < height - 1; j++) //Loop through vertical positions above match
                {
                    Item upperIndex = _items[i, j + 1];
                    Item current    = _items[i, j];

                    // Do the swappingz
                    _items[i, j]     = upperIndex;
                    _items[i, j + 1] = current;
                    _items[i, j].SetPosition(_items[i, j].x, _items[i, j].y - 1);
                    fallingItems.Add(_items[i, j]); // Set the item to fall
                }

                // Fill empty space with new random item
                _items[i, height - 1] = InstantiateDoddle(i, height - 1, 0, 1);
                Item newItem = _items[i, height - 1];
                fallingItems.Add(newItem); // Fall this new item
            }
        }
        else if (minX == maxX) // Vertical match, we have to update just one column
        {
            int matchHeight = (maxY - minY) + 1;
            int currentX    = minX;
            for (int j = minY + matchHeight; j <= height - 1; j++) // Loop throught vertical positions above match
            {
                Item lowerIndex = _items[currentX, j - matchHeight];
                Item current    = _items[currentX, j];

                //Do the swappingz
                _items[currentX, j - matchHeight] = current;
                _items[currentX, j] = lowerIndex;
            }

            for (int y = 0; y < height - matchHeight; y++) // Update all items on column
            {
                _items[currentX, y].SetPosition(currentX, y);
                fallingItems.Add(_items[currentX, y]);
            }
            for (int i = 0; i < match.Count; i++)                                                 // Loop through match count
            {
                int newYPos = (height - 1) - i;                                                   // Vertical position for the new item
                _items[currentX, newYPos] = InstantiateDoddle(currentX, newYPos, 0, match.Count); // Instantiate new item
                fallingItems.Add(_items[currentX, newYPos]);                                      // Set new item to fall
            }
        }

        yield return(StartCoroutine(FallItems(fallingItems))); // Fall all items setted to fall and waits for finish

        CheckForMatches();                                     // Check for more matches after update

        bool hasPossibleMoves = CheckForPossibleMoves();

        if (!hasPossibleMoves)
        {
            Debug.Log("No more possible moves. Shuffling board.");
            ShuffleBoard(new System.Random());
        }
        ;

        yield return(null);
    }
Ejemplo n.º 58
0
 private void OnMatchCreated(bool success, string extendedInfo, MatchInfo responseData)
 {
     base.StartHost(responseData);
     RefreshMatches();
 }
Ejemplo n.º 59
0
 public virtual void OnMatchCreated(bool success, string extendedInfo, MatchInfo info)
 {
     this.OnMatchCreatedEvent?.Invoke(success, extendedInfo, info);
 }
        void PopulateMatchInfo()
        {
            gVar.dictMIdIdent = new Dictionary<int, string>();

            for (int i = 0; i < jsonMatches.Count; i++)
            {
                string score = jsonMatches[i]["match"]["scores_csv"];
                int p1score = 0;
                int p2score = 0;
                if (score == "" || score == null)
                {
                    p1score = 0;
                    p2score = 0;
                }
                else
                {
                    if (score.Contains(','))
                    {
                        string[] scores = score.Split(',');

                        for (int j = 0; j < scores.Length; j++)
                        {
                            string[] scores1 = scores[j].Split('-');
                            int temp1;
                            int temp2;

                            int.TryParse(scores1[0], out temp1);
                            int.TryParse(scores1[1], out temp2);

                            if (temp1 > temp2)
                                p1score++;
                            else
                                p2score++;
                        }
                    }
                    else
                    {
                        string[] scores1 = score.Split('-');
                        int.TryParse(scores1[0], out p1score);
                        int.TryParse(scores1[1], out p2score);
                    }
                }

                MatchInfo _info = new MatchInfo();
                _info.id = jsonMatches[i]["match"]["id"];
                _info.state = jsonMatches[i]["match"]["state"];

                string state = jsonMatches[i]["match"]["state"];
                switch (state)
                {
                    case "open":
                        _info.stateId = 0;
                        break;
                    case "pending":
                        _info.stateId = 1;
                        break;
                    case "complete":
                        _info.stateId = 2;
                        break;
                }

                _info.ident = jsonMatches[i]["match"]["identifier"];

                if (jsonTournament["subdomain"] == null)
                    _info.subdomain = "";
                else
                    _info.subdomain = jsonTournament["subdomain"];

                _info.url = jsonTournament["url"];

                if (jsonMatches[i]["match"]["player1_id"] != null)
                {
                    _info.p1 = gVar.dictIdName[jsonMatches[i]["match"]["player1_id"]];
                    _info.p1id = jsonMatches[i]["match"]["player1_id"];
                }
                else
                {
                    _info.p1 = "";
                    _info.p1id = -1;
                }

                if (jsonMatches[i]["match"]["player2_id"] != null)
                {
                    _info.p2 = gVar.dictIdName[jsonMatches[i]["match"]["player2_id"]];
                    _info.p2id = jsonMatches[i]["match"]["player2_id"];
                }
                else
                {
                    _info.p2 = "";
                    _info.p2id = -1;
                }


                _info.round = jsonMatches[i]["match"]["round"];
                _info.p1s = p1score;
                _info.p2s = p2score;

                if (jsonMatches[i]["match"]["player1_prereq_match_id"] != null)
                    _info.p1prematchid = jsonMatches[i]["match"]["player1_prereq_match_id"];
                else
                    _info.p1prematchid = -1;


                _info.p1isprematchloser = jsonMatches[i]["match"]["player1_is_prereq_match_loser"];

                if (jsonMatches[i]["match"]["player2_prereq_match_id"] != null)
                    _info.p2prematchid = jsonMatches[i]["match"]["player2_prereq_match_id"];
                else
                    _info.p2prematchid = -1;

                _info.p2isprematchloser = jsonMatches[i]["match"]["player2_is_prereq_match_loser"];

                if (jsonMatches[i]["match"]["winner_id"] != null)
                    _info.winId = jsonMatches[i]["match"]["winner_id"];
                else
                    _info.winId = -1;

                if (jsonMatches[i]["match"]["loser_id"] != null)
                    _info.losId = jsonMatches[i]["match"]["loser_id"];
                else
                    _info.losId = -1;

                itemsMatches.Add(_info);

                gVar.dictMIdIdent.Add(jsonMatches[i]["match"]["id"], jsonMatches[i]["match"]["identifier"]);
            }
        }