Ejemplo n.º 1
0
        /// <summary>
        /// Customize this child
        /// </summary>
        public IsosTri90Tess()
        {
            InitializeComponent();
            double size = 40d;
            double temp = Math.Tan(Math.PI / 4d) * (size / 2);
            Pattern pat = new Pattern(size, temp * 2d, 0);
            List<DoublePoint> tri1 = new List<DoublePoint>();
            List<DoublePoint> tri2 = new List<DoublePoint>();
            List<DoublePoint> tri3 = new List<DoublePoint>();
            List<DoublePoint> tri4 = new List<DoublePoint>();
            addStartZone(new Point(0, 0), new Point((int)size, 0));
            setShapeHeight(temp);

            tri1.Add(new DoublePoint(0, 0));
            tri1.Add(new DoublePoint(size / 2, temp));
            tri1.Add(new DoublePoint(0, temp*2));

            tri2.Add(new DoublePoint(0, 0));
            tri2.Add(new DoublePoint(size, 0));
            tri2.Add(new DoublePoint(size / 2, temp));

            tri3.Add(new DoublePoint(size, temp * 2));
            tri3.Add(new DoublePoint(0, temp * 2));
            tri3.Add(new DoublePoint(size / 2, temp));

            tri4.Add(new DoublePoint(size, temp * 2));
            tri4.Add(new DoublePoint(size, 0));
            tri4.Add(new DoublePoint(size / 2, temp));

            pat.addPattern(tri1);
            pat.addPattern(tri2);
            pat.addPattern(tri3);
            pat.addPattern(tri4);
            setPattern(pat);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///   Creates a new instance of the <see cref="SchematronValidationEventArgs"/>.
        /// </summary>
        /// <param name="schematron">The <see cref="SchematronDocument"/> that detected the event.</param>
        /// <param name="queryEngine">The <see cref="IQueryLanguage"/> that detected the event.</param>
        /// <param name="pattern">The active <see cref="Pattern"/>.</param>
        /// <param name="rule">The <see cref="Sepia.Schematron.Rule"/> that caused the event to be raised.</param>
        /// <param name="assertion">The <see cref="Sepia.Schematron.Assertion"/> that caused the event to be raised.</param>
        /// <param name="context">An <see cref="object"/> that provides the context for the <paramref name="rule"/> and <paramref name="assertion"/>.</param>
        /// <param name="instance">An <see cref="XPathNavigator"/> to the document node that cause the event to be raised.</param>
        public SchematronValidationEventArgs(SchematronDocument schematron, IQueryLanguage queryEngine, Pattern pattern, Rule rule, Assertion assertion, object context, XPathNavigator instance)
        {
            this.schematron = schematron;
             this.queryEngine = queryEngine;
             this.pattern = pattern;
             this.rule = rule;
             this.assertion = assertion;
             this.instance = instance.Clone();

             if (assertion == null)
             {
            message = "A schematron validation event occured.";
             }
             else
             {
            message = assertion.Message.ToString(instance, context);
             }

             List<string> diagnostics = new List<string>();
             if (assertion != null && !string.IsNullOrEmpty(assertion.Diagnostics))
             {
            foreach (string id in assertion.Diagnostics.Split(' '))
            {
               Diagnostic diagnostic = schematron.Diagnostics[id];
               diagnostics.Add(diagnostic.Message.ToString(instance, context));
            }
             }
             this.diagnostics = diagnostics.ToArray();
        }
 private static Pattern<Word, ShapeNode> CreateEnvironmentPattern(Pattern<Word, ShapeNode> env)
 {
     Pattern<Word, ShapeNode> pattern = null;
     if (!env.IsEmpty)
         pattern = new Pattern<Word, ShapeNode>(env.Children.DeepCloneExceptBoundaries());
     return pattern;
 }
Ejemplo n.º 4
0
 public MatchResult(Pattern pattern, int x, int y, E_BlockType type)
 {
     this.pattern = pattern;
     this.x = x;
     this.y = y;
     this.type = type;
 }
Ejemplo n.º 5
0
 public static void PlayTact(Note root, Pattern pattern, OutputDevice outputDevice)
 {
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     Thread.Sleep(400);
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     Thread.Sleep(150);
     PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(400);
     PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(200);
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     Thread.Sleep(150);
     PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(200);
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     Thread.Sleep(400);
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     Thread.Sleep(150);
     PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(400);
     PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(200);
     PlayAccord(root, pattern, Direction.Down, outputDevice);
     //Thread.Sleep(150);
     //PlayAccord(root, pattern, Direction.Up, outputDevice);
     Thread.Sleep(400);
 }
Ejemplo n.º 6
0
    private void GeneratePattern()
    {
        Pattern pattern = new Pattern();

        int count = Random.Range(GameController.instance.minPatternSize_, GameController.instance.maxPatternSize_ + 1);

        var node = nodes_.Last;
        for (int index = Random.Range(0, nodes_.Count); index > 0; --index, node = node.Previous) ;

        node.Value.isActive = false;
        pattern.pattern.AddLast(node.Value);

        for (int i = 0; i < count; ++i) {
            LinkedList<PatternNode> adjacentNodes = node.Value.GetActiveAdjacentNodes();

            if (adjacentNodes.Count < 0) {
                break;
            }

            var adjacentNode = adjacentNodes.Last;
            for (int index = Random.Range(0, adjacentNodes.Count); index > 0; --index, adjacentNode = adjacentNode.Previous) ;

            pattern.pattern.AddLast(adjacentNode.Value);
            node = nodes_.Find(adjacentNode.Value);
            node.Value.isActive = false;
        }

        GameController.instance.RegisterPattern(pattern);
        for (node = nodes_.First; node != null; node.Value.isActive = true, node = node.Next) ;
    }
Ejemplo n.º 7
0
 /// <summary>
 /// This Method Performs Drag and Drop an element from scrolllist to Workfield by Sikuli4net
 /// </summary>
 /// <param name="scrollElement">Scroll Element class</param>
 public void DragAndDrop(ScrollElement scrollElement)
 {
     Pattern pattern_Drag = new Pattern(Configuration.PathToImgs()+scrollElement.GetImageDragPatern());
     Pattern pattern_Drop = new Pattern(Configuration.PathToImgs() + "wrk.png",0.5f);
     Screen scrn = new Screen();
     scrn.DragDrop(pattern_Drag,pattern_Drop);
 }
        public NarrowSynthesisRewriteSubruleSpec(SpanFactory<ShapeNode> spanFactory, MatcherSettings<ShapeNode> matcherSettings, bool isIterative,
			int targetCount, RewriteSubrule subrule, int index)
            : base(spanFactory, matcherSettings, isIterative, subrule, index)
        {
            _rhs = subrule.Rhs;
            _targetCount = targetCount;
        }
Ejemplo n.º 9
0
        public override void Init(ParsingContext context, ParseTreeNode parseNode)
        {
            base.Init(context, parseNode);

            foreach (var node in parseNode.ChildNodes)
            {
                if (node.AstNode is Pattern)
                {
                    Pattern = node.AstNode as Pattern;
                }
                else if (node.AstNode is AuxiliaryNode)
                {
                    var nodes = (node.AstNode as AuxiliaryNode).ChildNodes;
                    Conditions = nodes.OfType<Conditions>().FirstOrDefault();
                    Expression = nodes.OfType<Expression>().FirstOrDefault();
                }
            }

            foreach (var astNode in new AstNode[] { Pattern, Conditions, Expression })
            {
                if (astNode != null)
                {
                    astNode.Parent = this;
                }
            }

            AsString = "match";
        }
Ejemplo n.º 10
0
 public Captcha(int pattern, int leftOperand, int operatorValue, int rightOperand)
 {
     this.leftOperand = leftOperand;
     this.rightOperand = rightOperand;
     this.operatorValue = operatorValue;
     this.pattern = (Pattern)pattern;
 }
        /// <summary>
        /// Create a new <seealso cref="PatternKeywordMarkerFilter"/>, that marks the current
        /// token as a keyword if the tokens term buffer matches the provided
        /// <seealso cref="Pattern"/> via the <seealso cref="KeywordAttribute"/>.
        /// </summary>
        /// <param name="in">
        ///          TokenStream to filter </param>
        /// <param name="pattern">
        ///          the pattern to apply to the incoming term buffer
        ///  </param>
        public PatternKeywordMarkerFilter(TokenStream @in, Pattern pattern)
            : base(@in)
        {
            termAtt = AddAttribute<ICharTermAttribute>();

            this.matcher = pattern.matcher("");
        }
Ejemplo n.º 12
0
        public static Pattern ParseMatcher(string feature, bool applyToMembers)
        {
            Match m = Parser.Match(feature);
            if (!m.Success)
            {
                DLog.Warning(DContext.CompilerStart, "pattern parsing error :" + feature);
                return null;
            }

            Pattern match = new Pattern();
            if (m.Groups[1].Success) match.TypeMatcher = m.Groups[1].Value;
            if (m.Groups[2].Success) match.TypeInheritanceKeyword = m.Groups[2].Value;
            if (m.Groups[3].Success) match.TypeInheritanceName = m.Groups[3].Value;
            if (m.Groups[4].Success) match.MemberMatcher = m.Groups[4].Value;
            if (m.Groups[5].Success) match.MembersPublicOnly = true;
            if (m.Groups[6].Success) match.Attributes.Add(m.Groups[6].Value);
            if (m.Groups[7].Success)
                foreach (Capture cap in m.Groups[7].Captures)
                    match.Attributes.Add(cap.Value);

            match.ApplyToMembers = applyToMembers;

            if (match.TypeMatcher == null && match.MemberMatcher == null)
            {
                DLog.Warning(DContext.CompilerStart, "either type or member matcher should be specified: " + feature);
                return match;
            }
            return match;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Customize this child
        /// </summary>
        public HexagonTess()
        {
            InitializeComponent();

            double xSmallSegment = 10d;
            double xLargeSegment = 20d;
            double ySegment = Math.Cos(Math.PI / 6) * 20d;
            double height = ySegment * 2;
            double width = 40d;

            addStartZone(new Point((int)xSmallSegment, 0), new Point((int)(xSmallSegment + xLargeSegment), 0));
            setShapeHeight(height);

            Pattern pat = new Pattern(60d, height, 0d);
            List<DoublePoint> shape1 = new List<DoublePoint>();
            List<DoublePoint> shape2 = new List<DoublePoint>();

            shape1.Add(new DoublePoint(xSmallSegment + xLargeSegment, 0));
            shape1.Add(new DoublePoint(xSmallSegment, 0));
            shape1.Add(new DoublePoint(0, ySegment));
            shape1.Add(new DoublePoint(xSmallSegment, height));
            shape1.Add(new DoublePoint(xSmallSegment + xLargeSegment, height));
            shape1.Add(new DoublePoint(width, ySegment));

            shape2.Add(new DoublePoint(xLargeSegment + xLargeSegment + xSmallSegment + xSmallSegment, ySegment));
            shape2.Add(new DoublePoint(xLargeSegment + xSmallSegment + xSmallSegment, ySegment));
            shape2.Add(new DoublePoint(xLargeSegment + xSmallSegment + 0, ySegment + ySegment));
            shape2.Add(new DoublePoint(xLargeSegment + xSmallSegment + xSmallSegment, ySegment + height));
            shape2.Add(new DoublePoint(xLargeSegment + xSmallSegment + xSmallSegment + xLargeSegment, ySegment + height));
            shape2.Add(new DoublePoint(xLargeSegment + xSmallSegment + width, ySegment + ySegment));

            pat.addPattern(shape1);
            pat.addPattern(shape2);
            setPattern(pat);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Customize this child
        /// </summary>
        public RectTess(double ratio)
        {
            InitializeComponent();

            double patBase = 30;
            // ratioOver1 is used to scale down the rectangle
            double ratioOver1 = ratio - 1;
            if (ratioOver1 > 0)
            {
                // If the ratioOver1 is over 1, the scale down will be much to small, so we will make 1 the max.
                if (ratioOver1 > 1d)
                    ratioOver1 = 1d;
                patBase /= ratioOver1 + 1;
            }
            double heightRatio = ratio;
            double patHeight = patBase * heightRatio;
            double patWidth = patBase;
            addStartZone(new Point(0, 0), new Point((int)patWidth, 0));
            setShapeHeight(patHeight);

            Pattern pat = new Pattern(patWidth, patHeight, 0d);
            List<DoublePoint> tri1 = new List<DoublePoint>();

            tri1.Add(new DoublePoint(0, 0));
            tri1.Add(new DoublePoint(0, patHeight));
            tri1.Add(new DoublePoint(patWidth, patHeight));
            tri1.Add(new DoublePoint(patWidth, 0));

            pat.addPattern(tri1);
            setPattern(pat);
        }
        public SynthesisMetathesisRuleSpec(SpanFactory<ShapeNode> spanFactory, Pattern<Word, ShapeNode> pattern, string leftGroupName, string rightGroupName)
        {
            _spanFactory = spanFactory;
            _leftGroupName = leftGroupName;
            _rightGroupName = rightGroupName;

            _pattern = new Pattern<Word, ShapeNode>();
            foreach (PatternNode<Word, ShapeNode> node in pattern.Children)
            {
                var group = node as Group<Word, ShapeNode>;
                if (group != null)
                {
                    var newGroup = new Group<Word, ShapeNode>(group.Name);
                    foreach (Constraint<Word, ShapeNode> constraint in group.Children.Cast<Constraint<Word, ShapeNode>>())
                    {
                        Constraint<Word, ShapeNode> newConstraint = constraint.DeepClone();
                        newConstraint.FeatureStruct.AddValue(HCFeatureSystem.Modified, HCFeatureSystem.Clean);
                        newGroup.Children.Add(newConstraint);
                    }
                    _pattern.Children.Add(newGroup);
                }
                else
                {
                    _pattern.Children.Add(node.DeepClone());
                }
            }
            _pattern.Freeze();
        }
Ejemplo n.º 16
0
 public static Pattern TwoColumns()
 {
     var pattern = new Pattern();
     pattern.WholeColumns.Add(-1);
     pattern.WholeColumns.Add(-2);
     return pattern;
 }
        public FeatureAnalysisRewriteRuleSpec(SpanFactory<ShapeNode> spanFactory, MatcherSettings<ShapeNode> matcherSettings, Pattern<Word, ShapeNode> lhs, RewriteSubrule subrule)
            : base(false)
        {
            var rhsAntiFSs = new List<FeatureStruct>();
            foreach (Constraint<Word, ShapeNode> constraint in subrule.Rhs.Children.OfType<Constraint<Word, ShapeNode>>().Where(c => c.Type() == HCFeatureSystem.Segment))
                rhsAntiFSs.Add(constraint.FeatureStruct.AntiFeatureStruct());

            Pattern.Acceptable = match => IsUnapplicationNonvacuous(match, rhsAntiFSs);

            _analysisRhs = new Pattern<Word, ShapeNode>();
            int i = 0;
            foreach (Tuple<PatternNode<Word, ShapeNode>, PatternNode<Word, ShapeNode>> tuple in lhs.Children.Zip(subrule.Rhs.Children))
            {
                var lhsConstraint = (Constraint<Word, ShapeNode>) tuple.Item1;
                var rhsConstraint = (Constraint<Word, ShapeNode>) tuple.Item2;

                if (lhsConstraint.Type() == HCFeatureSystem.Segment && rhsConstraint.Type() == HCFeatureSystem.Segment)
                {
                    var targetConstraint = lhsConstraint.DeepClone();
                    targetConstraint.FeatureStruct.PriorityUnion(rhsConstraint.FeatureStruct);
                    targetConstraint.FeatureStruct.AddValue(HCFeatureSystem.Modified, HCFeatureSystem.Clean);
                    Pattern.Children.Add(new Group<Word, ShapeNode>("target" + i) {Children = {targetConstraint}});

                    FeatureStruct fs = rhsConstraint.FeatureStruct.AntiFeatureStruct();
                    fs.Subtract(lhsConstraint.FeatureStruct.AntiFeatureStruct());
                    fs.AddValue(HCFeatureSystem.Type, HCFeatureSystem.Segment);
                    _analysisRhs.Children.Add(new Constraint<Word, ShapeNode>(fs));

                    i++;
                }
            }
            Pattern.Freeze();

            SubruleSpecs.Add(new AnalysisRewriteSubruleSpec(spanFactory, matcherSettings, subrule, Unapply));
        }
Ejemplo n.º 18
0
        public SynthesisRewriteRuleSpec(SpanFactory<ShapeNode> spanFactory, MatcherSettings<ShapeNode> matcherSettings, bool isIterative, Pattern<Word, ShapeNode> lhs,
			IEnumerable<RewriteSubrule> subrules)
            : base(lhs.IsEmpty)
        {
            Pattern.Acceptable = match => CheckTarget(match, lhs);

            if (lhs.IsEmpty)
            {
                Pattern.Children.Add(new Constraint<Word, ShapeNode>(FeatureStruct.New().Symbol(HCFeatureSystem.Segment, HCFeatureSystem.Anchor).Value));
            }
            else
            {
                foreach (Constraint<Word, ShapeNode> constraint in lhs.Children.Cast<Constraint<Word, ShapeNode>>())
                {
                    var newConstraint = constraint.DeepClone();
                    if (isIterative)
                        newConstraint.FeatureStruct.AddValue(HCFeatureSystem.Modified, HCFeatureSystem.Clean);
                    Pattern.Children.Add(newConstraint);
                }
            }
            Pattern.Freeze();

            int i = 0;
            foreach (RewriteSubrule subrule in subrules)
            {
                if (lhs.Children.Count == subrule.Rhs.Children.Count)
                    SubruleSpecs.Add(new FeatureSynthesisRewriteSubruleSpec(spanFactory, matcherSettings, isIterative, subrule, i));
                else if (lhs.Children.Count > subrule.Rhs.Children.Count)
                    SubruleSpecs.Add(new NarrowSynthesisRewriteSubruleSpec(spanFactory, matcherSettings, isIterative, lhs.Children.Count, subrule, i));
                else if (lhs.Children.Count == 0)
                    SubruleSpecs.Add(new EpenthesisSynthesisRewriteSubruleSpec(spanFactory, matcherSettings, isIterative, subrule, i));
                i++;
            }
        }
Ejemplo n.º 19
0
        public static void Main(string[] args)
        {
            string inputname = args[0];
            string outputname = args[1];

            string[] lines = File.ReadAllLines(inputname);

            int ncases = int.Parse(lines[0]);
            int nline = 0;
            IList<string> results = new List<string>();

            for (int k = 0; k < ncases; k++)
            {
                Console.WriteLine(string.Format("Solving Case #{0}", k + 1));
                nline++;
                string[] numbers = lines[nline].Split(' ');
                int height = int.Parse(numbers[0]);
                int width = int.Parse(numbers[1]);
                Pattern pattern = new Pattern(width, height);

                for (int j = 0; j < height; j++)
                {
                    nline++;
                    pattern.SetRow(j, lines[nline]);
                    Console.WriteLine(lines[nline]);
                }

                results.Add(string.Format("Case #{0}: {1}", k+1, pattern.HasSolution() ? "YES" : "NO"));
            }

            File.WriteAllLines(outputname, results.ToArray());
        }
Ejemplo n.º 20
0
    public void Init(string s)
    {
        animation = GetComponent<VillagerAnimation>();
		animation.Init (s);

        skinMaterial = GetComponentInChildren<MeshRenderer>().material;
        origColor = skinMaterial.color;

        // music stuff
        musicToggle = GetComponent<ToggleSuspend>();
        musicPattern = GetComponent<Pattern>();
        SetMusicPattern();
        musicSample = GetComponent<Sampler>();
        SetMusicSample();

		keyboardPosition = transform.localPosition;

        textMesh = GetComponentInChildren<TextMesh>();

        letter = s;
        textMesh.text = s;

		currentState = State.Idle;
		timeSinceLastDanced = Time.time;
    }
Ejemplo n.º 21
0
		private void VisitMethodCall(MethodCallExpression expression)
		{
			VisitExpression(expression.Object);
			string methodName = expression.Method.Name;
			object objToInvokeUpon = returnValueFromLastExpressionVisit;

			MethodInfo methodInfo = objToInvokeUpon.GetType().GetMethod(methodName,
			                                                            BindingFlags.Public | BindingFlags.Instance);
			int paramCount = methodInfo.GetParameters().Count();
			Array paramArray = Array.CreateInstance(typeof (Object), paramCount);

			for (int arrLocation = 0; arrLocation < expression.Arguments.Count; arrLocation++)
			{
				Expression argument = expression.Arguments[arrLocation];
				VisitExpression(argument);
				if (argument is ConstantExpression)
				{
					object argValue = ((ConstantExpression) argument).Value;
					paramArray.SetValue(argValue, arrLocation);
				}
				else
				{
					object argValue = returnValueFromLastExpressionVisit;
					paramArray.SetValue(argValue, arrLocation);
					Console.WriteLine();
				}
			}
			var array = (object[]) paramArray;
			returnValueFromLastExpressionVisit = methodInfo.Invoke(objToInvokeUpon, array);
			if (returnValueFromLastExpressionVisit is Pattern)
			{
				m_pattern = (Pattern) returnValueFromLastExpressionVisit;
			}
		}
Ejemplo n.º 22
0
 public static void AddPatternString(string Text,Row Row,Pattern Pattern,TextStyle Style,Segment Segment,bool HasError)
 {
     Word x= Row.Add (Text);
     x.Style = Style;
     x.Pattern = Pattern;
     x.HasError =HasError;
     x.Segment =Segment;
 }
Ejemplo n.º 23
0
 public override void GenerateAnalysisLhs(Pattern<Word, ShapeNode> analysisLhs, IDictionary<string, Pattern<Word, ShapeNode>> partLookup, IDictionary<string, int> capturedParts)
 {
     foreach (ShapeNode node in _segments.Shape)
     {
         if (node.Annotation.Type() != HCFeatureSystem.Boundary)
             analysisLhs.Children.Add(new Constraint<Word, ShapeNode>(node.Annotation.FeatureStruct));
     }
 }
Ejemplo n.º 24
0
 public override void GenerateAnalysisLhs(Pattern<Word, ShapeNode> analysisLhs, IDictionary<string, Pattern<Word, ShapeNode>> partLookup, IDictionary<string, int> capturedParts)
 {
     Pattern<Word, ShapeNode> pattern = partLookup[PartName];
     int count = capturedParts.GetValue(PartName, () => 0);
     string groupName = AnalysisMorphologicalTransform.GetGroupName(PartName, count);
     analysisLhs.Children.Add(new Group<Word, ShapeNode>(groupName, pattern.Children.DeepCloneExceptBoundaries()));
     capturedParts[PartName]++;
 }
Ejemplo n.º 25
0
        //public static char[] Parse(string text,string separators)
        //{
        //    //string Result="";
        //    System.Text.StringBuilder Result=new System.Text.StringBuilder ();
        //    text= " " + text +" ";

        //    char c;

        //    for(int i = 0; i <text.Length;i++)
        //    {
        //        c = text[i];
        //        if (separators.IndexOf (c)>=0 )
        //            Result.Append (' ');
        //        else
        //            Result.Append ('.');
        //    }

        //    return Result.ToString().ToCharArray ();
        //}



        public static void AddPatternString(string text, Row row, Pattern pattern, TextStyle style, Segment segment, bool hasError)
        {
            Word x = row.Add(text);
            x.Style = style;
            x.Pattern = pattern;
            x.HasError = hasError;
            x.Segment = segment;
        }
Ejemplo n.º 26
0
        public VimMatch(SyntaxContext context, string groupName, Pattern pattern)
            : base(context, groupName)
        {
            ArgumentValidator.ThrowIfNull(pattern, "pattern");
            ArgumentValidator.ThrowIfNullOrEmpty(groupName, "groupName");

            this.m_pattern = pattern;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Customize this child
        /// </summary>
        public KiteTess()
        {
            InitializeComponent();
            double heightOnSide = Math.Sin(Math.PI / 3d) * 30d;
            double segmentHeight = Math.Tan(Math.PI / 6d) * 30d;
            double triH = Math.Sin(Math.PI / 6d) * 30d;
            double height = Math.Sqrt(900 + (segmentHeight*segmentHeight));
            double totalHeight = height + segmentHeight;
            double xFromCenter = Math.Cos(Math.PI / 3d) * 30d;
            Pattern pat = new Pattern(60, totalHeight, 30);
            List<DoublePoint> tri1 = new List<DoublePoint>();
            List<DoublePoint> tri2 = new List<DoublePoint>();
            List<DoublePoint> tri3 = new List<DoublePoint>();
            List<DoublePoint> tri4 = new List<DoublePoint>();
            List<DoublePoint> tri5 = new List<DoublePoint>();
            List<DoublePoint> tri6 = new List<DoublePoint>();
            addStartZone(new Point(30, 0), new Point(60, 0));
            addReflectedStartZone(new Point(0, 0), new Point(30, 0));
            setShapeHeight(heightOnSide);

            tri1.Add(new DoublePoint(30 - xFromCenter, heightOnSide));
            tri1.Add(new DoublePoint(0, segmentHeight));
            tri1.Add(new DoublePoint(0, 0));
            tri1.Add(new DoublePoint(30, 0));

            tri2.Add(new DoublePoint(30 - xFromCenter, heightOnSide));
            tri2.Add(new DoublePoint(30, height));
            tri2.Add(new DoublePoint(30 + triH, heightOnSide));
            tri2.Add(new DoublePoint(30, 0));

            tri3.Add(new DoublePoint(60, 0));
            tri3.Add(new DoublePoint(60, segmentHeight));
            tri3.Add(new DoublePoint(30 + triH, heightOnSide));
            tri3.Add(new DoublePoint(30, 0));

            tri4.Add(new DoublePoint(60 - xFromCenter, totalHeight - heightOnSide));
            tri4.Add(new DoublePoint(30, totalHeight - segmentHeight));
            tri4.Add(new DoublePoint(30, totalHeight));
            tri4.Add(new DoublePoint(60, totalHeight));

            tri5.Add(new DoublePoint(60 - xFromCenter, totalHeight - heightOnSide));
            tri5.Add(new DoublePoint(60, totalHeight - height));
            tri5.Add(new DoublePoint(60 + triH, totalHeight - heightOnSide));
            tri5.Add(new DoublePoint(60, totalHeight));

            tri6.Add(new DoublePoint(90, totalHeight));
            tri6.Add(new DoublePoint(90, totalHeight - segmentHeight));
            tri6.Add(new DoublePoint(60 + triH, totalHeight - heightOnSide));
            tri6.Add(new DoublePoint(60, totalHeight));

            pat.addPattern(tri1);
            pat.addPattern(tri2);
            pat.addPattern(tri3);
            pat.addPattern(tri4);
            pat.addPattern(tri5);
            pat.addPattern(tri6);
            setPattern(pat);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Customize this child
        /// </summary>
        public RhombusTess()
        {
            InitializeComponent();

            double smallSegment = Math.Cos(Math.PI / 3d) * 30d;
            double height = Math.Sin(Math.PI / 3d) * 30d;
            double lengthLong = Math.Cos(Math.PI / 6d) * 60d;
            double lengthShort = Math.Sin(Math.PI / 6d) * 60d;
            addStartZone(new Point((int)smallSegment + 30, 0), new Point((int)smallSegment + 60, 0));
            addReflectedStartZone(new Point((int)smallSegment, 0), new Point((int)smallSegment + 30, 0));
            setShapeHeight(height);

            Pattern pat = new Pattern(60d + lengthShort, lengthLong, 0d);
            List<DoublePoint> shape1 = new List<DoublePoint>();
            List<DoublePoint> shape2 = new List<DoublePoint>();
            List<DoublePoint> shape3 = new List<DoublePoint>();
            List<DoublePoint> shape4 = new List<DoublePoint>();
            List<DoublePoint> shape5 = new List<DoublePoint>();
            List<DoublePoint> shape6 = new List<DoublePoint>();

            shape1.Add(new DoublePoint(smallSegment, 0));
            shape1.Add(new DoublePoint(0, height));
            shape1.Add(new DoublePoint(30, height));
            shape1.Add(new DoublePoint(30 + smallSegment, 0));

            shape2.Add(new DoublePoint(0, height));
            shape2.Add(new DoublePoint(smallSegment, lengthLong));
            shape2.Add(new DoublePoint(30 + smallSegment, lengthLong));
            shape2.Add(new DoublePoint(30, height));

            shape3.Add(new DoublePoint(30 + smallSegment, 0));
            shape3.Add(new DoublePoint(30, height));
            shape3.Add(new DoublePoint(30 + smallSegment, lengthLong));
            shape3.Add(new DoublePoint(30 + lengthShort, height));

            shape4.Add(new DoublePoint(30 + smallSegment, 0));
            shape4.Add(new DoublePoint(30 + lengthShort, height));
            shape4.Add(new DoublePoint(60 + lengthShort, height));
            shape4.Add(new DoublePoint(60 + smallSegment, 0));

            shape5.Add(new DoublePoint(30 + lengthShort, height));
            shape5.Add(new DoublePoint(30 + smallSegment, lengthLong));
            shape5.Add(new DoublePoint(60 + smallSegment, lengthLong));
            shape5.Add(new DoublePoint(60 + lengthShort, height));

            shape6.Add(new DoublePoint(60 + lengthShort, height));
            shape6.Add(new DoublePoint(60 + smallSegment, lengthLong));
            shape6.Add(new DoublePoint(60 + lengthShort, lengthLong * 1.5));
            shape6.Add(new DoublePoint(60 + smallSegment + lengthShort, lengthLong));

            pat.addPattern(shape1);
            pat.addPattern(shape2);
            pat.addPattern(shape3);
            pat.addPattern(shape4);
            pat.addPattern(shape5);
            pat.addPattern(shape6);
            setPattern(pat);
        }
Ejemplo n.º 29
0
 public static Pattern Square()
 {
     var pattern = new Pattern();
     pattern.Shape.Add(new Cordinate(0, 0));
     pattern.Shape.Add(new Cordinate(1, 0));
     pattern.Shape.Add(new Cordinate(0, -1));
     pattern.Shape.Add(new Cordinate(1, -1));
     return pattern;
 }
Ejemplo n.º 30
0
 public void Clone_Should_Clone_Rotations_And_Color_Them()
 {
     var pattern = new Pattern();
     pattern.Rotations = new ITetrisCup[]
     {
         A.Fake<ITetrisCup>(), A.Fake<ITetrisCup>(),
         A.Fake<ITetrisCup>(), A.Fake<ITetrisCup>()
     };
 }
Ejemplo n.º 31
0
 public EditDotMetro(Pattern pattern) : this(pattern, null)
 {
 }
Ejemplo n.º 32
0
 public static Statement ToStatement(this Pattern pattern)
 {
     return(pattern);
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Generates a hold note alongside normal notes.
        /// </summary>
        /// <param name="startTime">The start time of notes.</param>
        /// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
        private Pattern generateHoldAndNormalNotes(double startTime)
        {
            // - - - -
            // ■ x x -
            // ■ - x x
            // ■ x - x
            // ■ - x x

            var pattern = new Pattern();

            int holdColumn = GetColumn((HitObject as IHasXPosition)?.X ?? 0, true);

            if (convertType.HasFlag(PatternType.ForceNotStack) && PreviousPattern.ColumnWithObjects < TotalColumns)
            {
                holdColumn = FindAvailableColumn(holdColumn, PreviousPattern);
            }

            // Create the hold note
            addToPattern(pattern, holdColumn, startTime, EndTime);

            int nextColumn = GetRandomColumn();
            int noteCount;

            if (ConversionDifficulty > 6.5)
            {
                noteCount = GetRandomNoteCount(0.63, 0);
            }
            else if (ConversionDifficulty > 4)
            {
                noteCount = GetRandomNoteCount(TotalColumns < 6 ? 0.12 : 0.45, 0);
            }
            else if (ConversionDifficulty > 2.5)
            {
                noteCount = GetRandomNoteCount(TotalColumns < 6 ? 0 : 0.24, 0);
            }
            else
            {
                noteCount = 0;
            }
            noteCount = Math.Min(TotalColumns - 1, noteCount);

            bool ignoreHead = !sampleInfoListAt(startTime).Any(s => s.Name == HitSampleInfo.HIT_WHISTLE || s.Name == HitSampleInfo.HIT_FINISH || s.Name == HitSampleInfo.HIT_CLAP);

            var rowPattern = new Pattern();

            for (int i = 0; i <= spanCount; i++)
            {
                if (!(ignoreHead && startTime == HitObject.StartTime))
                {
                    for (int j = 0; j < noteCount; j++)
                    {
                        nextColumn = FindAvailableColumn(nextColumn, validation: c => c != holdColumn, patterns: rowPattern);
                        addToPattern(rowPattern, nextColumn, startTime, startTime);
                    }
                }

                pattern.Add(rowPattern);
                rowPattern.Clear();

                startTime += SegmentDuration;
            }

            return(pattern);
        }
Ejemplo n.º 34
0
 private string ProcessPatternMatch(Pattern pattern, Match match)
 {
     return(String.Format(ElementFormat, pattern.Name, match.Value));
 }
Ejemplo n.º 35
0
        protected internal virtual Tree FindSyntacticHead(Mention m, Tree root, IList <CoreLabel> tokens)
        {
            // mention ends with 's
            int endIdx = m.endIndex;

            if (m.originalSpan.Count > 0)
            {
                string lastWord = m.originalSpan[m.originalSpan.Count - 1].Get(typeof(CoreAnnotations.TextAnnotation));
                if ((lastWord.Equals("'s") || lastWord.Equals("'")) && m.originalSpan.Count != 1)
                {
                    endIdx--;
                }
            }
            Tree exactMatch = FindTreeWithSpan(root, m.startIndex, endIdx);

            //
            // found an exact match
            //
            if (exactMatch != null)
            {
                return(SafeHead(exactMatch, endIdx));
            }
            // no exact match found
            // in this case, we parse the actual extent of the mention, embedded in a sentence
            // context, so as to make the parser work better :-)
            if (allowReparsing)
            {
                int approximateness            = 0;
                IList <CoreLabel> extentTokens = new List <CoreLabel>();
                extentTokens.Add(InitCoreLabel("It"));
                extentTokens.Add(InitCoreLabel("was"));
                int AddedWords = 2;
                for (int i = m.startIndex; i < endIdx; i++)
                {
                    // Add everything except separated dashes! The separated dashes mess with the parser too badly.
                    CoreLabel label = tokens[i];
                    if (!"-".Equals(label.Word()))
                    {
                        // necessary to copy tokens in case the parser does things like
                        // put new indices on the tokens
                        extentTokens.Add((CoreLabel)label.LabelFactory().NewLabel(label));
                    }
                    else
                    {
                        approximateness++;
                    }
                }
                extentTokens.Add(InitCoreLabel("."));
                // constrain the parse to the part we're interested in.
                // Starting from ADDED_WORDS comes from skipping "It was".
                // -1 to exclude the period.
                // We now let it be any kind of nominal constituent, since there
                // are VP and S ones
                ParserConstraint         constraint  = new ParserConstraint(AddedWords, extentTokens.Count - 1, Pattern.Compile(".*"));
                IList <ParserConstraint> constraints = Java.Util.Collections.SingletonList(constraint);
                Tree tree = Parse(extentTokens, constraints);
                ConvertToCoreLabels(tree);
                // now unnecessary, as parser uses CoreLabels?
                tree.IndexSpans(m.startIndex - AddedWords);
                // remember it has ADDED_WORDS extra words at the beginning
                Tree subtree = FindPartialSpan(tree, m.startIndex);
                // There was a possible problem that with a crazy parse, extentHead could be one of the added words, not a real word!
                // Now we make sure in findPartialSpan that it can't be before the real start, and in safeHead, we disallow something
                // passed the right end (that is, just that final period).
                Tree extentHead = SafeHead(subtree, endIdx);
                System.Diagnostics.Debug.Assert((extentHead != null));
                // extentHead is a child in the local extent parse tree. we need to find the corresponding node in the main tree
                // Because we deleted dashes, it's index will be >= the index in the extent parse tree
                CoreLabel l        = (CoreLabel)extentHead.Label();
                Tree      realHead = FunkyFindLeafWithApproximateSpan(root, l.Value(), l.Get(typeof(CoreAnnotations.BeginIndexAnnotation)), approximateness);
                System.Diagnostics.Debug.Assert((realHead != null));
                return(realHead);
            }
            // If reparsing wasn't allowed, try to find a span in the tree
            // which happens to have the head
            Tree wordMatch = FindTreeWithSmallestSpan(root, m.startIndex, endIdx);

            if (wordMatch != null)
            {
                Tree head = SafeHead(wordMatch, endIdx);
                if (head != null)
                {
                    int index = ((CoreLabel)head.Label()).Get(typeof(CoreAnnotations.IndexAnnotation)) - 1;
                    if (index >= m.startIndex && index < endIdx)
                    {
                        return(head);
                    }
                }
            }
            // If that didn't work, guess that it's the last word
            int lastNounIdx = endIdx - 1;

            for (int i_1 = m.startIndex; i_1 < m.endIndex; i_1++)
            {
                if (tokens[i_1].Tag().StartsWith("N"))
                {
                    lastNounIdx = i_1;
                }
                else
                {
                    if (tokens[i_1].Tag().StartsWith("W"))
                    {
                        break;
                    }
                }
            }
            IList <Tree> leaves  = root.GetLeaves();
            Tree         endLeaf = leaves[lastNounIdx];

            return(endLeaf);
        }
Ejemplo n.º 36
0
 public SpecificBeatmapPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, IBeatmap originalBeatmap)
     : base(random, hitObject, beatmap, previousPattern, originalBeatmap)
 {
 }
Ejemplo n.º 37
0
        public Pattern EncodePattern(string input)
        {
            var pattern = new Pattern();

            for (var index = 0; index < input.Length; index++)
            {
                var maxLength = input.Length - index;
                //Maximal munch
                for (var len = maxLength; len > 0; len--)
                {
                    var bunch = input.Substring(index, len);

                    if (Lingon.DefaultSet.FirstOrDefault(ling => ling.Symbol == bunch) != null)
                    {
                        pattern.Add(Lingon.DefaultSet.FirstOrDefault(ling => ling.Symbol == bunch));
                        index += len - 1;
                        break;
                    }
                    else if (bunch.StartsWith("[") && bunch.EndsWith("]") && len > 2)
                    {
                        pattern.Add(new NonceSet(EncodePattern(bunch.Substring(1, bunch.Length - 2))));
                        index += len - 1;
                        break;
                    }
                    else if (bunch.Length > 1 && bunch.Substring(1).StartsWith("[") && bunch.EndsWith("]"))
                    {
                        var symbol = bunch.Substring(0, 1);
                        var split  = bunch.Substring(1).Split("]").Where(ft => ft != "").ToList();

                        if (split.Any(segment => !segment.StartsWith("[")))
                        {
                            continue;
                        }

                        var features    = split.Select(ft => ft.Replace("[", ""));
                        var hasFeatures = new List <Feature>();
                        var notFeatures = new List <Feature>();

                        if (Lingons.ContainsKey(symbol))
                        {
                            hasFeatures.AddRange(Lingons[symbol].Features);
                        }
                        else if (Categories.ContainsKey(symbol))
                        {
                            hasFeatures.AddRange(Categories[symbol].HasFeatures);
                            notFeatures.AddRange(Categories[symbol].NotFeatures);
                        }


                        foreach (var feature in features)
                        {
                            var add  = !feature.StartsWith("-");
                            var name = feature.Substring(1);
                            (add ? hasFeatures : notFeatures).Add(Feature.AllFeatures.First(ft => String.Equals(ft.Name, name, StringComparison.CurrentCultureIgnoreCase)));
                        }

                        pattern.Add(new Category(hasFeatures, notFeatures));
                        index += len - 1; //Move to end of bunch
                        break;
                    }
                    else if (Lingons.ContainsKey(bunch))
                    {
                        pattern.Add(Lingons[bunch]);
                        index += len - 1; //Move to end of bunch
                        break;
                    }
                    else if (Categories.ContainsKey(bunch))
                    {
                        pattern.Add(Categories[bunch]);
                        index += len - 1; //Move to end of bunch
                        break;
                    }
                    else if (len == 1)
                    {
                        pattern.Add(Lingon.Unknown);
                        break;
                    }
                }
            }

            return(pattern);
        }
 public AnalysisAffixProcessAllomorphRuleSpec(AffixProcessAllomorph allomorph)
     : base(allomorph.Lhs, allomorph.Rhs)
 {
     _allomorph = allomorph;
     Pattern.Freeze();
 }
Ejemplo n.º 39
0
 public static string GetPatternPath(Pattern pattern)
 {
     return(GetRootPath() + "/Patterns/" + pattern.ImageUri);
 }
Ejemplo n.º 40
0
        static void StartSearch(Func <Pattern, bool, IEnumerable <ScanEntry> > scanner, Pattern pattern, Player player)
        {
            IEnumerable <ScanEntry> result = Enumerable.Empty <ScanEntry>();

            for (var i = 0; i < _options.Fuzzy.Length; i++)
            {
                var fuzzy = _options.Fuzzy[i];

                var fuzzyRanks = fuzzy.Contains('r');
                var fuzzyOrder = fuzzy.Contains('o');
                Console.WriteLine(new string('-', 60));
                Console.WriteLine(string.Format(Translate.Get("fuzzy.fmt"), FuzzyToString(fuzzy)));

                pattern = StringToPattern(pattern.Str, player, fuzzyRanks, silent: true);
                Console.WriteLine(PatternToString(pattern));

                var r   = scanner(pattern, fuzzyOrder);
                var msg = r.Count() == 0 ? "not" : r.Count().ToString();
                msg = msg + " found.";

                var lastp = (i == (_options.Fuzzy.Length - 1));

                if (!r.Any() && !lastp)
                {
                    msg = msg + " retry...";
                }

                Console.WriteLine(msg);

                if (r.Any())
                {
                    OutputSearchResults(r);
                    result = r;
                    break;
                }
            }

            while (true)
            {
                Console.WriteLine();
                Console.WriteLine(Translate.Get("prompt.after_normal_search"));
                var line = Prompt();

                if (string.IsNullOrEmpty(line))
                {
                    var target = result.OrderBy(x => Math.Abs(x.Index)).FirstOrDefault();

                    if (target == null)
                    {
                        Console.WriteLine(Translate.Get("no_target"));
                        continue;
                    }

                    var lastState = target.Data.Opening.LastState;
                    RareSearch(lastState, player);
                }
                else if (line.StartsWith("h"))
                {
                    ShowPatternHelp();
                }
                else if (line.StartsWith("q"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    var newPattern = StringToPattern(line, player, fuzzyRanks: false);

                    if (newPattern == null)
                    {
                        continue;
                    }

                    StartSearch(scanner, newPattern, player);
                }
            }
        }
Ejemplo n.º 41
0
 public void VisitPatternPlaceholder(AstNode placeholder, Pattern pattern)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 42
0
 public void Fill(Player player, Pattern pattern, int radius, int depth = -1)
 {
     EditSession.Fill((BlockCoordinates)player.KnownPosition, pattern, new AirBlocksMask(player.Level), radius, depth);
 }
Ejemplo n.º 43
0
        public PlotWorldGenerator()
        {
            RoadPattern = new Pattern();
            var gravel   = new Gravel();
            var stone    = new Stone();
            var andesite = new Stone()
            {
                StoneType = "andesite"
            };
            var dirt  = new Dirt();
            var grass = new Grass();

            RoadPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 20,
                Block  = gravel
            });
            RoadPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 10,
                Block  = dirt
            });
            RoadPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 10,
                Block  = andesite
            });
            RoadPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 20,
                Block  = stone
            });
            RoadPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 40,
                Block  = grass
            });
            RoadPattern.Order();

            PlotPattern = new Pattern();
            PlotPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 70,
                Block  = new Air()
            });
            PlotPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 27,
                Block  = new Tallgrass()
                {
                    TallGrassType = "tall"
                }
            });
            PlotPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 1,
                Block  = new YellowFlower()
            });
            PlotPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 1,
                Block  = new RedFlower()
            });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 1 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 2 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 3 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 4 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 5 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 6 });
            //PlotPattern.BlockList.Add(new Pattern.BlockDataEntry() { Weight = 5, Id = 38, Metadata = 7 });
            PlotPattern.BlockList.Add(new Pattern.BlockDataEntry()
            {
                Weight = 1,
                Block  = new RedFlower()
                {
                    FlowerType = "oxeye"
                }
            });
            PlotPattern.Order();
        }
Ejemplo n.º 44
0
 protected StraightPatternGenerator(HitObject hitObject, Sheetmusic sheetmusic, int availableColumns, Pattern previousPattern)
     : base(hitObject, sheetmusic, availableColumns, previousPattern)
 {
 }
Ejemplo n.º 45
0
 bool canConstruct(Pattern p)
 {
     return(inventory.GetInventoryValue(p.type) >= p.quantity);
 }
Ejemplo n.º 46
0
 public OrTypePattern(string variantName, Pattern innerValue)
 {
     VariantName = variantName;
     InnerValue  = innerValue;
 }
Ejemplo n.º 47
0
 public AutomationElement ElementAt(int row, int column)
 {
     return(Pattern.GetItem(row, column));
 }
Ejemplo n.º 48
0
 public UrlEncodeSegment(Pattern pattern)
 {
     _pattern = pattern;
 }
Ejemplo n.º 49
0
 static Pattern NewObj(Pattern p)
 {
     return(new MethodPattern(ILCode.Newobj, ".ctor", p));
 }
Ejemplo n.º 50
0
 public FeatureSynthesisRewriteSubruleSpec(SpanFactory <ShapeNode> spanFactory, MatcherSettings <ShapeNode> matcherSettings, bool isIterative,
                                           RewriteSubrule subrule, int index)
     : base(spanFactory, matcherSettings, isIterative, subrule, index)
 {
     _rhs = subrule.Rhs;
 }
Ejemplo n.º 51
0
        private Pattern generate()
        {
            if (TotalColumns == 1)
            {
                var pattern = new Pattern();
                addToPattern(pattern, 0, HitObject.StartTime, EndTime);
                return(pattern);
            }

            if (spanCount > 1)
            {
                if (SegmentDuration <= 90)
                {
                    return(generateRandomHoldNotes(HitObject.StartTime, 1));
                }

                if (SegmentDuration <= 120)
                {
                    convertType |= PatternType.ForceNotStack;
                    return(generateRandomNotes(HitObject.StartTime, spanCount + 1));
                }

                if (SegmentDuration <= 160)
                {
                    return(generateStair(HitObject.StartTime));
                }

                if (SegmentDuration <= 200 && ConversionDifficulty > 3)
                {
                    return(generateRandomMultipleNotes(HitObject.StartTime));
                }

                double duration = EndTime - HitObject.StartTime;
                if (duration >= 4000)
                {
                    return(generateNRandomNotes(HitObject.StartTime, 0.23, 0, 0));
                }

                if (SegmentDuration > 400 && spanCount < TotalColumns - 1 - RandomStart)
                {
                    return(generateTiledHoldNotes(HitObject.StartTime));
                }

                return(generateHoldAndNormalNotes(HitObject.StartTime));
            }

            if (SegmentDuration <= 110)
            {
                if (PreviousPattern.ColumnWithObjects < TotalColumns)
                {
                    convertType |= PatternType.ForceNotStack;
                }
                else
                {
                    convertType &= ~PatternType.ForceNotStack;
                }
                return(generateRandomNotes(HitObject.StartTime, SegmentDuration < 80 ? 1 : 2));
            }

            if (ConversionDifficulty > 6.5)
            {
                if (convertType.HasFlag(PatternType.LowProbability))
                {
                    return(generateNRandomNotes(HitObject.StartTime, 0.78, 0.3, 0));
                }

                return(generateNRandomNotes(HitObject.StartTime, 0.85, 0.36, 0.03));
            }

            if (ConversionDifficulty > 4)
            {
                if (convertType.HasFlag(PatternType.LowProbability))
                {
                    return(generateNRandomNotes(HitObject.StartTime, 0.43, 0.08, 0));
                }

                return(generateNRandomNotes(HitObject.StartTime, 0.56, 0.18, 0));
            }

            if (ConversionDifficulty > 2.5)
            {
                if (convertType.HasFlag(PatternType.LowProbability))
                {
                    return(generateNRandomNotes(HitObject.StartTime, 0.3, 0, 0));
                }

                return(generateNRandomNotes(HitObject.StartTime, 0.37, 0.08, 0));
            }

            if (convertType.HasFlag(PatternType.LowProbability))
            {
                return(generateNRandomNotes(HitObject.StartTime, 0.17, 0, 0));
            }

            return(generateNRandomNotes(HitObject.StartTime, 0.27, 0, 0));
        }
Ejemplo n.º 52
0
 public static Expression ToExpression(this Pattern pattern)
 {
     return(pattern);
 }
Ejemplo n.º 53
0
        public DistanceObjectPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, IBeatmap originalBeatmap)
            : base(random, hitObject, beatmap, previousPattern, originalBeatmap)
        {
            convertType = PatternType.None;
            if (!Beatmap.ControlPointInfo.EffectPointAt(hitObject.StartTime).KiaiMode)
            {
                convertType = PatternType.LowProbability;
            }

            var distanceData = hitObject as IHasDistance;
            var repeatsData  = hitObject as IHasRepeats;

            spanCount = repeatsData?.SpanCount() ?? 1;

            TimingControlPoint     timingPoint     = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime);
            DifficultyControlPoint difficultyPoint = beatmap.ControlPointInfo.DifficultyPointAt(hitObject.StartTime);

            // The true distance, accounting for any repeats
            double distance = (distanceData?.Distance ?? 0) * spanCount;
            // The velocity of the osu! hit object - calculated as the velocity of a slider
            double osuVelocity = osu_base_scoring_distance * beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier * difficultyPoint.SpeedMultiplier / timingPoint.BeatLength;
            // The duration of the osu! hit object
            double osuDuration = distance / osuVelocity;

            EndTime         = hitObject.StartTime + osuDuration;
            SegmentDuration = (EndTime - HitObject.StartTime) / spanCount;
        }
Ejemplo n.º 54
0
 public override int GetHashCode()
 {
     return(Pattern != null ? Pattern.GetHashCode() : 0);
 }
Ejemplo n.º 55
0
        public void ReadSongInfo()
        {
            if (filebytes.Length == 0)
            {
                return;
            }

            numchannels = filebytes[0];
            numpatterns = filebytes[1];
            number_of_patterns_in_one_loop = filebytes[2];

            restartPosition = filebytes[4];

            tempo = filebytes[5];
            bpm   = filebytes[6];

            clipvaluethingy = filebytes[8];
            numinstruments  = filebytes[9];
            unkValue1       = filebytes[10];
            unkValue2       = filebytes[11];
            unkValue3       = filebytes[12];
            unkOffset       = BitConverter.ToInt32(filebytes, 0x13);

            int pos = 0x28;

            patterns = new List <Pattern>();

            patternsInPlayingOrder = new List <Pattern>();

            for (int i = 0; i < number_of_patterns_in_one_loop; i++)
            {
                if (GetPatternWithIndex(patterns, filebytes[pos]) == null)
                {
                    Pattern newPattern = new Pattern();

                    newPattern.index = filebytes[pos];

                    patterns.Add(newPattern);

                    patternsInPlayingOrder.Add(newPattern);
                }
                else
                {
                    patternsInPlayingOrder.Add(GetPatternWithIndex(patterns, filebytes[pos]));
                }

                pos++;
            }

            while (pos % 4 != 0)
            {
                pos++;
            }


            //start of the actual pattern info


            foreach (Pattern p in patterns)
            {
                p.number_of_rows = BitConverter.ToInt32(filebytes, pos);
                pos += 4;

                for (int i = 0; i < p.number_of_rows; i++)
                {
                    p.rows.Add(GetRow(parentbinfile, BitConverter.ToInt32(filebytes, pos)));
                    p.patternSize += p.rows[p.rows.Count - 1].Length;

                    pos += 4;
                }
            }
        }
Ejemplo n.º 56
0
        public override bool PreAI()
        {
            if (timer++ > elapse)
            {
                timer = 0;
            }
            switch (pattern)
            {
            case Pattern.JustSpawned:
                if (JustSpawned())
                {
                    goto case Pattern.FadeIn;
                }
                break;

            case Pattern.FadeIn:
                pattern = Pattern.FadeIn;
                if (npc.alpha > 0)
                {
                    npc.alpha -= 5;
                    break;
                }
                else
                {
                    goto case Pattern.Idle;
                }

            case Pattern.FadeOut:
                pattern = Pattern.FadeOut;
                if (npc.alpha < 255)
                {
                    npc.alpha += 5;
                    break;
                }
                goto case Pattern.Teleport;

            case Pattern.Teleport:
                pattern = Pattern.Teleport;
                move    = ArchaeaNPC.FastMove(npc);
                if (move != Vector2.Zero)
                {
                    npc.position = move;
                    Teleport();
                    hasAttacked = false;
                    goto case Pattern.FadeIn;
                }
                break;

            case Pattern.Idle:
                pattern = Pattern.Idle;
                if (timer % elapse == 0 && Main.rand.Next(3) == 0)
                {
                    if (!hasAttacked)
                    {
                        hasAttacked = true;
                        goto case Pattern.Attack;
                    }
                    else
                    {
                        goto case Pattern.FadeOut;
                    }
                }
                return(false);

            case Pattern.Attack:
                pattern = Pattern.Attack;
                if (PreAttack())
                {
                    Attack();
                    attacks++;
                }
                if (attacks > maxAttacks)
                {
                    pattern = Pattern.Idle;
                    attacks = 0;
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 57
0
        public void Replace_With_New_XM(string filename)
        {
            byte[] newXMfilebytes = File.ReadAllBytes(filename);

            patterns = new List <Pattern>();
            patternsInPlayingOrder = new List <Pattern>();

            // read XM from file

            number_of_patterns_in_one_loop = BitConverter.ToUInt16(newXMfilebytes, 0x40);
            restartPosition = BitConverter.ToUInt16(newXMfilebytes, 0x42);
            numchannels     = BitConverter.ToUInt16(newXMfilebytes, 0x44);
            numpatterns     = BitConverter.ToUInt16(newXMfilebytes, 0x46);
            numinstruments  = BitConverter.ToUInt16(newXMfilebytes, 0x48);

            tempo = BitConverter.ToUInt16(newXMfilebytes, 0x4C);
            bpm   = BitConverter.ToUInt16(newXMfilebytes, 0x4E);

            int pos = 0x50;

            for (int i = 0; i < number_of_patterns_in_one_loop; i++)
            {
                if (GetPatternWithIndex(patterns, newXMfilebytes[pos]) == null)
                {
                    Pattern newPattern = new Pattern();

                    newPattern.index = newXMfilebytes[pos];

                    patterns.Add(newPattern);

                    patternsInPlayingOrder.Add(newPattern);
                }
                else
                {
                    patternsInPlayingOrder.Add(GetPatternWithIndex(patterns, newXMfilebytes[pos]));
                }
                pos++;
            }

            while (newXMfilebytes[pos] == 0x00)
            {
                pos++;
            }

            //start of pattern data

            for (int i = 0; i < numpatterns; i++)
            {
                pos += 5;

                patterns[i].number_of_rows = BitConverter.ToUInt16(newXMfilebytes, pos);
                pos += 2;
                patterns[i].patternSize = BitConverter.ToUInt16(newXMfilebytes, pos);
                pos += 2;

                patterns[i].rows = new List <byte[]>();

                for (int r = 0; r < patterns[i].number_of_rows; r++)        //add rows
                {
                    patterns[i].rows.Add(GetRegularXMRow(newXMfilebytes, pos));
                    pos += patterns[i].rows[patterns[i].rows.Count - 1].Length;
                }
            }
        }
Ejemplo n.º 58
0
 public static AstType ToType(this Pattern pattern)
 {
     return(pattern);
 }
Ejemplo n.º 59
0
 ComparePaths(Pattern, other.Pattern) &&
Ejemplo n.º 60
0
        public FunctionDeclaration(Document parent, ref string Input)
            : base(parent)
        {
            Pattern regExPattern =
                "^\\s*" +
                new Group("def",
                          new Group("type", Provider.type) +
                          "\\s+" +
                          new Group("identifier", Provider.identifier) +
                          "\\s*\\(" +
                          new Group("params",
                                    "\\s*" +
                                    Provider.type + "\\s*" + Provider.identifier +
                                    "\\s*(,\\s*" +
                                    Provider.type + "\\s*" + Provider.identifier +
                                    ")*") +
                          "?" +
                          "\\)\\s*") +
                new Group("terminus", "[;{]");

            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(regExPattern);
            System.Text.RegularExpressions.Match match = regEx.Match(Input);

            if (!match.Success)
            {
                throw new ParseException();
            }
            //if (match.Index != 0)
            //	throw new ParseException();
            Input = Input.Remove(0, match.Index + match.Length);           // Also removes all starting spaces etc...


            Type = ITypeSpecifier.Parse(this, match.Groups["type"].Value);
            if (Type == null)
            {
                throw new SyntaxException("Error parsing variable: Expected type, got \"" + match.Groups["type"].Value + "\".");
            }

            Identifier = match.Groups["identifier"].Value;
            if ((Identifier == null) || (Identifier == ""))
            {
                throw new SyntaxException("Error parsing variable: Expected identifier, got \"" + match.Groups["identifier"].Value + "\".");
            }

            string[] paramStrings            = match.Groups["params"].Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            List <VariableDeclaration> param = new List <VariableDeclaration>();

            for (int i = 0; i < paramStrings.Length; i++)
            {
                paramStrings[i] = paramStrings[i].Trim(new char[] { ' ', '\t', '\n', '\r' });
                try
                {
                    VariableDeclaration decl = new VariableDeclaration(this, ref paramStrings[i], false);
                    param.Add(decl);
                }
                catch (ParseException)
                {
                }
            }
            Parameters = param.ToArray();

            if (match.Groups["terminus"].Value == "{")             // Well, there's a body...
            {
                //TODO: Parse body of function...
                //Body = new ISyntaxNode[0];

                List <ISyntaxNode> bodyNodes = new List <ISyntaxNode>();

                System.Text.RegularExpressions.Regex endMatch = new System.Text.RegularExpressions.Regex("^\\s*}");
                while (!endMatch.IsMatch(Input))
                {
                    FunctionCall fcall = TryParse <FunctionCall>(this, ref Input);
                    if (fcall != null)
                    {
                        bodyNodes.Add(fcall);

                        // Search for following semikolon and remove it...
                        System.Text.RegularExpressions.Regex semikolon      = new System.Text.RegularExpressions.Regex("^\\s*;");
                        System.Text.RegularExpressions.Match semikolonMatch = semikolon.Match(Input);
                        if (!semikolonMatch.Success)
                        {
                            throw new SyntaxException("Syntax error: Missing semikolon after function call.");
                        }
                        Input = Input.Remove(0, semikolonMatch.Length);

                        continue;
                    }

                    throw new SyntaxException("Syntax error: Invalid token \"" + Input + "\"");
                }

                Body = bodyNodes.ToArray();

                // Finally remove remaining (closing) }
                int index = Input.IndexOf('}');
                Input = Input.Remove(0, index + 1);
            }
            else if (match.Groups["terminus"].Value == ";")             // No Body, only header declaration
            {
                Body = null;
            }
        }