예제 #1
0
        public void TestStateClone()
        {
			MatchState state = new MatchState(new PhysicsEngine(new GameWorld(null)));

			IEntity e = new IEntity(IDGenerator.GenerateID(), new Vec2(100f, -99f), 1f, 1f, 1f);
			state.AddEntity(e);

			Assert.True(state.ContainsEntity(e.ID), "entity1 added to match");

			IEntity e2 = new IEntity(IDGenerator.GenerateID(), new Vec2(42f, 24f), 1f, 1f, 1f);
			state.AddEntity(e2);

			Assert.True(state.ContainsEntity(e2.ID), "entity2 added to match");


			MatchState clone = state.Clone() as MatchState;

			Assert.True(clone.ContainsEntity(e.ID), "clone contains entity1");
			Assert.True(clone.ContainsEntity(e2.ID), "clone contains entity2");

			IEntity clonedE = clone.GetEntity(e.ID);
			TestClonedEntityValues(e, clonedE, true, "after clone (e1)");

			ChangeClonedEntity(clonedE, new Vec2(11f, 111f), new Vec2(22f, 222f), 1000f, 2000f, 333f);
			TestClonedEntityValues(e, clonedE, false, "after clone modif (e1)");

			IEntity clonedE2 = clone.GetEntity(e2.ID);
			TestClonedEntityValues(e2, clonedE2, true, "after clone (e2)");

			ChangeClonedEntity(clonedE2, new Vec2(87f, 78f), new Vec2(52f, 25f), 76f, 88f, 2121f);
			TestClonedEntityValues(e2, clonedE2, false, "after clone modif (e2)");
        }
예제 #2
0
 private static int ClassEnd( MatchState ms, int p )
 {
     var lua = ms.Lua;
     switch( ms.Pattern[p++] )
     {
         case L_ESC:
         {
             if( p == ms.PatternEnd )
                 lua.L_Error( "malformed pattern (ends with '%')" );
             return p+1;
         }
         case '[':
         {
             if( ms.Pattern[p] == '^' ) p++;
             do {
                 if( p == ms.PatternEnd )
                     lua.L_Error( "malformed pattern (missing ']')" );
                 if( ms.Pattern[p++] == L_ESC && p < ms.PatternEnd )
                     p++; // skip escapes (e.g. `%]')
             } while( ms.Pattern[p] != ']' );
             return p+1;
         }
         default: return p;
     }
 }
예제 #3
0
        private static int ClassEnd( ref MatchState ms, int pPos )
        {
            var pat = ms.Pat;

            switch( pat[pPos++] )
            {
            case (byte)'%':
                if( pPos == pat.Length )
                    throw new ArgumentException( "Malformed pattern (ends with %%)" );
                return pPos + 1;

            case (byte)'[':
                if( pat[pPos] == (byte)'^' )
                    pPos++;

                do
                {
                    if( pPos == pat.Length )
                        throw new ArgumentException( "Malformed pattern (missing ']')" );

                    if( pat[pPos++] == (byte)'%' && pPos < pat.Length )
                        pPos++;
                } while( pat[pPos] != (byte)']' );

                return pPos + 1;

            default:
                return pPos;
            }
        }
예제 #4
0
 private static int CheckCapture( MatchState ms, char l )
 {
     var lua = ms.Lua;
     int i = (int)(l - '1');
     if( i < 0 || i >= ms.Level || ms.Capture[i].Len == CAP_UNFINISHED )
         return lua.L_Error( "invalid capture index %d", i+1 );
     return i;
 }
예제 #5
0
파일: Match.cs 프로젝트: pksorensen/CycleR
 public void Start()
 {
     if (State == MatchState.Ready)
     {
         _broadcastHandler.BroadcastConfiguration(_mode.GetConfiguration());
         State = MatchState.Loading;
     }
 }
예제 #6
0
        public Match()
        {
            Id = Guid.NewGuid();
            _matchState = MatchState.NotStarted;

            // TODO: set up teams based on docuDB
            Team1 = new Team(0, "red team");
            Team2 = new Team(1, "blue team");
        }
예제 #7
0
    private void GG(int winning_player_num)
    {
        state = MatchState.PostMatch;
        //match_audio.PlayGameOver();
        TimeScaleManager.Instance.AddMultiplier("GG_slow", 0.3f);
        this.winner_player_num = winning_player_num;

        StartCoroutine(TranInGGPage());
    }
예제 #8
0
파일: LuaStrLib.cs 프로젝트: rokyado/UniLua
 private static int CaptureToClose( MatchState ms )
 {
     var lua = ms.Lua;
     int level=ms.Level;
     for( level--; level>=0; level-- )
     {
         if( ms.Capture[level].Len == CAP_UNFINISHED )
             return level;
     }
     return lua.L_Error( "invalid pattern capture" );
 }
예제 #9
0
        public GameMatch(string mapPath)
        {
			World = new GameWorld(mapPath);
			Physics = new PhysicsEngine(World);
			CurrentState = new MatchState(Physics);

			LeftStructures = new TeamStructures(Teams.Left,
				World.Map.Meta.LeftMeta.BaseTileIds,
				World.Map.Meta.LeftMeta.BaseTowerTileIds,
                World.Map.Meta.LeftMeta.TopTowerTileIds,
                World.Map.Meta.LeftMeta.BottomTowerTileIds);
			RightStructures = new TeamStructures(Teams.Right,
				World.Map.Meta.RightMeta.BaseTileIds,
                World.Map.Meta.RightMeta.BaseTowerTileIds,
                World.Map.Meta.RightMeta.TopTowerTileIds,
                World.Map.Meta.RightMeta.BottomTowerTileIds);

			Structures = new List<IStructure>();
			LeftStructures.Structures.ForEach(Structures.Add);
			RightStructures.Structures.ForEach(Structures.Add);
        }
예제 #10
0
        private static void add_value(MatchState ms, luaL_Buffer b, CharPtr s,
                                      CharPtr e)
        {
            lua_State L = ms.L;

            switch (lua_type(L, 3))
            {
            case LUA_TNUMBER:
            case LUA_TSTRING: {
                add_s(ms, b, s, e);
                return;
            }

            case LUA_TUSERDATA:
            case LUA_TFUNCTION: {
                int n;
                lua_pushvalue(L, 3);
                n = push_captures(ms, s, e);
                lua_call(L, n, 1);
                break;
            }

            case LUA_TTABLE: {
                push_onecapture(ms, 0, s, e);
                lua_gettable(L, 3);
                break;
            }
            }
            if (lua_toboolean(L, -1) == 0)        /* nil or false? */
            {
                lua_pop(L, 1);
                lua_pushlstring(L, s, (uint)(e - s));          /* keep original text */
            }
            else if (lua_isstring(L, -1) == 0)
            {
                luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
            }
            luaL_addvalue(b);        /* add result to accumulator */
        }
예제 #11
0
        /// <summary>
        /// Returns the node position as a number.
        /// </summary>
        /// <param name="state">
        /// Match results including the target User-Agent.
        /// </param>
        /// <returns>
        /// -1 if there is no numeric characters, otherwise the characters
        /// as an integer.
        /// </returns>
        internal int GetCurrentPositionAsNumeric(MatchState state)
        {
            // Find the left most numeric character from the current position.
            int i = Position;

            while (i >= 0 &&
                   state.TargetUserAgentArray[i] >= (byte)'0' &&
                   state.TargetUserAgentArray[i] <= (byte)'9')
            {
                i--;
            }

            // If numeric characters were found then return the number.
            if (i < Position)
            {
                return(GetNumber(
                           state.TargetUserAgentArray,
                           i + 1,
                           Position - i));
            }
            return(-1);
        }
예제 #12
0
    private IEnumerator EndMatch()
    {
        matchState = MatchState.Ending;

        if (tutorialScene)
        {
            _GameManager.instance.StartCoroutine(_GameManager.instance.LoadNewGame());

            Destroy(gameObject);
        }
        else
        {
            musicEvent.stop(FMOD.Studio.STOP_MODE.IMMEDIATE);
            RuntimeManager.PlayOneShot(endingSound);
            _GameManager.instance.playerControllers.Clear();
            if (matchByTime)
            {
                matchInfo.SetRankingsByKills();
            }

            cameraFollow.objectsToShow.Clear();
            cameraFollow.objectsToShow.Add(matchInfo.GetWinner().transform);
            cameraFollow.minZoom         = focusPlayerZoom;
            cameraFollow.positionDamping = 0f;
            matchInfo.GetWinner().gameObject.SetActive(true);
            matchInfo.GetWinner().rigidbody.velocity = Vector3.zero;
            matchInfo.GetWinner().rigidbody.isKinematic = true;

            yield return(new WaitForSeconds(timeToChangeScene));

            _GameManager.instance.SceneTransition.Play();

            yield return(new WaitForSeconds(_GameManager.instance.SceneTransition.clip.length));

            MasterBus.stopAllEvents(FMOD.Studio.STOP_MODE.ALLOWFADEOUT);

            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }
    }
예제 #13
0
        private static void add_value(MatchState ms, LuaLBuffer b, CharPtr s,
                                      CharPtr e)
        {
            LuaState L = ms.L;

            switch (LuaType(L, 3))
            {
            case LUA_TNUMBER:
            case LUA_TSTRING: {
                add_s(ms, b, s, e);
                return;
            }

            case LUA_TUSERDATA:
            case LUA_TFUNCTION: {
                int n;
                LuaPushValue(L, 3);
                n = push_captures(ms, s, e);
                LuaCall(L, n, 1);
                break;
            }

            case LUA_TTABLE: {
                push_onecapture(ms, 0, s, e);
                LuaGetTable(L, 3);
                break;
            }
            }
            if (LuaToBoolean(L, -1) == 0)        /* nil or false? */
            {
                LuaPop(L, 1);
                LuaPushLString(L, s, (uint)(e - s));          /* keep original text */
            }
            else if (LuaIsString(L, -1) == 0)
            {
                LuaLError(L, "invalid replacement value (a %s)", LuaLTypeName(L, -1));
            }
            LuaLAddValue(b);        /* add result to accumulator */
        }
예제 #14
0
    public void DecideEvent(MatchState matchState)
    {
        this.matchState = matchState;
        int team1Dead = matchState.Team1CurrentlyDead();
        int team2Dead = matchState.Team2CurrentlyDead();

        if (Mathf.Abs(team1Dead - team2Dead) >= 3)
        {
            if (matchState.timeToRushan < 0 && matchState.matchMinutes >= 15)
            {
                // RuSHAAAN
                if (team1Dead > team2Dead)
                {
                    // enemy rushan
                    eventType = MatchEventType.ENEMY_RUSHAN;
                    Dialog dialog = getEnemyRushanDialog();
                    DialogManagerScript.Instance.ShowDialog(dialog, dialogResolved);
                }
                else
                {
                    // our rushan
                    eventType = MatchEventType.OWN_RUSHAN;
                    Dialog dialog = getOwnRushanDialog();
                    DialogManagerScript.Instance.ShowDialog(dialog, dialogResolved);
                }
            }
        }
        else if (matchState.team1Wards <= 0)
        {
            // wardeeeei
            eventType = MatchEventType.WARDS;
            Dialog dialog = getWardsDialog();
            DialogManagerScript.Instance.ShowDialog(dialog, dialogResolved);
        }
        else if (Random.Range(0, 100) < 5)
        {
            // what to buy
        }
    }
예제 #15
0
    static int get_m_match(IntPtr L)
    {
        object     o   = LuaScriptMgr.GetLuaObject(L, 1);
        MatchState obj = (MatchState)o;

        if (obj == null)
        {
            LuaTypes types = LuaDLL.lua_type(L, 1);

            if (types == LuaTypes.LUA_TTABLE)
            {
                LuaDLL.luaL_error(L, "unknown member name m_match");
            }
            else
            {
                LuaDLL.luaL_error(L, "attempt to index m_match on a nil value");
            }
        }

        LuaScriptMgr.PushObject(L, obj.m_match);
        return(1);
    }
예제 #16
0
    public void StartMatch(int type)
    {
        if (!PhotonNetwork.isMasterClient)
        {
            photonView.RPC("StartMatch", PhotonTargets.MasterClient, (int)((AvatarType)type).OtherType());
        }
        else if (State == MatchState.CHOOSING_ROLES)
        {
            AvatarType myType = (AvatarType)type;
            foreach (var playerID in avatarList.Keys)
            {
                AvatarType avatarType  = playerID == PhotonNetwork.player.ID ? myType : myType.OtherType();
                int        spawnNumber = avatarType == AvatarType.DODGER ? 0 : 1;

                Avatar avatar = avatarList[playerID];

                avatar.OutOfHealth += OutOfHealth;
                avatar.CreateAvatar(avatarType, spawns.GetChild(spawnNumber).position);
            }
            State = MatchState.PLAYING;
        }
    }
예제 #17
0
        private static int singlematch(MatchState ms, CharPtr s, CharPtr p,
                                       CharPtr ep)
        {
            if (s >= ms.src_end)
            {
                return(0);
            }
            else
            {
                int c = uchar(s[0]);
                switch (p[0])
                {
                case '.': return(1);           /* matches any char */

                case L_ESC: return(match_class(c, (byte)(p[1])));

                case '[': return(matchbracketclass(c, p, ep - 1));

                default: return(((byte)(p[0]) == c) ? 1 : 0);
                }
            }
        }
예제 #18
0
 public void OnMatchStateChange(MatchState oldState, MatchState newState)
 {
     if (oldState != null && oldState.m_eState == MatchState.State.eFoul)
     {
         m_needSwitchRole = false;
         Reset();
     }
     else if (newState.m_eState == MatchState.State.ePlayerCloseUp)
     {
         if (m_uiMatch != null)
         {
             m_uiMatch.ShowCounter(false, false);
         }
     }
     else if (newState.m_eState == MatchState.State.eFreeThrowStart)
     {
         if (m_uiMatch != null)
         {
             m_uiMatch.ShowCounter(false, false);
         }
     }
 }
예제 #19
0
        public MatchState JoinGame(GameType matchType, Guid playerId)
        {
            var gameList = _onlineMatches
                           .FindAll(x => x.gameType == matchType)
                           .FindAll(x => x.operationState == GameOperationState.WaitingForPlayers);
            MatchState matchState = null;

            if (gameList.Count == 0)
            {
                matchState = MatchFactory.CreateNewMatch(matchType, playerId);
                _onlineMatches.Add(matchState);
            }
            else
            {
                matchState = gameList.First();
                matchState.players.Add(playerId);
                matchState.inGameState.secondPlayer = playerId;
                matchState.operationState           = GameOperationState.InProgress;
            }

            return(matchState);
        }
예제 #20
0
        public ReadOnlyCollection <ChallongeMatch> GetMatches(string tournamentId, MatchState state = MatchState.All, string participantId = null)
        {
            RestRequest request;

            if (participantId == null)
            {
                request = new RestRequest($"tournaments/{tournamentId}/matches.json?state={state.ToRequestString()}", Method.GET);
            }
            else
            {
                request = new RestRequest($"tournaments/{tournamentId}/matches.json?state={state.ToRequestString()}&participant_id={participantId}", Method.GET);
            }

            var result = m_client.Execute(request);

            if (result.ResponseStatus != ResponseStatus.Completed)
            {
                throw new Exception("Rest request failed. Try again.");
            }

            return(JsonConvert.DeserializeObject <List <MatchWrapper> >(result.Content).Select(m => m.Match).ToReadOnlyCollection());
        }
예제 #21
0
    // Update is called once per frame
    void Update()
    {
        var        roomProperties = PhotonNetwork.room.CustomProperties;
        MatchState matchState     = MatchState.Wait;

        if (roomProperties.ContainsKey(PhotonPropId.MatchState))
        {
            matchState = (MatchState)roomProperties[PhotonPropId.MatchState];
        }

        //cycling through some states
        switch (matchState)
        {
        case MatchState.Start:
            StartingState();
            break;

        case MatchState.Play:
            PlayingState();
            break;
        }
    }
예제 #22
0
    public void SetNewGame()
    {
        matchState = MatchState.Starting;

        for (int i = 0; i < players.Count; i++)
        {
            SpawnPlayer(players[i].gameObject, i);
            players[i].enabled = false;
            matchInfo.SetPlayer(players[i]);

            cameraFollow.objectsToShow.Add(players[i].transform);
        }

        if (testingScene)
        {
            StartGame();
        }
        else
        {
            StartCoroutine(StartCountdown(tutorialScene ? 0 : timeBeforeMatch));
        }
    }
예제 #23
0
    IEnumerator LaunchRoundPhase()
    {
        state     = MatchState.ROUND_PHASE;
        phaseTime = 0f;

        //force players switch view to side & reset turnDone value
        foreach (GardenPlayer player in players)
        {
            player.turnDone = false;
            player.view     = PlayerView.SIDE;
        }

        //initial delay
        yield return(new WaitForSeconds(1f));

        phaseTime = ROUND_PHASE_TIME;

        //wait for phase time expires or players turn done - 30s
        while (phaseTime > 0f && !GetPlayersReady())
        {
            //update time
            phaseTime -= Time.unscaledDeltaTime;

            foreach (GardenPlayer player in players)
            {
                player.RpcUpdatePhaseTime(phaseTime / INITIAL_PHASE_TIME);
            }

            yield return(null);
        }

        //delay
        phaseTime = 0f;
        yield return(new WaitForSeconds(1f));

        //end phase
        state        = MatchState.ROUND_RESULTS_PHASE;
        phaseProcess = null;
    }
예제 #24
0
파일: Match.cs 프로젝트: dtryon/tennis
        private void AdvanceState(Side side)
        {
            if (side == Side.One)
            {
                sideOneScore++;
            }

            if (side == Side.Two)
            {
                sideTwoScore++;
            }

            if (sideOneScore >= 2)
            {
                state = MatchState.MatchWonBySideOne;
            }

            if (sideTwoScore >= 2)
            {
                state = MatchState.MatchWonBySideTwo;
            }
        }
예제 #25
0
        internal static void HandleDisconnectFromMatch(MatchState match, string accountId)
        {
            if (match.InProgress && (match.OpposingPlayerInMatch(accountId) || match.AwaitingPlayerTimeout()))
            {
                if (match.IsParticipantId(accountId))
                {
                    match.BeginDepartureTimer(accountId);
                    InterEventDispatcher.InvokeDCFromMatchInProgressEvent
                        (new DCFromMatchInProgressEventArgs(match, match.GetPlayerStateById(accountId)));
                }

                else
                {
                    RemoveUserFromMatch(match, accountId);
                }
            }

            else
            {
                RemoveUserFromMatch(match, accountId);
            }
        }
예제 #26
0
 void Update()
 {
     if (isServer)
     {
         var players = FindObjectsOfType <Player>();
         if (players.Length == 0)
         {
             return;
         }
         if (State == MatchState.NotStarted)
         {
             if (players.All(p => p.State == PlayerState.Ready))
             {
                 State = MatchState.Starting;
             }
         }
         else if (State == MatchState.Starting)
         {
             if (players.All(p => p.State == PlayerState.Ready))
             {
                 CurrentStartTimer -= Time.deltaTime;
                 if (CurrentStartTimer < 0f)
                 {
                     State = MatchState.Started;
                     foreach (var player in players)
                     {
                         player.State = PlayerState.InGame;
                     }
                     SpawnPlayerCharacters();
                 }
             }
             else
             {
                 State             = MatchState.NotStarted;
                 CurrentStartTimer = TimerWhenReady;
             }
         }
     }
 }
예제 #27
0
        private static int ClassEnd(ref MatchState ms, int pPos)
        {
            var pat = ms.Pat;

            switch (pat[pPos++])
            {
            case (byte)'%':
                if (pPos == pat.Length)
                {
                    throw new ArgumentException("Malformed pattern (ends with %%)");
                }
                return(pPos + 1);

            case (byte)'[':
                if (pat[pPos] == (byte)'^')
                {
                    pPos++;
                }

                do
                {
                    if (pPos == pat.Length)
                    {
                        throw new ArgumentException("Malformed pattern (missing ']')");
                    }

                    if (pat[pPos++] == (byte)'%' && pPos < pat.Length)
                    {
                        pPos++;
                    }
                } while(pat[pPos] != (byte)']');

                return(pPos + 1);

            default:
                return(pPos);
            }
        }
예제 #28
0
    /*
     * private int countTotalHeroHealth(List<Hero> heroes)
     * {
     * int health = 0;
     * foreach (Hero hero in heroes)
     * {
     *  health += hero.currenthp;
     * }
     * return health;
     * }
     *
     * private int countTotalHeroDamage(List<Hero> heroes)
     * {
     * int damage = 0;
     * foreach (Hero hero in heroes)
     * {
     *  damage += hero.damage;
     * }
     * return damage;
     * }
     *
     * private int countTotalHeroHealing(List<Hero> heroes)
     * {
     * int healing = 0;
     * foreach (Hero hero in heroes)
     * {
     *  healing += hero.healing;
     * }
     * return healing;
     * }*/

    private void animateFight(MatchState matchState)
    {
        FightEvent join = new FightEvent();

        join.eventType = FightEventType.JOIN_FIGHT;
        FightEventTarget target;

        FightEvent leave = new FightEvent();

        leave.eventType = FightEventType.LEAVE_FIGHT;

        foreach (Hero hero in matchState.fightAllHeroes)
        {
            target            = new FightEventTarget();
            target.targetType = FightEventTargetType.HERO;
            target.id         = hero.id;
            join.targets.Add(target);
            leave.targets.Add(target);
        }

        FightEvent die = new FightEvent();

        die.eventType = FightEventType.DEATH;

        foreach (Hero hero in matchState.fightDeadHeroes)
        {
            target            = new FightEventTarget();
            target.targetType = FightEventTargetType.HERO;
            target.id         = hero.id;
            die.targets.Add(target);
        }

        fightEvents.Add(join);
        fightEvents.Add(die);
        fightEvents.Add(leave);

        FightAnimatorScript.Instance.PlayFight(fightEvents);
    }
예제 #29
0
        private async Task <RollListDto <MatchStatus> > GetRollListByState(MatchState matchState, Guid?oldestId, int count)
        {
            var currentUserName = identityService.GetCurrentUserName();
            Expression <Func <Match, bool> > filter = x => x.State == matchState && x.Users.Any(u => u.User.UserName == currentUserName);

            if (oldestId.HasValue)
            {
                var oldest = await context.Matches.CustomFindAsync(oldestId, "No such match.");

                if (oldest.LastMove != null)
                {
                    filter = filter.And(x => x.LastMove == null && x.CreateTime < oldest.LastMove || x.LastMove < oldest.LastMove);
                }
                else
                {
                    filter = filter.And(x => x.LastMove == null && x.CreateTime < oldest.CreateTime || x.LastMove < oldest.CreateTime);
                }
            }

            var matches = await context.Matches.AsNoTracking()
                          .Include(x => x.Board)
                          .Include(x => x.Users)
                          .ThenInclude(x => x.User)
                          .Include(x => x.Winner)
                          .Where(filter)
                          .OrderByDescending(x => x.LastMove)
                          .Take(count)
                          .ToListAsync();

            var last    = matches.LastOrDefault();
            var hasMore = matches.Count == count && last != null && await context.Matches.AnyAsync(x => x.LastMove < last.LastMove);

            return(new RollListDto <MatchStatus>
            {
                Data = matches.Select(x => matchConverter.ConvertFor(x, currentUserName)),
                HasMoreLeft = hasMore
            });
        }
예제 #30
0
        private static int ClassEnd(MatchState ms, int p)
        {
            var lua = ms.Lua;

            switch (ms.Pattern[p++])
            {
            case L_ESC:
            {
                if (p == ms.PatternEnd)
                {
                    lua.L_Error("malformed pattern (ends with '%')");
                }
                return(p + 1);
            }

            case '[':
            {
                if (ms.Pattern[p] == '^')
                {
                    p++;
                }
                do
                {
                    if (p == ms.PatternEnd)
                    {
                        lua.L_Error("malformed pattern (missing ']')");
                    }
                    if (ms.Pattern[p++] == L_ESC && p < ms.PatternEnd)
                    {
                        p++;                                 // skip escapes (e.g. `%]')
                    }
                } while(ms.Pattern[p] != ']');
                return(p + 1);
            }

            default: return(p);
            }
        }
예제 #31
0
        public void StartMatch()
        {
            this.State = MatchState.IN_PROGRESS;
            int matchTime = Blitz.Instance.Configuration.MatchTime;

            new Countdown(
                matchTime,
                "{0} seconds left.",
                new List <int> {
                matchTime - 10, matchTime / 2, 5, 4, 3, 2, 1
            },
                this.EndMatch
                );
            foreach (Team team in Blitz.Instance.Configuration.Teams)
            {
                foreach (PlayerData pd in team.Players)
                {
                    pd.GetRocketPlayer().Teleport(SpawnManager.Instance.GetSpawnpoint(pd), 0);
                    pd.GetRocketPlayer().Inventory.Clear();
                    Unit.GiveLoadout(pd);
                }
            }
        }
예제 #32
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Style      s     = new Style(typeof(TextBlock));
            MatchState state = (MatchState)value;

            switch (state)
            {
            case MatchState.WIN_WHITE:
                s.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.LightGray));
                return(s);

            case MatchState.WIN_BLACK:
                s.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.Black));
                return(s);

            case MatchState.DRAW:
                s.Setters.Add(new Setter(TextBlock.ForegroundProperty, Brushes.LightGreen));
                return(s);

            default:
                return(s);
            }
        }
    private void MatchStateChanged(MatchState matchState)
    {
        if (!showSelfScore && !showEnemyScore)
        {
            return;
        }

        switch (matchState)
        {
        case MatchState.Preparing:
        case MatchState.Goal:
            selfScoreView.SetActive(showSelfScore);
            enemyScoreView.SetActive(showEnemyScore);
            matchScoreView.SetActive(false);
            break;

        case MatchState.Match:
            selfScoreView.SetActive(false);
            enemyScoreView.SetActive(false);
            matchScoreView.SetActive(true);
            break;
        }
    }
예제 #34
0
        public void CalculateNextState_InvalidMovePositionIsNotEmpty_ThrowsException()
        {
            var playerOne    = Guid.NewGuid();
            var playerTwo    = Guid.NewGuid();
            var move         = MovePosition.MiddleCenter;
            var currentState = new MatchState
            {
                operationState = GameOperationState.InProgress,
                playerTurnId   = playerOne,
                inGameState    = new TicTacToeState
                {
                    firstPlayer = playerOne,
                    board       = new List <PlayerMark>
                    {
                        PlayerMark.Empty, PlayerMark.Empty, PlayerMark.Empty,
                        PlayerMark.Empty, PlayerMark.X, PlayerMark.Empty,
                        PlayerMark.Empty, PlayerMark.Empty, PlayerMark.Empty,
                    }
                },
            };

            Assert.Throws(typeof(InvalidPlayerMoveException), () => TicTacToeLogic.CalculateNextState(currentState, playerOne, move));
        }
예제 #35
0
    void EnterEndMinigame()
    {
        currMinigame.End();
        state = MatchState.EndMinigame;

        if (numPlayersAliveMatch <= 1 && settings.numPlayers > 1 || numPlayersAliveMatch == 0 && settings.numPlayers == 1)
        {
            EnterEndMatch();
        }

        RespawnDeadList();
        minigameIndex += 1;
        minigameIndex  = minigameIndex % minigames.Length;
        if (minigameIndex == 0)
        {
            level += 1;
            SetLevelText(level.ToString());
        }
        currMinigame    = minigames[minigameIndex].GetComponent <Minigame>();
        numPlayersAlive = numPlayersAliveMatch;

        timeEnteredState = Time.time;
    }
예제 #36
0
        public MatchObject(MatchResult result, ChallongeAPICaller caller)
        {
            this.result = result;
            this.caller = caller;
            switch (result.state)
            {
            case "open":
                matchState = MatchState.Open;
                break;

            case "pending":
                matchState = MatchState.Pending;
                break;

            case "completed":
                matchState = MatchState.Complete;
                break;

            default:
                throw new InvalidMatchState();
            }
            updateMatchQuery = new UpdateMatchQuery(result);
        }
예제 #37
0
        internal static void RemoveUserFromMatch(MatchState match, string accountId)
        {
            PlayerState   userRemoved;
            DepartureType departureType = DepartureType.Unknown;

            match.RemoveUserFromMatch(accountId, out departureType, out userRemoved);

            if (match.PlayerOne == null & match.PlayerTwo == null)
            {
                if (m_Matches.ContainsKey(match.MatchIdentity))
                {
                    m_Matches.Remove(match.MatchIdentity);
                    MatchEventDispatcher.InvokeMatchEndEvent
                        (new MatchEndEventArgs(match.MatchIdentity));
                }
            }

            else
            {
                MatchEventDispatcher.InvokeUserDepartedEvent
                    (new UserDepartedEventArgs(match, departureType, userRemoved));
            }
        }
예제 #38
0
        private static void PushOneCapture
            (MatchState ms
            , int i
            , int start
            , int end
            )
        {
            var lua = ms.Lua;

            if (i >= ms.Level)
            {
                if (i == 0)                  // ms.Level == 0, too
                {
                    lua.PushString(ms.Src.Substring(start, end - start));
                }
                else
                {
                    lua.L_Error("invalid capture index");
                }
            }
            else
            {
                int l = ms.Capture[i].Len;
                if (l == CAP_UNFINISHED)
                {
                    lua.L_Error("unfinished capture");
                }
                if (l == CAP_POSITION)
                {
                    lua.PushInteger(ms.Capture[i].Init - ms.SrcInit + 1);
                }
                else
                {
                    lua.PushString(ms.Src.Substring(ms.Capture[i].Init, l));
                }
            }
        }
        // Kicks all players who are BANNED (Lobby and otherwise)
        public static void KickBannedPlayers()
        {
            if (GetList(MPBanMode.Ban).Count < 1)
            {
                // no bans active
                return;
            }
            MatchState s       = NetworkMatch.GetMatchState();
            bool       inLobby = (s == MatchState.LOBBY || s == MatchState.LOBBY_LOAD_COUNTDOWN);

            if (inLobby)
            {
                // Kick Lobby Players
                foreach (KeyValuePair <int, PlayerLobbyData> p in NetworkMatch.m_players)
                {
                    if (p.Value != null)
                    {
                        MPBanEntry candidate = new MPBanEntry(p.Value);
                        if (IsBanned(candidate, MPBanMode.Ban))
                        {
                            KickPlayer(p.Value, true);
                        }
                    }
                }
            }
            else
            {
                foreach (var p in Overload.NetworkManager.m_Players)
                {
                    MPBanEntry candidate = new MPBanEntry(p);
                    if (IsBanned(candidate, MPBanMode.Ban))
                    {
                        KickPlayer(p, true);
                    }
                }
            }
        }
예제 #40
0
            void FastForwardServerState()
            {
                if (latestServerState == null || latestServerStateTimestamp < InputHistory.Oldest.Timestep)
                {
                    return;
                }
                CurrentState = latestServerState;
                var start = latestServerStateTimestamp != 0 ? latestServerStateTimestamp - 1 : 0;

                foreach (var timedInput in InputHistory.StartingWith(start))
                {
                    if (timedInput.Timestep >= InputHistory.Current.Timestep)
                    {
                        break;
                    }
                    var input = timedInput.Input;
                    if (latestServerInput != null)
                    {
                        input.MergeWith(latestServerInput.Value);
                    }
                    if (timedInput.Timestep < latestServerStateTimestamp || timedInput.Timestep == 0)
                    {
                        InputContext.Reset(input);
                    }
                    else
                    {
                        InputContext.Update(input);
                        InputContext.Predict();

                        var state = CurrentState;
                        Simulation.Simulate(ref state, InputContext);
                        CurrentState = state;
                    }
                }
                InputHistory.DropBefore(latestServerStateTimestamp);
                latestServerState = null;
            }
예제 #41
0
		private static void Add_Value (MatchState ms, StringBuilder b, int s, int e) {
		  ILuaState lua = ms.Lua;
		  switch (lua.Type(3)) {
			case LuaType.LUA_TNUMBER:
			case LuaType.LUA_TSTRING: {
			  Add_S(ms, b, s, e);
			  return;
			}
			case LuaType.LUA_TFUNCTION: {
			  int n;
			  lua.PushValue(3);
			  n = PushCaptures(lua, ms, s, e);
			  lua.Call(n, 1);
			  break;
			}
			case LuaType.LUA_TTABLE: {
			  PushOneCapture(ms, 0, s, e);
			  lua.GetTable(3);
			  break;
			}
		  }
		  if (lua.ToBoolean(-1)==false) {  /* nil or false? */
			lua.Pop(1);
			b.Append(ms.Src.Substring(s, (e - s)));  /* keep original text */
		  }
		  else if (!lua.IsString(-1))
			lua.L_Error("invalid replacement value (a %s)", lua.L_TypeName(-1));
	      else
			b.Append(lua.ToString(-1));
		}
예제 #42
0
		private static void Add_S (MatchState ms, StringBuilder b, int s, int e) {
		  string news = ms.Lua.ToString(3);
		  for (int i = 0; i < news.Length; i++) {
			if (news[i] != L_ESC)
			  b.Append(news[i]);
			else {
			  i++;  /* skip ESC */
			  if (!Char.IsDigit((news[i])))
			      b.Append(news[i]);
			  else if (news[i] == '0')
				  b.Append(ms.Src.Substring(s, (e - s))); 
			  else {
				PushOneCapture(ms, news[i] - '1', s, e);
				b.Append(ms.Lua.ToString(-1));  /* add capture to accumulated result */
			  }
			}
		  }
		}
예제 #43
0
		private static int GmatchAux( ILuaState lua )
		{
			MatchState ms = new MatchState();
			string src = lua.ToString( lua.UpvalueIndex(1) );
			string pattern = lua.ToString( lua.UpvalueIndex(2) );
			ms.Lua = lua;
			ms.Src = src;
			ms.SrcInit = 0;
			ms.SrcEnd = src.Length;
			ms.Pattern = pattern;
			ms.PatternEnd = pattern.Length;
			for( int s = lua.ToInteger( lua.UpvalueIndex(3) )
			   ; s <= ms.SrcEnd
			   ; s++ )
			{
				ms.Level = 0;
				int e = Match( ms, s, 0 );
				if( e != -1 )
				{
					int newStart = (e == 0) ? e+1: e;
					lua.PushInteger( newStart );
					lua.Replace( lua.UpvalueIndex(3) );
					return PushCaptures(lua, ms, s, e);
				}
			}
			return 0; // not found
		}
예제 #44
0
		private static int StrFindAux( ILuaState lua, bool find )
		{
			string s = lua.L_CheckString( 1 );
			string p = lua.L_CheckString( 2 );
			int init = PosRelative( lua.L_OptInt(3, 1), s.Length );
			if( init < 1 ) init = 1;
			else if( init > s.Length + 1 ) // start after string's end?
			{
				lua.PushNil(); // cannot find anything
				return 1;
			}
			// explicit request or no special characters?
			if( find && (lua.ToBoolean(4) || NoSpecials(p)) )
			{
				// do a plain search
				int pos = s.IndexOf( p, init-1 );
				if( pos >= 0 )
				{
					lua.PushInteger( pos+1 );
					lua.PushInteger( pos+p.Length );
					return 2;
				}
			}
			else
			{
				int s1 = init-1;
				int ppos = 0;
				bool anchor = p[ppos] == '^';
				if( anchor )
					ppos++; // skip anchor character

				MatchState ms = new MatchState();
				ms.Lua = lua;
				ms.Src = s;
				ms.SrcInit = s1;
				ms.SrcEnd = s.Length;
				ms.Pattern = p;
				ms.PatternEnd = p.Length;

				do
				{
					ms.Level = 0;
					int res = Match( ms, s1, ppos );
					if( res != -1 )
					{
						if(find)
						{
							lua.PushInteger( s1+1 ); // start
							lua.PushInteger( res );  // end
							return PushCaptures(lua, ms, -1, 0) + 2;
						}
						else return PushCaptures(lua, ms, s1, res);
					}
				} while( s1++ < ms.SrcEnd && !anchor );
			}
			lua.PushNil(); // not found
			return 1;
		}
예제 #45
0
		private static bool SingleMatch( MatchState ms, char c, int p, int ep )
		{
			switch( ms.Pattern[p] )
			{
				case '.': 	return true; // matches any char
				case L_ESC: return MatchClass( c, ms.Pattern[p+1] );
				case '[': 	return MatchBreaketClass( ms, c, p, ep-1 );
				default: 	return ms.Pattern[p] == c;
			}
		}
예제 #46
0
        private static CharPtr start_capture(MatchState ms, CharPtr s,
											CharPtr p, int what)
        {
            CharPtr res;
              int level = ms.level;
              if (level >= LUA_MAXCAPTURES) luaL_error(ms.L, "too many captures");
              ms.capture[level].init = s;
              ms.capture[level].len = what;
              ms.level = level+1;
              if ((res=match(ms, s, p)) == null)  /* match failed? */
            ms.level--;  /* undo capture */
              return res;
        }
예제 #47
0
 private static int str_gsub(lua_State L)
 {
     uint srcl;
       CharPtr src = luaL_checklstring(L, 1, out srcl);
       CharPtr p = luaL_checkstring(L, 2);
       int  tr = lua_type(L, 3);
       int max_s = luaL_optint(L, 4, (int)(srcl+1));
       int anchor = 0;
       if (p[0] == '^')
       {
       p = p.next();
       anchor = 1;
       }
       int n = 0;
       MatchState ms = new MatchState();
       luaL_Buffer b = new luaL_Buffer();
       luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
                       tr == LUA_TFUNCTION || tr == LUA_TTABLE ||
                       tr == LUA_TUSERDATA, 3,
                       "string/function/table expected");
       luaL_buffinit(L, b);
       ms.L = L;
       ms.src_init = src;
       ms.src_end = src+srcl;
       while (n < max_s) {
     CharPtr e;
     ms.level = 0;
     e = match(ms, src, p);
     if (e != null) {
       n++;
       add_value(ms, b, src, e);
     }
     if ((e!=null) && e>src) /* non empty match? */
       src = e;  /* skip it */
     else if (src < ms.src_end)
     {
         char c = src[0];
         src = src.next();
         luaL_addchar(b, c);
     }
     else break;
     if (anchor != 0) break;
       }
       luaL_addlstring(b, src, (uint)(ms.src_end-src));
       luaL_pushresult(b);
       lua_pushinteger(L, n);  /* number of substitutions */
       return 2;
 }
예제 #48
0
		private static int MatchCapture( MatchState ms, int s, char l )
		{
			int i = CheckCapture( ms, l );
			int len = ms.Capture[i].Len;
			if( ms.SrcEnd - s >= len &&
				string.Compare(ms.Src, ms.Capture[i].Init, ms.Src, s, len) == 0 )
				return s + len;
			else
				return -1;
		}
예제 #49
0
		private static int EndCapture( MatchState ms, int s, int p )
		{
			int l = CaptureToClose( ms );
			ms.Capture[l].Len = s - ms.Capture[l].Init; // close capture
			int res = Match( ms, s, p );
			if( res == -1 ) // match failed?
				ms.Capture[l].Len = CAP_UNFINISHED; // undo capture
			return res;
		}
예제 #50
0
		private static int MinExpand( MatchState ms, int s, int p, int ep )
		{
			for(;;)
			{
				int res = Match( ms, s, ep+1 );
				if( res >= 0 )
					return res;
				else if( s < ms.SrcEnd && SingleMatch( ms, ms.Src[s], p, ep ) )
					s++; // try with one more repetition
				else return -1;
			}
		}
예제 #51
0
		private static int MaxExpand( MatchState ms, int s, int p, int ep )
		{
			int i = 0; // counts maximum expand for item
			while( (s+i) < ms.SrcEnd && SingleMatch( ms, ms.Src[s+i], p, ep ) )
				i++;
			// keeps trying to match with the maximum repetitions
			while( i >= 0 )
			{
				int res = Match( ms, (s+i), (ep+1) );
				if( res >= 0 ) return res;
				i--; // else didn't match; reduce 1 repetition to try again
			}
			return -1;
		}
예제 #52
0
		private static int MatchBalance( MatchState ms, int s, int p )
		{
			var lua = ms.Lua;
			if( p >= ms.PatternEnd - 1 )
				lua.L_Error( "malformed pattern (missing arguments to '%b')" );
			if( ms.Src[s] != ms.Pattern[p] ) return -1;
			else
			{
				char b = ms.Pattern[p];
				char e = ms.Pattern[p+1];
				int count = 1;
				while( ++s < ms.SrcEnd )
				{
					if( ms.Src[s] == e )
					{
						if( --count == 0 ) return s+1;
					}
					else if( ms.Src[s] == b ) count++;
				}
			}
			return -1; //string ends out of balance
		}
예제 #53
0
		private static int Str_Gsub( ILuaState lua )
		{
			
			string src = lua.L_CheckString(1);
			int srcl = src.Length;
			string p = lua.L_CheckString(2);
			LuaType tr = lua.Type(3);
			int max_s = lua.L_OptInt(4, srcl + 1);
			int anchor = 0;
			if (p[0] == '^')
			{
                p = p.Substring(1);
                anchor = 1;
			}
			int n = 0;
			MatchState ms = new MatchState();
			StringBuilder b = new StringBuilder(srcl);
			lua.L_ArgCheck(tr == LuaType.LUA_TNUMBER || tr == LuaType.LUA_TSTRING ||
						   tr == LuaType.LUA_TFUNCTION || tr == LuaType.LUA_TTABLE, 3,
							  "string/function/table expected");
			ms.Lua = lua;
			ms.Src = src;
			ms.SrcInit = 0;
			ms.SrcEnd = srcl;
			ms.Pattern = p;
			ms.PatternEnd = p.Length;
			int s = 0;
			while (n < max_s) {
			   ms.Level = 0;
			   int e = Match(ms, s, 0);
			   if (e != -1) {
			       n++;
				   Add_Value(ms, b, s, e);
			   }
			   if ((e != -1) && e > s) /* non empty match? */
			      s = e;  /* skip it */
			   else if (s < ms.SrcEnd)
			   {
			       char c = src[s];
				   ++s;
			       b.Append(c);
			   }
			   else break;
			   if (anchor != 0) break;
		    }
			b.Append(src.Substring(s, ms.SrcEnd - s));
			lua.PushString(b.ToString());
		    lua.PushInteger(n);  /* number of substitutions */
		    return 2;
		}
예제 #54
0
		private static int Match( MatchState ms, int s, int p )
		{
			var lua = ms.Lua;
			init: // using goto's to optimize tail recursion
			if( p == ms.PatternEnd )
				return s;
			switch( ms.Pattern[p] )
			{
				case '(': // start capture
				{
					if( ms.Pattern[p+1] == ')' ) // position capture?
						return StartCapture( ms, s, p+2, CAP_POSITION );
					else
						return StartCapture( ms, s, p+1, CAP_UNFINISHED );
				}
				case ')': // end capture
				{
					return EndCapture( ms, s, p+1 );
				}
				case '$':
				{
					if( p+1 == ms.PatternEnd ) // is the `$' the last char in pattern?
						return (s == ms.SrcEnd) ? s : -1; // check end of string
					else goto dflt;
				}
				case L_ESC: // escaped sequences not in the format class[*+?-]?
				{
					switch( ms.Pattern[p+1] )
					{
						case 'b': // balanced string?
						{
							s = MatchBalance( ms, s, p+2 );
							if( s == -1 ) return -1;
							p += 4; goto init; // else return match(ms, s, p+4);
						}
						case 'f': // frontier?
						{
							p += 2;
							if( ms.Pattern[p] != '[' )
								lua.L_Error( "missing '[' after '%f' in pattern" );
							int ep = ClassEnd( ms, p ); //points to what is next
							char previous = (s == ms.SrcInit) ? '\0' : ms.Src[s-1];
							if( MatchBreaketClass(ms, previous, p, ep-1) ||
								!MatchBreaketClass(ms, ms.Src[s], p, ep-1) ) return -1;
							p = ep; goto init; // else return match( ms, s, ep );
						}
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9': // capture results (%0-%9)?
						{
							s = MatchCapture( ms, s, ms.Pattern[p+1] );
							if( s == -1 ) return -1;
							p+=2; goto init; // else return match(ms, s, p+2);
						}
						default: goto dflt;
					}
				}
				default: dflt: // pattern class plus optional suffix
				{
					int ep = ClassEnd( ms, p );
					bool m = s < ms.SrcEnd && SingleMatch(ms, ms.Src[s], p, ep);
				    if(ep < ms.PatternEnd){
						switch(ms.Pattern[ep]) //fix gmatch bug patten is [^a]
						{
							case '?': // optional
							{
								if( m )
								{
									int res = Match(ms, s+1, ep+1);
									if( res != -1 )
										return res;
								}
								p=ep+1; goto init; // else return match(ms, s, ep+1);
							}
							case '*': // 0 or more repetitions
							{
								return MaxExpand(ms, s, p, ep);
							}
							case '+': // 1 or more repetitions
							{
								return (m ? MaxExpand(ms, s+1, p, ep) : -1);
							}
							case '-': // 0 or more repetitions (minimum)
							{
								return MinExpand(ms, s, p, ep);
							}
						}
				    }
				    if(!m) return -1;
					s++; p=ep; goto init; // else return match(ms, s+1, ep);
				}
			}
		}
예제 #55
0
파일: Node.cs 프로젝트: VirusFree/AIMLBot
        /// <summary>
        /// Navigates this node (and recusively into child nodes) for a match to the path passed as an argument
        /// whilst processing the referenced request
        /// </summary>
        /// <param name="path">The normalized path derived from the user's input</param>
        /// <param name="query">The query that this search is for</param>
        /// <param name="request">An encapsulation of the request from the user</param>
        /// <param name="matchstate">The part of the input path the node represents</param>
        /// <param name="wildcard">The contents of the user input absorbed by the AIML wildcards "_" and "*"</param>
        /// <returns>The template to process to generate the output</returns>
        public string evaluate(string path, SubQuery query, Request request, MatchState matchstate, StringBuilder wildcard)
        {
            // check for timeout
            if (request.StartedOn.AddMilliseconds(request.bot.TimeOut) < DateTime.Now)
            {
                request.bot.writeToLog("WARNING! Request timeout. User: "******" raw input: \"" + request.rawInput + "\"");
                request.hasTimedOut = true;
                return string.Empty;
            }

            // so we still have time!
            path = path.Trim();

            // check if this is the end of a branch in the GraphMaster 
            // return the cCategory for this node
            if (this.children.Count==0)
            {
                if (path.Length > 0)
                {
                    // if we get here it means that there is a wildcard in the user input part of the
                    // path.
                    this.storeWildCard(path, wildcard);
                }
                return this.template;
            }

            // if we've matched all the words in the input sentence and this is the end
            // of the line then return the cCategory for this node
            if (path.Length == 0)
            {
                return this.template;
            }

            // otherwise split the input into it's component words
            string[] splitPath = path.Split(" \r\n\t".ToCharArray());

            // get the first word of the sentence
            string firstWord = Normalize.MakeCaseInsensitive.TransformInput(splitPath[0]);

            // and concatenate the rest of the input into a new path for child nodes
            string newPath = path.Substring(firstWord.Length, path.Length - firstWord.Length);

            // first option is to see if this node has a child denoted by the "_" 
            // wildcard. "_" comes first in precedence in the AIML alphabet
            if (this.children.ContainsKey("_"))
            {
                Node childNode = (Node)this.children["_"];

                // add the next word to the wildcard match 
                StringBuilder newWildcard = new StringBuilder();
                this.storeWildCard(splitPath[0],newWildcard);
                
                // move down into the identified branch of the GraphMaster structure
                string result = childNode.evaluate(newPath, query, request, matchstate, newWildcard);

                // and if we get a result from the branch process the wildcard matches and return 
                // the result
                if (result.Length>0)
                {
                    if (newWildcard.Length > 0)
                    {
                        // capture and push the star content appropriate to the current matchstate
                        switch (matchstate)
                        {
                            case MatchState.UserInput:
                                query.InputStar.Add(newWildcard.ToString());
                                // added due to this match being the end of the line
                                newWildcard.Remove(0, newWildcard.Length);
                                break;
                            case MatchState.That:
                                query.ThatStar.Add(newWildcard.ToString());
                                break;
                            case MatchState.Topic:
                                query.TopicStar.Add(newWildcard.ToString());
                                break;
                        }
                    }
                    return result;
                }
            }

            // second option - the nodemapper may have contained a "_" child, but led to no match
            // or it didn't contain a "_" child at all. So get the child nodemapper from this 
            // nodemapper that matches the first word of the input sentence.
            if (this.children.ContainsKey(firstWord))
            {
                // process the matchstate - this might not make sense but the matchstate is working
                // with a "backwards" path: "topic <topic> that <that> user input"
                // the "classic" path looks like this: "user input <that> that <topic> topic"
                // but having it backwards is more efficient for searching purposes
                MatchState newMatchstate = matchstate;
                if (firstWord == "<THAT>")
                {
                    newMatchstate = MatchState.That;
                }
                else if (firstWord == "<TOPIC>")
                {
                    newMatchstate = MatchState.Topic;
                }

                Node childNode = (Node)this.children[firstWord];
                // move down into the identified branch of the GraphMaster structure using the new
                // matchstate
                StringBuilder newWildcard = new StringBuilder();
                string result = childNode.evaluate(newPath, query, request, newMatchstate,newWildcard);
                // and if we get a result from the child return it
                if (result.Length > 0)
                {
                    if (newWildcard.Length > 0)
                    {
                        // capture and push the star content appropriate to the matchstate if it exists
                        // and then clear it for subsequent wildcards
                        switch (matchstate)
                        {
                            case MatchState.UserInput:
                                query.InputStar.Add(newWildcard.ToString());
                                newWildcard.Remove(0, newWildcard.Length);
                                break;
                            case MatchState.That:
                                query.ThatStar.Add(newWildcard.ToString());
                                newWildcard.Remove(0, newWildcard.Length);
                                break;
                            case MatchState.Topic:
                                query.TopicStar.Add(newWildcard.ToString());
                                newWildcard.Remove(0, newWildcard.Length);
                                break;
                        }
                    }
                    return result;
                }
            }

            // third option - the input part of the path might have been matched so far but hasn't
            // returned a match, so check to see it contains the "*" wildcard. "*" comes last in
            // precedence in the AIML alphabet.
            if (this.children.ContainsKey("*"))
            {
                // o.k. look for the path in the child node denoted by "*"
                Node childNode = (Node)this.children["*"];

                // add the next word to the wildcard match 
                StringBuilder newWildcard = new StringBuilder();
                this.storeWildCard(splitPath[0], newWildcard);

                string result = childNode.evaluate(newPath, query, request, matchstate, newWildcard);
                // and if we get a result from the branch process and return it
                if (result.Length > 0)
                {
                    if (newWildcard.Length > 0)
                    {
                        // capture and push the star content appropriate to the current matchstate
                        switch (matchstate)
                        {
                            case MatchState.UserInput:
                                query.InputStar.Add(newWildcard.ToString());
                                // added due to this match being the end of the line
                                newWildcard.Remove(0, newWildcard.Length);
                                break;
                            case MatchState.That:
                                query.ThatStar.Add(newWildcard.ToString());
                                break;
                            case MatchState.Topic:
                                query.TopicStar.Add(newWildcard.ToString());
                                break;
                        }
                    }
                    return result;
                }
            }

            // o.k. if the nodemapper has failed to match at all: the input contains neither 
            // a "_", the sFirstWord text, or "*" as a means of denoting a child node. However, 
            // if this node is itself representing a wildcard then the search continues to be
            // valid if we proceed with the tail.
            if ((this.word == "_") || (this.word == "*"))
            {
                this.storeWildCard(splitPath[0], wildcard);
                return this.evaluate(newPath, query, request, matchstate, wildcard);
            }

            // If we get here then we're at a dead end so return an empty string. Hopefully, if the
            // AIML files have been set up to include a "* <that> * <topic> *" catch-all this
            // state won't be reached. Remember to empty the surplus to requirements wildcard matches
            wildcard = new StringBuilder();
            return string.Empty;
        }
예제 #56
0
		private static void PushOneCapture
			( MatchState ms
			, int i
			, int start
			, int end
			)
		{
			var lua = ms.Lua;
			if( i >= ms.Level )
			{
				if( i == 0 ) // ms.Level == 0, too
					lua.PushString( ms.Src.Substring( start, end-start ) );
				else
					lua.L_Error( "invalid capture index" );
			}
			else
			{
				int l = ms.Capture[i].Len;
				if( l == CAP_UNFINISHED )
					lua.L_Error( "unfinished capture" );
				if( l == CAP_POSITION )
					lua.PushInteger( ms.Capture[i].Init - ms.SrcInit + 1 );
				else
					lua.PushString( ms.Src.Substring( ms.Capture[i].Init, l ) );
			}
		}
예제 #57
0
 private static int str_find_aux(lua_State L, int find)
 {
     uint l1, l2;
       CharPtr s = luaL_checklstring(L, 1, out l1);
       CharPtr p = luaL_checklstring(L, 2, out l2);
       ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
       if (init < 0) init = 0;
       else if ((uint)(init) > l1) init = (ptrdiff_t)l1;
       if ((find!=0) && ((lua_toboolean(L, 4)!=0) ||  /* explicit request? */
       strpbrk(p, SPECIALS) == null)) {  /* or no special characters? */
     /* do a plain search */
     CharPtr s2 = lmemfind(s+init, (uint)(l1-init), p, (uint)(l2));
     if (s2 != null) {
       lua_pushinteger(L, s2-s+1);
       lua_pushinteger(L, (int)(s2-s+l2));
       return 2;
     }
       }
       else {
     MatchState ms = new MatchState();
     int anchor = 0;
     if (p[0] == '^')
     {
         p = p.next();
         anchor = 1;
     }
     CharPtr s1=s+init;
     ms.L = L;
     ms.src_init = s;
     ms.src_end = s+l1;
     do {
       CharPtr res;
       ms.level = 0;
       if ((res=match(ms, s1, p)) != null) {
         if (find != 0) {
           lua_pushinteger(L, s1-s+1);  /* start */
           lua_pushinteger(L, res-s);   /* end */
           return push_captures(ms, null, null) + 2;
         }
         else
           return push_captures(ms, s1, res);
       }
     } while (((s1=s1.next()) <= ms.src_end) && (anchor==0));
       }
       lua_pushnil(L);  /* not found */
       return 1;
 }
예제 #58
0
		private static int PushCaptures(ILuaState lua, MatchState ms, int spos, int epos )
		{
			int nLevels = (ms.Level == 0 && spos >= 0) ? 1 : ms.Level;
			lua.L_CheckStack(nLevels, "too many captures");
			for( int i=0; i<nLevels; ++i )
				PushOneCapture( ms, i, spos, epos );
			return nLevels; // number of strings pushed
		}
예제 #59
0
		private static int StartCapture( MatchState ms, int s, int p, int what )
		{
			var lua = ms.Lua;
			int level = ms.Level;
			if( level >= LUA_MAXCAPTURES )
				lua.L_Error( "too many captures" );
			ms.Capture[level].Init = s;
			ms.Capture[level].Len = what;
			ms.Level = level + 1;
			int res = Match( ms, s, p );
			if( res == -1 ) // match failed?
				ms.Level--;
			return res;
		}
예제 #60
0
		private static bool MatchBreaketClass( MatchState ms, char c, int p, int ec )
		{
			bool sig = true;
			if( ms.Pattern[p+1] == '^' )
			{
				sig = false;
				p++; // skip the `^'
			}
			while( ++p < ec )
			{
				if( ms.Pattern[p] == L_ESC )
				{
					p++;
					if( MatchClass( c, ms.Pattern[p] ) )
						return sig;
				}
				else if( ms.Pattern[p+1] == '-' && (p+2 < ec) )
				{
					p += 2;
					if( ms.Pattern[p-2] <= c && c <= ms.Pattern[p] )
						return sig;
				}
				else if( ms.Pattern[p] == c ) return sig;
			}
			return !sig;
		}