コード例 #1
0
 public Filter(DateTime start, DateTime end, string eventType = "", Matches match=Matches.EQUAL)
 {
     Start = start;
     End = end;
     Count = -1;
     Offset = -1;
     EventType = eventType;
     Match = match;
 }
コード例 #2
0
 public Filter(int count, int offset = 0, string eventType = "", Matches match=Matches.EQUAL)
 {
     Count = count;
     Offset = offset;
     Start = DateTime.MinValue;
     End = DateTime.MinValue;
     EventType = eventType;
     Match = match;
 }
コード例 #3
0
 /// <summary>
 /// Adds a query to the current group
 /// </summary>
 /// <param name="query">The query to add</param>
 /// <param name="occur">The occur value for the query</param>
 /// <param name="key">A key to allow manipulation from the dictionary later on (a default key will be generated if none is specified</param>
 public virtual void Add(Query query, Matches occur, string key = null)
 {
     if (key == null)
     {
         key = "Query_" + Queries.Count;
     }
     SetOccurValue(this, ref occur);
     QueryReference queryReference = new QueryReference { Occur = occur, Query = query };
     Queries.Add(key, queryReference);
 }
コード例 #4
0
        public IActionResult GetMatchesList(string selectedMatchID, string matchesList)
        {
            FullMatchDetailsModelView fullMatchDetailsModelView = new FullMatchDetailsModelView();
            List <Matches>            allMatches = JsonConvert.DeserializeObject <List <Matches> >(matchesList);
            Matches  match = allMatches?.FirstOrDefault(x => x.MatchId == int.Parse(selectedMatchID));
            DateTime date  = match.Time.Value.Date;

            fullMatchDetailsModelView.MatchesListSelection = allMatches?.Where(x => x.Time.Value.Date == date && x.MatchId != match.MatchId && x.StatusId < 13)
                                                             .OrderBy(x => x.MatchTypeId).ThenBy(x => x.Time).ToList();
            return(PartialView("~/Views/PartialViews/MatchDetailsSelectionListView.cshtml", fullMatchDetailsModelView));
        }
コード例 #5
0
        private async Task <Queue <AdvancedMatchInfo> > freshMeat()
        {
            // Get new matches
            Matches matches = await TinderState.Instance.Api.getMatches();

            if (matches == null || matches.message != null)
            {
                return(new Queue <AdvancedMatchInfo>());
            }

            return(new Queue <AdvancedMatchInfo>(matches.results));
        }
コード例 #6
0
        public async Task SaveBet(BetScore bet)
        {
            var match = Matches.First(m => m.Id == bet.MatchId);

            if (match.BeginAt < DateTime.Now)
            {
                return;
            }

            await _awsJsInterop.GraphQlAsync <object>(bet.Id == null?Mutations.CREATE_BET : Mutations.UPDATE_BET, new
            {
                input = new
                {
                    id               = bet.Id,
                    owner            = _awsHelper.User.Username,
                    userName         = _awsHelper.UserName,
                    betCompetitionId = Competition.Id,
                    betMatchId       = bet.MatchId,
                    scores           = new object[]
                    {
                        new
                        {
                            isHome = true,
                            value  = bet.HomeValue
                        },
                        new
                        {
                            isHome = false,
                            value  = bet.AwayValue
                        }
                    }
                }
            });

            if (_createResult)
            {
                await _awsJsInterop.GraphQlAsync <ResultResponses>(Mutations.CREATE_RESULT, new
                {
                    input = new
                    {
                        owner               = _awsHelper.User.Username,
                        userName            = _awsHelper.UserName,
                        resultCompetitionId = Competition.Id,
                        value               = 0
                    }
                });

                _createResult = false;
            }

            bet.ValueChanged = false;
            bet.Saved        = true;
        }
コード例 #7
0
 private void ClearSearchResults(string obj)
 {
     SportName                  = null;
     TournamentName             = null;
     SelectedSport              = null;
     SelectedTournament         = null;
     Sports                     = new ObservableCollection <ComboBoxItem>();
     Tournaments                = new ObservableCollection <ComboBoxItem>();
     ChangeTracker.SearchString = "";
     IsFocused                  = false;
     Matches.Clear();
 }
コード例 #8
0
        /// <inheritdoc />
        public override int GetHashCode()
        {
            var hashCode = -905952502;

            hashCode = hashCode * -1521134295 + Matches.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Expected);

            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(Actual);

            hashCode = hashCode * -1521134295 + Reason.GetHashCode();
            return(hashCode);
        }
コード例 #9
0
 public IHttpActionResult GetAllMatches([FromUri] long accountId, [FromUri] string region)
 {
     if (Array.IndexOf(Globals.REGIONS, region) != -1)
     {
         var matches = new Matches().Get(accountId, region);
         return(Ok(matches));
     }
     else
     {
         return(BadRequest());
     }
 }
コード例 #10
0
 public static Query Field(this IQueryBuilderIndividual inputQueryBuilder, string fieldName, string value, Matches occur = Matches.NotSet, float? boost = null, string key = null, int slop = 1)
 {
     if (value.Contains("*"))
     {
         return inputQueryBuilder.WildCard(GetEncodedFieldName(fieldName), value.ToLower(), occur, boost, key);
     }
     if (value.Contains(" "))
     {
         PhraseQuery phraseQuery = inputQueryBuilder.Phrase(slop, boost, occur, key);
         string[] valueElems = value.Split(new[] {' '});
         foreach (var valueElem in valueElems)
         {
             phraseQuery.AddTerm(GetEncodedFieldName(fieldName), valueElem.ToLower());
         }
         return phraseQuery;
     }
     return inputQueryBuilder.Term(GetEncodedFieldName(fieldName), value.ToLower(), occur, boost, key);
 }
コード例 #11
0
		/// <summary>Runs it all.</summary>
		public void DoRun(IBot bot, IEnumerable<IInstruction> instructions)
		{
			if (bot == null) { throw new ArgumentNullException("bot"); }
			if (instructions == null) { throw new ArgumentNullException("instructions"); }

			var settings = new Settings();
			var matches = new Matches();

			foreach (var instruction in instructions)
			{
				if (settings.Apply(instruction))
				{
					bot.ApplySettings(settings);
				}
				else if (matches.Apply(instruction)) { }
				else if (instruction is WinsInstruction)
				{
					bot.Update((WinsInstruction)instruction);
				}
				else if (instruction is RequestMoveInstruction)
				{
					bot.Update(matches);
					try
					{
						var response = bot.GetResponse(((RequestMoveInstruction)instruction).Time);
						Writer.WriteLine(response.Action);
						if (!String.IsNullOrEmpty(response.Log))
						{
							Logger.WriteLine(response.Log);
						}
					}
					catch (Exception x)
					{
						Writer.WriteLine(GameAction.Check);
						Logger.WriteLine(x);
					}
				}
			}
		}
コード例 #12
0
 public virtual TermRangeQuery TermRange(string fieldName, string rangeStart, string rangeEnd, bool includeLower = true, bool includeUpper = true,
                                 Matches occur = Matches.NotSet, float? boost = null, string key = null, bool? caseSensitive = null)
 {
     if (caseSensitive.HasValue)
     {
         if (!caseSensitive.Value)
         {
             rangeStart = rangeStart.ToLowerInvariant();
             rangeEnd = rangeEnd.ToLowerInvariant();
         }
     }
     else if(!CaseSensitive)
     {
         rangeStart = rangeStart.ToLowerInvariant();
         rangeEnd = rangeEnd.ToLowerInvariant();
     }
     TermRangeQuery query = new TermRangeQuery(QueryParser.Escape(fieldName), rangeStart, rangeEnd, includeLower, includeUpper);
     SetBoostValue(query, boost);
     Add(query, occur, key);
     return query;
 }
コード例 #13
0
 protected virtual IQueryBuilder CreateNewChildGroup(Matches occur = Matches.NotSet, Matches childrenOccur = Matches.NotSet)
 {
     return new QueryBuilder(this) { Occur = occur, DefaultChildrenOccur = childrenOccur };
 }
コード例 #14
0
 /// <summary>
 /// Creates a simple group allowing the specification of whether it should occur, each item of which SHOULD occur by default
 /// </summary>
 /// <param name="occur">Whether the group must / should occur</param>
 /// <param name="queries">The lamdba expressions showing queries</param>
 public virtual IQueryBuilder Or(Matches occur = Matches.NotSet, params Action<IQueryBuilder>[] queries)
 {
     return Group(occur, Matches.Sometimes, queries).Parent;
 }
コード例 #15
0
        public bool Matches_IsValid(string firstName, string regexPattern)
        {
            //Create Validator
            var validator = new Matches<Contact>(regexPattern);
            RuleValidatorContext<Contact, string> context = BuildContextForLength(firstName);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
コード例 #16
0
 /// <summary>
 /// Gets the default child occur value
 /// </summary>
 /// <returns></returns>
 protected virtual Matches GetDefaultChildrenOccur()
 {
     if (defaultChildrenOccur == Matches.NotSet)
     {
         defaultChildrenOccur = Matches.Always;
     }
     return defaultChildrenOccur;
 }
コード例 #17
0
    public Matches[] SortVertices(Vector3[] object1, Vector3[] object2)
    {
        //High vert object will contain the object with a greater number of vertices
        Vector3[] highVertObject = null;

        //Low vert object will contain the object with a lower number of vertices
        Vector3[] lowVertObject = null;

        List<int> highVertMappedIndices = new List<int> ();
        //First we find which object has more vertices (We will want to map from high vertice object to low vertice obect)
        if (object1.Length >= object2.Length) {
            highVertObject = object1;
            lowVertObject = object2;
        } else {
            highVertObject = object2;
            lowVertObject = object1;
        }

        //The matches struct will match each vertice on the small vert object to 1+ vertices on the high vert object
        Matches[] matches = new Matches[lowVertObject.Length];
        for (int i = 0; i < matches.Length; i++) {
            matches [i].parentVert = lowVertObject [i];
            matches [i].verts = new List<Vector3> ();
            matches [i].arrayLocations = new List<int> ();
        }

        //Now we will want a way to compute distances for points in each array this will be accomplished with a 2D array
        //The rows of this array will be made up of the vertices of the vertices highVertObject while the columns are made up of the vertices of the lowVertObject
        float[,] verticeDistances = new float[highVertObject.Length, lowVertObject.Length];
        if(matchAll)
        {
            for (int i = 0; i < highVertObject.Length; i++) {
                for (int j = 0; j < lowVertObject.Length; j++) {
                    verticeDistances [i, j] = Vector3.Distance (highVertObject [i], lowVertObject [j]);
                }
            }

            //Find which vertice on the high vert object each vertice on the low vert object is mapped closest to.
            //We do not want a single vertice on low vert object to be mapped to multiple vertices on the high vert object
            for (int i = 0; i < matches.Length; i++) {
                int minHighVertDistIndex = Int32.MaxValue;
                int minLowVertDistIndex = Int32.MaxValue;
                float minVertDistValue = float.MaxValue;
                //Find the minumum distance in the 2d array so we can map the two points together
                for (int j = 0; j < highVertObject.Length; j++) {
                    for (int k = 0; k < lowVertObject.Length; k++) {
                        if (verticeDistances [j, k] < minVertDistValue) {
                            minHighVertDistIndex = j;
                            minLowVertDistIndex = k;
                            minVertDistValue = verticeDistances [j, k];
                        }
                    }
                }
                //Store the min value into the matches array
                matches [minLowVertDistIndex].verts.Add (highVertObject [minHighVertDistIndex]);
                matches [minLowVertDistIndex].arrayLocations.Add (minHighVertDistIndex);
                //Add which vertice got mapped to the
                highVertMappedIndices.Add (minHighVertDistIndex);
                //Maximize all values in the current lowvertdistindex column and minHighVertDistIndex row so that we don't end up mapping multiple values from the low vert shape into the high vert shape
                for (int j = 0; j < lowVertObject.Length; j++) {
                    verticeDistances [minHighVertDistIndex, j] = float.MaxValue;
                }
                for (int j = 0; j < highVertObject.Length; j++) {
                    verticeDistances [j, minLowVertDistIndex] = float.MaxValue;
                }
            }
        }

        //Now we will need to recreate the 2d distance array
        for (int i = 0; i < highVertObject.Length; i++)
        {
            for (int j = 0; j < lowVertObject.Length; j++)
            {
                verticeDistances[i, j] = Vector3.Distance(highVertObject[i], lowVertObject[j]);
            }
        }

        //Now we need to map the remaining vertices on the highVertObject to a vertice on the low vert object
        //To do this we will find the closest vertice in the lowVertObject to each vertice in the highVert object and map them together
        for(int i = 0; i<highVertObject.Length; i++)
        {
            //We dont want to remap any vertices so if we find one that's already been mapped we will skip it
            if(!highVertMappedIndices.Contains(i))
            {
                int minLowVertIndex = 0;
                float minLowVertDist = float.MaxValue;
                for (int j = 0; j < lowVertObject.Length; j++ )
                {
                    if(verticeDistances[i,j]<minLowVertDist)
                    {
                        minLowVertIndex = j;
                        minLowVertDist = verticeDistances[i, j];
                    }
                }
                matches[minLowVertIndex].verts.Add(highVertObject[i]);
                matches[minLowVertIndex].arrayLocations.Add(i);
            }
        }

        //We want to insure that every vertice in the lowVert object is mapped to, so we will start out by mapping each lowVert vertice to a single highVert vertice
        return matches;
    }
コード例 #18
0
 public static Query Language(this IQueryBuilder inputQueryBuilder, Language language, Matches occur = Matches.NotSet, float? boost = null, string key = null)
 {
     string languageString = language.CultureInfo.Name.ToLower();
     return inputQueryBuilder.Keyword(SitecoreFields.Language, languageString, occur, boost, key);
 }
コード例 #19
0
 public static IQueryBuilder Ids(this IQueryBuilder inputQueryBuilder, ID[] itemIds, float? boost = null, Matches occur = Matches.NotSet, Matches childrenOccur = Matches.NotSet, string key = null)
 {
     var group = inputQueryBuilder.Group(occur);
     foreach (ID itemId in itemIds)
     {
         group.Id(itemId, childrenOccur, boost, key);
     }
     return inputQueryBuilder;
 }
コード例 #20
0
        /// <summary>
        /// Sets up and adds a wildcard query object allowing the search for an explcit term in the field
        /// </summary>
        /// <param name="fieldName">The field name to search within</param>
        /// <param name="fieldValue">The value to match</param>
        /// <param name="occur">Whether it must, must not or should occur in the field</param>
        /// <param name="boost">A boost multiplier (1 is default / normal).</param>
        /// <param name="key">The dictionary key to allow reference beyond the initial scope</param>
        /// <param name="caseSensitive"></param>
        /// <returns>The generated wildcard query object</returns>
        public virtual WildcardQuery WildCard(string fieldName, string fieldValue, Matches occur = Matches.NotSet, float? boost = null, string key = null, bool? caseSensitive = null)
        {
            Term term = GetTerm(fieldName, fieldValue, caseSensitive);
            WildcardQuery query = new WildcardQuery(term);
            SetBoostValue(query, boost);

            Add(query, occur, key);
            return query;
        }
コード例 #21
0
        public virtual IQueryBuilder WildCards(string fieldName, string[] fieldValues, Matches occur = Matches.NotSet,
								  float? boost = null, bool? caseSensitive = null)
        {
            var group = Group();
            foreach (var fieldValue in fieldValues)
            {
                group.WildCard(fieldName, fieldValue, occur, boost, caseSensitive:caseSensitive);
            }
            return this;
        }
コード例 #22
0
        public virtual Query Keyword(string fieldName, string fieldValue, Matches occur = Matches.NotSet, float? boost = null, string key = null,
		                     bool? caseSensitive = null)
        {
            if (!caseSensitive.HasValue || !caseSensitive.Value)
            {
                fieldValue = fieldValue.ToLower();
            }
            return Raw(fieldName, fieldValue, occur, boost, key, KeywordAnalyzer);
        }
コード例 #23
0
        protected virtual void SetOccurValue(IQueryBuilder inputQueryBuilder, ref Matches occur)
        {
            if (occur != Matches.NotSet)
            {
                return;
            }

            occur = inputQueryBuilder != null ? inputQueryBuilder.DefaultChildrenOccur : Matches.Always;
        }
コード例 #24
0
        public virtual IQueryBuilder Keywords(string fieldName, string[] fieldValues, Matches occur = Matches.NotSet, float? boost = null, string key = null,
		                      bool? caseSensitive = null)
        {
            var group = Group();
            foreach (var fieldValue in fieldValues)
            {
                group.Raw(fieldName, fieldValue, occur, boost, key, KeywordAnalyzer);
            }
            return this;
        }
コード例 #25
0
 /// <summary>
 /// Creates a simple group allowing the specification of whether it should occur, and specification of each items occurance.
 /// </summary>
 /// <param name="occur">Whether the group must / should occur</param>
 /// <param name="childrenOccur">Whether the child query should occur by default</param>
 /// <param name="queries">The lamdba expressions showing queries</param>
 public virtual IQueryBuilder Group(Matches occur = Matches.NotSet, Matches childrenOccur = Matches.NotSet, params Action<IQueryBuilder>[] queries)
 {
     if (occur == Matches.NotSet)
     {
         occur = Matches.Always;
     }
     var groupedBooleanQuery = AddChildGroup(occur, childrenOccur, queries);
     if (groupedBooleanQuery == null)
     {
         throw new Exception("An error occurred creating the inner query");
     }
     return groupedBooleanQuery;
 }
コード例 #26
0
 /// <summary>
 /// Creates a simple group allowing the specification of whether it should occur, each item of which MUST occur by default
 /// </summary>
 /// <param name="occur">Whether the group must / should occur</param>
 /// <param name="queries">The lamdba expressions showing queries</param>
 public virtual IQueryBuilder And(Matches occur = Matches.NotSet, params Action<IQueryBuilder>[] queries)
 {
     Group(occur, Matches.Always, queries);
     return this;
 }
コード例 #27
0
        protected virtual IQueryBuilder AddChildGroup(Matches occur = Matches.NotSet, Matches childrenOccur = Matches.NotSet, params Action<IQueryBuilder>[] queries)
        {
            if (occur == Matches.NotSet)
            {
                occur = Matches.Always;
            }
            if (childrenOccur == Matches.NotSet)
            {
                childrenOccur = Matches.Always;
            }

            IQueryBuilder queryBuilder = CreateNewChildGroup(occur, childrenOccur);
            foreach (var item in queries)
            {
                item(queryBuilder);
            }
            Groups.Add(queryBuilder);
            return queryBuilder;
        }
コード例 #28
0
		public void Simulate(NodeCollection nodes, MT19937Generator rnd)
		{
			var bots = new Dictionary<PlayerName, ACDCBot>()
			{
				{ PlayerName.player1, GetBot(nodes, PlayerName.player1, rnd) },
				{ PlayerName.player2, GetBot(nodes, PlayerName.player2, rnd) },
			};

			var matches = new Matches();
			matches.Round = 1;
			var stack1 = 2000;
			var stack2 = 2000;

			var blind = 20;
			
			for (var round = 1; round < int.MaxValue; round++)
			{
				if (round % 10 == 0) { blind += 10; }
				var small = blind >> 1;

				matches.Round = round;
				matches.Current.Player1.Stack = stack1;
				matches.Current.Player2.Stack = stack2;

				var mirrored = (round & 1) == 0;

				var shuffled = Cards.GetShuffledDeck(rnd);
				var deck1 = Cards.Empty;
				var deck2 = Cards.Empty;
				var tabl0 = Cards.Empty;
				var tabl3 = Cards.Empty;
				var tabl4 = Cards.Empty;
				var tabl5 = Cards.Empty;

				deck1.AddRange(shuffled.Take(2));
				deck2.AddRange(shuffled.Skip(2).Take(2));
				tabl3.AddRange(shuffled.Skip(4).Take(3));
				tabl4.AddRange(shuffled.Skip(4).Take(4));
				tabl5.AddRange(shuffled.Skip(4).Take(5));

				var tables = new Cards[] { tabl0, tabl3, tabl4, tabl5 };

				matches.Current.BigBlind = blind;
				matches.Current.SmallBlind = small;
				matches.Current.Player1.Hand = deck1;
				matches.Current.Player2.Hand = deck2;

				SetPot(matches.Current, mirrored);

				var outcome = PlayerName.None;

				var showdown = false;

				foreach (var table in tables)
				{
					matches.Current.Table = table;
					outcome = SimulateRound(matches, bots);
					if (outcome != PlayerName.None) { break; }
				}
				if (outcome == PlayerName.None)
				{
					showdown = true;
					outcome = PokerHandEvaluator.GetOutcome(deck1, deck2, tabl5);
				}
				if (outcome == PlayerName.None)
				{
					matches.Current.Player1.Stack += matches.Current.Pot >> 1;
					matches.Current.Player2.Stack += matches.Current.Pot >> 1;
				}
				else
				{
					var realoutcome = outcome;
					if (!showdown)
					{
						realoutcome = PokerHandEvaluator.GetOutcome(deck1, deck2, tabl5);
					}
					matches.Current[outcome].Stack += matches.Current.Pot;

					if (realoutcome == outcome)
					{
						var wins = new WinsInstruction(outcome, matches.Current.Pot);
						bots[PlayerName.player1].Update(wins);
						bots[PlayerName.player2].Update(wins);
					}
					// A bot chickened later, but that should not matter for the bits it played.
					else
					{
						bots[PlayerName.player1].Update(new WinsInstruction(PlayerName.player1, matches.Current.Pot));
						bots[PlayerName.player2].Update(new WinsInstruction(PlayerName.player2, matches.Current.Pot));
					}
				}
				matches.Current.Player1.Pot = 0;
				matches.Current.Player2.Pot = 0;

				stack1 = matches.Current.Player1.Stack;
				stack2 = matches.Current.Player2.Stack;

				if (stack1 < blind || stack2 < blind)
				{
					break;
				}
			}
		}
コード例 #29
0
        public virtual NumericRangeQuery<long> NumericRange(string fieldName, long minValue, long maxValue, Matches occur = Matches.NotSet, float? boost = null,
									int precisionStep = 1, bool includeMin = true, bool includeMax = true, string key = null)
        {
            NumericRangeQuery<long> numericRangeQuery = NumericRangeQuery.NewLongRange(fieldName, precisionStep, minValue, maxValue, includeMin, includeMax);
            SetBoostValue(numericRangeQuery, boost);
            Add(numericRangeQuery, occur, key);
            return numericRangeQuery;
        }
コード例 #30
0
 public int FindMatch(Matches theMatcher, int theExpectedRow, Parse theExpectedCells)
 {
     int result = -1;
     if (myActuals.Count == 0) return result;
     int lastMatched = -1;
     for (int row = 0; row < myActuals.Count; row++) {
         if (myActuals[row].MatchRow != null) {
             lastMatched = row;
             continue;
         }
         if (result == -1 && theMatcher(theExpectedCells, myActuals[row].Value)) {
             result = row;
         }
     }
     if (result > -1) {
         myActuals[result].MatchRow = theExpectedRow;
         UnmatchedCount--;
     } else {
         myActuals.Insert(lastMatched + 1, new ActualItem(null, -1));
     }
     return result;
 }
コード例 #31
0
 public virtual Occur GetLuceneOccur(Matches matches)
 {
     switch (matches)
     {
         case Matches.Never:
             return Lucene.Net.Search.Occur.MUST_NOT;
         case Matches.Sometimes:
             return Lucene.Net.Search.Occur.SHOULD;
         default:
             return Lucene.Net.Search.Occur.MUST;
     }
 }
コード例 #32
0
        /// <summary>
        /// Sets up and adds a phrase query object allowing the search for an explcit term in the field
        /// To add terms, use the AddTerm() query extension
        /// </summary>
        /// <param name="occur">Whether it must, must not or should occur in the field</param>
        /// <param name="slop">The allowed distance between the terms</param>
        /// <param name="boost">A boost multiplier (1 is default / normal).</param>
        /// <param name="key">The dictionary key to allow reference beyond the initial scope</param>
        /// <returns>The generated phrase query object</returns>
        public virtual PhraseQuery Phrase(int slop, float? boost = null, Matches occur = Matches.NotSet, string key = null)
        {
            PhraseQuery query = new PhraseQuery();

            SetBoostValue(query, boost);
            query.Slop = slop;

            Add(query, occur, key);
            return query;
        }
コード例 #33
0
		private PlayerName SimulateRound(Matches matches, Dictionary<PlayerName, ACDCBot> bots)
		{
			var action = GameAction.Invalid;

			var p1 = bots[matches.Current.OnButton.Other()];
			var p2 = bots[matches.Current.OnButton];

			var s = 0;

			while (true)
			{
				s++;
				p1.Update(matches);
				action = p1.GetResponse(TimeSpan.Zero).Action;
				if (action == GameAction.Fold) { return matches.Current.OnButton; }
				if (action == GameAction.Check) { if (s > 1) { return PlayerName.None; } }
				else
				{
					var toCall = matches.Current.Off.GetAmountToCall(matches.Current.On);
					matches.Current.Off.Call(toCall);
					matches.Current.Off.Act(action);
				}

				s++;
				p2.Update(matches);
				action = p2.GetResponse(TimeSpan.Zero).Action;
				if (action == GameAction.Fold) { return matches.Current.OnButton.Other(); }
				if (action == GameAction.Check) { return PlayerName.None; }

				else
				{
					var toCall = matches.Current.On.GetAmountToCall(matches.Current.Off);
					matches.Current.On.Call(toCall);
					matches.Current.On.Act(action);
				}
			}
		}
コード例 #34
0
 /// <summary>
 /// Adds a phrase query with a number of pre-specified values
 /// </summary>
 /// <param name="fieldName">The field name to query</param>
 /// <param name="fieldValues">The array of field values</param>
 /// <param name="slop">The distance between values</param>
 /// <param name="occur">The occurance for the query</param>
 /// <param name="boost">The boost value for the query</param>
 /// <param name="caseSensitive">A boolean denoting whether or not to retain case</param>
 /// <returns>The input query builder</returns>
 public virtual IQueryBuilder Phrase(string fieldName, string[] fieldValues, int slop, Matches occur = Matches.NotSet, float? boost = null, bool? caseSensitive = null)
 {
     PhraseQuery phrase = Phrase(slop, boost, occur);
     foreach (var fieldValue in fieldValues)
     {
         phrase.AddTerm(this, fieldName, fieldValue, caseSensitive);
     }
     return this;
 }
コード例 #35
0
ファイル: Timer.cs プロジェクト: wshanshan/DDD
        /// <summary>
        /// Coordinates all the processing for each time slice
        /// </summary>
        /// <param name="updateIncrement"></param>
        public static void NextTimeSlice()
        {


            /*
             * Initially the only items that would be named in events would be actual units.
             * Now that other things (ActiveRegions,for example) can also appear in events
             * it is necessary to allow UnitFActs to know those names too, to keep various checks on
             * object name legality from failing
             */
            /* 1. Process the incoming list of events from below */
            // Which units are currently on the incoming list?
            List<string> unitList = IncomingList.AffectedUnits();
            for (int i = 0; i < unitList.Count; i++)
            {
                List<IncomingItemType> eventList = IncomingList.Retrieve(unitList[i]);


                /* do things with these events */
                for (int j = 0; j < eventList.Count; j++)
                {
                    ScenarioEventType thisItem = eventList[j].TheEvent;
                    Coordinator.debugLogger.Writeline("Timer", "Time: " + timer + " Unit " + unitList[i] + " has incoming " + thisItem.GetType().ToString(), "test");

                    if (UnitFacts.AnyDead(thisItem.AllUnits))
                    {
                        continue;
                    }
                    Boolean launchedByOwner;
                    switch (thisItem.GetType().ToString())
                    {

                        case name_Space + "MoveComplete_Event":
                            {
                                Coordinator.debugLogger.Writeline("Timer", "Unit " + thisItem.UnitID + " MoveComplete discovered at t=" + timer.ToString(), "test");
                                // scan happenings list for matches                          
                                VerifyMatch = ActionMatch;
                                SeekHappening(thisItem.UnitID, "MoveComplete_Event");


                                SeekSpeciesHappening(thisItem, "MoveComplete_Event");

                            }
                            break;
                        case name_Space + "StateChangeNotice":
                            string newState = ((StateChangeNotice)thisItem).NewState;
                            Coordinator.debugLogger.Writeline("Timer", "Unit " + thisItem.UnitID + " StateChange to " + newState + " discovered at t=" + timer.ToString(), "test");

                            VerifyMatch = StateMatch;
                            List<string> affectedUnitList = new List<string>();
                            if ("Dead" != newState)
                            {
                                affectedUnitList.Add(thisItem.UnitID);

                                UnitFacts.CurrentUnitStates[thisItem.UnitID] = newState;// newState;

                            }
                            else              // Purge queues if the new state is "Dead"
                            {

                                affectedUnitList = SubplatformRecords.DeepDockedList(thisItem.UnitID);
                            }
                            for (int someUnit = 0; someUnit < affectedUnitList.Count; someUnit++)
                            {
                                if ("Dead" == newState)
                                {
                                    UnitFacts.CurrentUnitStates[affectedUnitList[someUnit]] = "Dead";// newState;
                                    //first drop all timer events involving this unit
                                    TimerQueueClass.FlushOneUnit(affectedUnitList[someUnit]);
                                }
                                SeekHappening(affectedUnitList[someUnit], newState);

                                //Then if dead, remove all happening events involving this unit
                                if ("Dead" == newState)
                                {
                                    HappeningList.FlushOneUnit(affectedUnitList[someUnit]);
                                    Coordinator.debugLogger.Writeline("Timer", " stateChangeEvent for  " + affectedUnitList[someUnit], "test");
                                }
                                SeekSpeciesHappening(thisItem, newState);
                            }
                            break;
                        case name_Space + "AttackSuccessfulNotice":
                            AttackSuccessfulNotice asn = (AttackSuccessfulNotice)thisItem;
                            for (int asi = 0; asi < AttackSuccessfulList.Happenings.Count; asi++)
                            {

                                AttackSuccessfulCompletionType tryThisEvent = AttackSuccessfulList.Happenings[asi];
                                if (tryThisEvent.Matches(asn))
                                {
                                    if (tryThisEvent.DoThisList.Count > 0)
                                        AttackSuccessfulCompletionType.EnqueueEvents(asn.UnitID, asn.Target, tryThisEvent.DoThisList);

                                    break;
                                }
                            }
                            break;
                        case name_Space + "AttackObjectRequestType":

                            Coordinator.debugLogger.Writeline("Timer", "Attack request for  " + thisItem.UnitID + "attack Request discovered at t=" + timer.ToString(), "test");

                            AttackObjectRequestType recastAOR = (AttackObjectRequestType)thisItem;

                            if (ApprovalsList.AttackApproved(recastAOR))
                            {
                                string attacker = recastAOR.UnitID;
                                string target = recastAOR.TargetObjectID;
                                AttackObjectEvent attack = new AttackObjectEvent(attacker, target, recastAOR.CapabilityName);
                                attack.AddOtherUnit(target);
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000/*Coordinator.UpdateIncrement*/), attack);
                            }
                            else
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000), new SystemMessage(1, recastAOR.UnitID, "Attack against " + recastAOR.TargetObjectID + " failed."));


                            break;

                        case name_Space + "WeaponLaunchRequestType":
                            WeaponLaunchRequestType recastWL = (WeaponLaunchRequestType)thisItem;
                            string unitID = recastWL.UnitID;
                            string weaponID = recastWL.WeaponID;
                            string targetID = recastWL.TargetObjectID;
                            Coordinator.debugLogger.Writeline("Timer", "Weapon Launch request for  " + unitID + " using " + weaponID + " Attack Request discovered at t=" + timer.ToString(), "test");

                            string platformOwner = UnitFacts.Data[unitID].Owner;
                            string weaponOwner = UnitFacts.Data[weaponID].Owner;
                            launchedByOwner = SpeciesType.GetSpecies(UnitFacts.Data[weaponID].Species).LaunchedByOwner;
                            //   )
                            if (
                               SubplatformRecords.IsLaunchableWeapon(unitID, weaponID)
                               &&
                               (
                               (platformOwner == recastWL.DecisionMaker)
                               ||
                               (weaponOwner == recastWL.DecisionMaker) && launchedByOwner
                                )
                               )
                            {
                                // validate attack
                                DecisionMakerType targetDM = DecisionMakerType.GetDM(UnitFacts.GetDM(targetID));
                                if (
                                    (launchedByOwner && UnitFacts.HostileTo(DecisionMakerType.GetDM(platformOwner).Team, targetDM.Team))
                                    ||
                                    (UnitFacts.HostileTo(DecisionMakerType.GetDM(weaponOwner).Team, targetDM.Team))
                                    //Removed !launchedByOwner from second statement
                                    )
                                {
                                    //NB. THe code that builds and sends the event was missing from here. It was last seen in rev 232.
                                    // its removeal was probably an accident?
                                    // build event to send down
                                    WeaponLaunch_EventType wEvent = new WeaponLaunch_EventType(unitID, targetID, weaponID);
                                    TimerQueueClass.Add(1 + (int)(timer / 1000), wEvent);
                                    // replace by new platform handling       

                                }
                            }
                            else
                            {
                                //need to throw an event back to ViewPro to re-allocate weapon
                                String reason = "";
                                if (!UnitFacts.Data.ContainsKey(unitID))
                                {
                                    reason = "Platform object is unknown by the system.";
                                }
                                else if (UnitFacts.Data[unitID].Owner != recastWL.DecisionMaker)
                                {
                                    reason = "Requesting DM does not own the Platform object.";
                                }

                                WeaponLaunchFailure_EventType failEvent = new WeaponLaunchFailure_EventType(weaponID, unitID, reason);
                                failEvent.Time = (int)(timer / 1000/*Coordinator.UpdateIncrement*/);
                                TimerQueueClass.Add(1 + (int)(timer / 1000/*Coordinator.UpdateIncrement*/), failEvent);
                            }
                            break;

                        case name_Space + "SubplatformLaunchRequestType":
                            SubplatformLaunchRequestType recastSL = (SubplatformLaunchRequestType)thisItem;
                            string childID = recastSL.UnitID;
                            string requestor = recastSL.Requestor;
                            string parentID = recastSL.ParentUnit;
                            LocationType destination = recastSL.Destination;
                            Coordinator.debugLogger.Writeline("Timer", "Subplatform Launch request for  " + childID + " from " + parentID + "  discovered at t=" + timer.ToString(), "test");
                            launchedByOwner = SpeciesType.GetSpecies(UnitFacts.Data[childID].Species).LaunchedByOwner;

                            if (
                             (UnitFacts.Data[parentID].Owner == requestor)
                             ||
                             (UnitFacts.Data[childID].Owner == requestor) && launchedByOwner
                             )
                            {
                                // build event to send down
                                SubplatformLaunchType slEvent = new SubplatformLaunchType(childID, parentID, destination);
                                TimerQueueClass.Add(1 + (int)(timer / 1000), slEvent);


                            }
                            /**/

                            break;
                        case name_Space + "SubplatformDockRequestType":
                            SubplatformDockRequestType recastSD = (SubplatformDockRequestType)thisItem;
                            string orphanID = recastSD.UnitID;
                            string dockRequestor = recastSD.Requestor;
                            string adopterID = recastSD.ParentUnit;

                            Coordinator.debugLogger.Writeline("Timer", "Subplatform Dock request for  " + orphanID + " from " + adopterID + "  discovered at t=" + timer.ToString(), "test");

                            if ("" != adopterID)
                            {
                                if (UnitFacts.Data.ContainsKey(orphanID)
                                    && UnitFacts.Data.ContainsKey(adopterID)
                                    && ((UnitFacts.Data[orphanID].Owner == dockRequestor)
                                    //     && (UnitFacts.Data[adopterID].Owner == dockRequestor)
                                        )
                                    && SpeciesType.GetSpecies(UnitFacts.GetSpecies(adopterID)).CanHaveSubplatform(UnitFacts.GetSpecies(orphanID))
                                    )
                                {
                                    /* for dock to any object*/
                                    SubplatformDockType sdEvent = new SubplatformDockType(orphanID, adopterID);
                                    TimerQueueClass.Add(1 + (int)(timer / 1000), sdEvent);



                                }
                            }// if  the parent is "" just ignore the request
                            else
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000), new SystemMessage(1, dockRequestor, "Docking of " + orphanID + "to " + adopterID + " failed."));

                            break;
                        case name_Space + "MoveObjectRequestType":
                            // does this dM control this object
                            MoveObjectRequestType recastMove = (MoveObjectRequestType)thisItem;

                            Coordinator.debugLogger.Writeline("Timer", "Move request for  " + thisItem.UnitID + " discovered at t=" + timer.ToString(), "test");


                            if (UnitFacts.Data.ContainsKey(recastMove.UnitID) && (UnitFacts.Data[recastMove.UnitID].Owner == recastMove.DecisionMaker))
                            {
                                Move_EventType mover = new Move_EventType(recastMove.UnitID, TimerTicker.Timer, recastMove.Destination, recastMove.Throttle);
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000/*Coordinator.UpdateIncrement*/), mover);
                            }
                            else
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000), new SystemMessage(1, recastMove.DecisionMaker, "Move of " + recastMove.UnitID + " denied."));

                            break;

                        case name_Space + "TransferObjectRequest":
                            Boolean transferred = false;
                            TransferObjectRequest recastTransferRequest = (TransferObjectRequest)thisItem;
                            /*
                              * Transfer is allowed when
                              * (1) requestor is owner of asset and has transfer authority
                              * (2) owner of unit is  subordinate of requestor, who has forced transfer authority
                              * Unit is in a stealable state
                              * * */
                            DecisionMakerType unitDM = DecisionMakerType.GetDM(UnitFacts.GetDM(recastTransferRequest.UnitID));
                            DecisionMakerType requestingDM = DecisionMakerType.GetDM(recastTransferRequest.Requestor);
                            DecisionMakerType receivingDM = DecisionMakerType.GetDM(recastTransferRequest.Recipient);

                            // To know if stealable, need current state
                            Boolean inStealableState = false;
                            Dictionary<string, StateBody> allStates = StatesForUnits.GetExpandedStatesOf(recastTransferRequest.UnitID);
                            if (allStates.ContainsKey(recastTransferRequest.State))
                            {
                                StateBody thisState = allStates[recastTransferRequest.State];
                                inStealableState = thisState.Parameters.ContainsKey("Stealable");
                            }


                            if ((unitDM.Identifier == requestingDM.Identifier) && (requestingDM.HasTransferAuthority)
                                ||// does the path from requestor to unit contain and forced transfers?
                                (requestingDM.CanForceTransferOf(unitDM)
                                ||
                            (
                                inStealableState && (recastTransferRequest.Requestor == receivingDM.Identifier))))
                            {


                                if (receivingDM.CanOwn(recastTransferRequest.UnitID))
                                    transferred = UnitFacts.ChangeDM(recastTransferRequest.UnitID, recastTransferRequest.Recipient);
                            }
                            if (transferred)
                            {
                                TransferEvent confirmation = new TransferEvent(recastTransferRequest.UnitID, UnitFacts.GetDM(recastTransferRequest.UnitID), recastTransferRequest.Recipient);
                                EventCommunicator.SendEvent(confirmation);
                                VerifyMatch = ActionMatch;
                                SeekHappening(thisItem.UnitID, "TransferObject");
                                SeekSpeciesHappening(thisItem, "TransferObject");

                                //Note: Event here is successful transfer, not request
                            }
                            else
                                TimerQueueClass.Add(1 + (int)(TimerTicker.Timer / 1000), new SystemMessage(1, recastTransferRequest.Requestor, "Transfer of " + recastTransferRequest.UnitID + " to " + recastTransferRequest.Recipient + " denied."));

                            break;


                        case name_Space + "SelfDefenseAttackNotice":
                            /*
                             * Notice: Assuming that self-defense only against enemy and that the condition is satisfied
                             * by the attack, without any attention to who the enemy is.  Will surely need a "Team" level happenings queue in time
                             */
                            {
                                Coordinator.debugLogger.Writeline("Timer", "Unit " + thisItem.UnitID + " SelfDefenseAttackNotice discovered at t=" + timer.ToString(), "test");
                                // scan happenings list for matches    
                                VerifyMatch = ActionMatch;
                                SeekHappening(thisItem.UnitID, "SelfDefenseAttackNotice");




                                SeekSpeciesHappening(thisItem, "SelfDefenseAttackNotice");
                                break;
                            }// 
コード例 #36
0
 public virtual Query Raw(string field, string queryText, Matches occur = Matches.NotSet, float? boost = null, string key = null, Analyzer analyzer = null)
 {
     if (analyzer == null)
     {
         analyzer = new StandardAnalyzer(Version.LUCENE_29);
     }
     QueryParser queryParser = new QueryParser(Version.LUCENE_29, field, analyzer);
     Query query = queryParser.Parse(queryText);
     SetBoostValue(query, boost);
     Add(query, occur, key);
     return query;
 }