Beispiel #1
0
 public void ClearClip()
 {
     _strategy = MoveStrategy.Standard;
     _physicalCursorLocation = _curr;
     _prev = new Point(_curr.X, _curr.Y);
     Win32.SetCursorPos(_curr.X, _curr.Y);
 }
Beispiel #2
0
 public GameState(GameState g)
 {
     Cube.ImportState(g.Cube.ExportState());
     Turn     = g.Turn;
     Player   = g.Player;
     Strategy = g.Strategy;
 }
Beispiel #3
0
        protected override bool OnDragEnd(Point dragStartPosition, Point dragEndPosition)
        {
            Mouse.OverrideCursor = (Cursor)null;
            bool flag = this.dragCancelled;

            this.ProvisionalContainer = (BaseFrameworkElement)null;
            if (this.dragContainer == null || this.dragCancelled)
            {
                this.PopSelf();
                return(true);
            }
            if (this.moveStrategy != null)
            {
                dragEndPosition = this.SnapPrimarySelectionBounds(dragStartPosition, dragEndPosition);
                BaseFrameworkElement layoutContainer = this.moveStrategy.LayoutContainer;
                this.moveStrategy.ContinueDrag(dragEndPosition, layoutContainer);
                if (!this.moveStrategy.EndDrag(true))
                {
                    this.CancelEditTransaction();
                    flag = true;
                }
                this.ToolBehaviorContext.SnappingEngine.Stop();
                this.moveStrategy = (MoveStrategy)null;
            }
            if (!flag)
            {
                this.ActiveSceneViewModel.ElementSelectionSet.SetSelection((ICollection <SceneElement>) this.selectedElements, this.primarySelection);
                if (this.HasMouseMovedAfterDown)
                {
                    this.CommitEditTransaction();
                }
            }
            this.PopSelf();
            return(true);
        }
Beispiel #4
0
 public void SetClip(int x, int y)
 {
     _strategy = MoveStrategy.Clipped;
     _physicalCursorLocation = new Point(x, y);
     _prev = _physicalCursorLocation;
     Win32.SetCursorPos(x, y);
 }
Beispiel #5
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="name"></param>
 public LowLevelMouseHook(string name)
 {
     _name = name;
     _hookID = IntPtr.Zero;
     _hookProc = HookCallback;
     _state = DoubleClickState.Empty;
     _strategy = MoveStrategy.Standard;
 }
Beispiel #6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="name"></param>
 public LowLevelMouseHook(string name)
 {
     _name     = name;
     _hookID   = IntPtr.Zero;
     _hookProc = HookCallback;
     _state    = DoubleClickState.Empty;
     _strategy = MoveStrategy.Standard;
 }
Beispiel #7
0
 private void CancelDrag()
 {
     if (this.moveStrategy != null)
     {
         this.moveStrategy.EndDrag(false);
         this.moveStrategy = (MoveStrategy)null;
     }
     this.ProvisionalContainer = (BaseFrameworkElement)null;
     this.ToolBehaviorContext.SnappingEngine.Stop();
     this.CancelEditTransaction();
     this.dragCancelled = true;
 }
 public IMoveStrategy GetMoveStrategy(MoveStrategy key)
 {
     switch (key)
     {
         case MoveStrategy.Run:
             return GetRunStrategy();
         case MoveStrategy.Walk:
             return GetWalkStrategy();
         case MoveStrategy.Crawl:
             return GetCrawlStrategy();
         default:
             throw new Exception("Unknown key: " + key);
     }
 }
    public override void init()
    {
        base.init();
        AbstractStrategy captureStrategy = new CaptureStrategy (_creature);
        this.addState (captureStrategy);

        AbstractStrategy deafStrategy = new DeafStrategy (_creature);
        this.addState (deafStrategy);

        AbstractStrategy moveStrategy = new MoveStrategy (_creature);
        this.addState (moveStrategy, true);

        AbstractStrategy combatStrategy = new CombatStrategy (_creature);
        this.addState (combatStrategy);

        _init = true;
    }
Beispiel #10
0
        public virtual bool Move(int row, int column)
        {
            var destination = new Tuple <int, int>(row, column);
            var origin      = new Tuple <int, int>(Row, Column);
            var moveSet     = MoveStrategy.GetMoveSet(Row, Column, OpposingColor);
            var canMove     = !destination.Equals(origin) &&
                              moveSet.Any(t => t.Equals(destination)) &&
                              !ChessBoard.IsCheckedState(this, destination);

            if (canMove)
            {
                BeforeMove(destination);
                ChessBoard.Remove(Row, Column);
                HandleCapture(destination);
                MoveCount++;
                AfterMove();
                ChessBoard.AddReplace(this, destination.Item1, destination.Item2);
            }
            return(canMove);
        }
        public override void Draw(DrawingContext context, Matrix matrix)
        {
            Point       position;
            double      length;
            Orientation orientation;

            if (this.baseFlowInsertionPoint.IsEmpty || MoveStrategy.GetContainerHost((SceneElement)this.baseFlowInsertionPoint.Element) == null || !this.GetInsertionInfo((SceneElement)this.baseFlowInsertionPoint.Element, this.baseFlowInsertionPoint.Index, this.baseFlowInsertionPoint.IsCursorAtEnd, out position, out length, out orientation))
            {
                return;
            }
            Point point1 = position;
            Point point2 = position;

            switch (orientation)
            {
            case Orientation.Horizontal:
                point2.Y += length;
                break;

            case Orientation.Vertical:
                point2.X += length;
                break;
            }
            Brush  activeBrush = FeedbackHelper.GetActiveBrush(AdornerType.Default);
            Pen    thinPen     = FeedbackHelper.GetThinPen(AdornerType.Default);
            Point  point0      = this.TransformPoint(point1);
            Point  point1_1    = this.TransformPoint(point2);
            Vector vector      = point1_1 - point0;

            if (!Tolerances.NearZero(vector))
            {
                vector.Normalize();
                context.PushTransform((Transform) new MatrixTransform(new Matrix(vector.X, vector.Y, -vector.Y, -vector.X, point0.X, point0.Y)));
                context.DrawGeometry(activeBrush, thinPen, BaseFlowInsertionPointAdorner.ArrowGeometry);
                context.Pop();
                context.PushTransform((Transform) new MatrixTransform(new Matrix(-vector.X, -vector.Y, vector.Y, -vector.X, point1_1.X, point1_1.Y)));
                context.DrawGeometry(activeBrush, thinPen, BaseFlowInsertionPointAdorner.ArrowGeometry);
                context.Pop();
            }
            context.DrawLine(thinPen, point0, point1_1);
        }
        public void MoveTest()
        {
            UnitTestUIDispatcher dispatcher = new UnitTestUIDispatcher();
            Point        startPoint         = new Point(100, 100);
            MoveStrategy ms         = new MoveStrategy();
            IRay         ray        = new Ray("1", startPoint, 0);
            IRenderable  renderable = new Renderable(Colors.Black, Colors.White, 1, 15, 15, 3);
            Shape        shape      = new Shape("1", ray, renderable, new RenderWithHeaderStrategy());
            Moveable     mv         = new Moveable(15, 15, 0, 0, shape, new MoveOpponentStrategy());

            ms.Move(mv, 1);
            mv.Shape.Ray.Angle += 90;

            ms.Move(mv, 1);
            mv.Shape.Ray.Angle += 90;

            ms.Move(mv, 1);
            mv.Shape.Ray.Angle += 90;
            ms.Move(mv, 1);

            Assert.IsTrue(mv.Shape.Ray.CenterPoint.Equals(startPoint));
        }
        internal static List <FlowPanelLayoutUtilities.LineInfo> ExtractLines(SceneElement container)
        {
            List <FlowPanelLayoutUtilities.LineInfo> list = new List <FlowPanelLayoutUtilities.LineInfo>();
            IViewPanel  flowPanel   = MoveStrategy.GetContainerHost(container) as IViewPanel;
            Orientation orientation = flowPanel.Orientation;
            double      num         = -1.0;
            Point       startPoint  = new Point(0.0, 0.0);

            FlowPanelLayoutUtilities.InitializeStartPoint(ref startPoint, flowPanel);
            int startElementIndex = 0;
            int endElementIndex   = 0;
            ActualBoundsInParent actualBoundsInParent = new ActualBoundsInParent(container);

            for (int index = 0; index < flowPanel.ChildrenCount; ++index)
            {
                IViewVisual child1 = flowPanel.GetChild(index);
                Rect        rect   = actualBoundsInParent[child1];
                num = FlowPanelLayoutUtilities.UpdateLineLength(num, startPoint, rect, orientation);
                if (endElementIndex + 1 < flowPanel.ChildrenCount)
                {
                    IViewVisual child2 = flowPanel.GetChild(endElementIndex + 1);
                    Rect        nextElementLayoutBounds = actualBoundsInParent[child2];
                    if (FlowPanelLayoutUtilities.IsNextElementStartOfNewLine(rect, nextElementLayoutBounds, orientation))
                    {
                        list.Add(new FlowPanelLayoutUtilities.LineInfo(startPoint, num, startElementIndex, endElementIndex));
                        startElementIndex = endElementIndex + 1;
                        FlowPanelLayoutUtilities.UpdateStartPoint(ref startPoint, num, orientation);
                        num = -1.0;
                    }
                    ++endElementIndex;
                }
                else
                {
                    list.Add(new FlowPanelLayoutUtilities.LineInfo(startPoint, num, startElementIndex, endElementIndex));
                    break;
                }
            }
            return(list);
        }
Beispiel #14
0
        public static IEnumerable <IMove> FirstTurn(Cube cube, Content player, MoveStrategy strategy = MoveStrategy.Domination)
        {
            SortedSet <MoveFirstTurn> moves = new SortedSet <MoveFirstTurn>();

            for (int idCell = 0; idCell < 24; ++idCell)
            {
                var c = cube.GetCell(idCell);
                if (c.Content != player)
                {
                    continue;
                }

                int pow = strategy != MoveStrategy.Random ? -1 : 0;
                int dom = strategy == MoveStrategy.Domination ? -1 : 0;

                var mv = new MoveFirstTurn(player, idCell);
                mv.Do(cube);
                mv.Weight = MainClass.Random.Next(100) + cube.ComputeCubeScore(player).DomPlayer *dom * 100 + 10000 * pow * c.Power;
                moves.Add(mv);
                mv.Undo(cube);
            }

            return(moves);
        }
Beispiel #15
0
        public static ushort MinMaxMove(TicTacToeBoard board, Piece.PieceValue token)
        {
            // computer always plays the center square if it is available
            if (!board.At(4))
            {
                return(4);
            }

            // computer's 2nd move should be a corner if computer went first
            // computer's 1st move should be a corner if the center is taken
            // really not the best strategy
            if ((board.Moves == 1 && board.At(4)) || board.Moves == 2)
            {
                return((TicTacToeBoard.Corners)[Computer.randNum.Next(0, TicTacToeBoard.Corners.Length - 1)]);
            }

            // start with recommended move
            ushort aMove = 4;

            // use MinMax strategy to find the next move
            MoveStrategy strategy = Computer.LookAhead(new Piece(token), new TicTacToeBoard(board), ref aMove);

            return(aMove);
        }
        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();

            if (Client.IsRegistered && Client.Board == null || Client.CurrentPiece == null || Client.NextPiece == null)
            {
                return;
            }

            DateTime searchBestMoveStartTime = DateTime.Now;

            // Use specials
            List <SpecialAdvice> advices;

            SpecialStrategy.GetSpecialAdvices(Client.Board, Client.CurrentPiece, Client.NextPiece, Client.Inventory, Client.InventorySize, Client.Opponents.ToList(), out advices);
            foreach (SpecialAdvice advice in advices)
            {
                bool continueLoop = true;
                switch (advice.SpecialAdviceAction)
                {
                case SpecialAdvice.SpecialAdviceActions.Wait:
                    continueLoop = false;
                    break;

                case SpecialAdvice.SpecialAdviceActions.Discard:
                    Client.DiscardFirstSpecial();
                    continueLoop = true;
                    break;

                case SpecialAdvice.SpecialAdviceActions.UseSelf:
                    continueLoop = Client.UseFirstSpecial(Client.PlayerId);
                    break;

                case SpecialAdvice.SpecialAdviceActions.UseOpponent:
                    continueLoop = Client.UseFirstSpecial(advice.OpponentId);
                    break;
                }
                if (!continueLoop)
                {
                    break;
                }
                System.Threading.Thread.Sleep(10); // delay next special use
            }

            DateTime specialManaged = DateTime.Now;

            // Get best move
            int  bestRotationDelta;
            int  bestTranslationDelta;
            bool rotationBeforeTranslation;

            MoveStrategy.GetBestMove(Client.Board, Client.CurrentPiece, Client.NextPiece, out bestRotationDelta, out bestTranslationDelta, out rotationBeforeTranslation);

            DateTime searchBestModeEndTime = DateTime.Now;

            // Perform move
            if (rotationBeforeTranslation)
            {
                // Rotate
                Rotate(bestRotationDelta);
                // Translate
                Translate(bestTranslationDelta);
            }
            else
            {
                // Translate
                Translate(bestTranslationDelta);
                // Rotate
                Rotate(bestRotationDelta);
            }
            // Drop (delayed)
            TimeSpan timeSpan  = DateTime.Now - searchBestMoveStartTime;
            double   sleepTime = SleepTime - timeSpan.TotalMilliseconds;

            if (sleepTime <= 0)
            {
                sleepTime = 10;
            }
            System.Threading.Thread.Sleep((int)sleepTime);  // delay drop instead of animating
            Client.Drop();
            //
            Log.Default.WriteLine(LogLevels.Info, "BEST MOVE found in {0} ms and special in {1} ms", (searchBestModeEndTime - specialManaged).TotalMilliseconds, (specialManaged - searchBestMoveStartTime).TotalMilliseconds);
        }
 public void Move(string direction)
 {
     MoveStrategy.Move(this, direction);
 }
Beispiel #18
0
        private void InitializeDrag(Point dragStartPosition)
        {
            SceneViewModel viewModel = this.ActiveView.ViewModel;

            this.CreateSubTransaction();
            this.dragStartPosition = dragStartPosition;
            this.ComputeDraggedElements();
            if (this.draggedElements == null || this.draggedElements.Count == 0)
            {
                this.moveStrategy  = (MoveStrategy)null;
                this.dragContainer = (BaseFrameworkElement)null;
                this.CancelDrag();
            }
            else
            {
                this.moveStrategy        = (MoveStrategy)null;
                this.moveStrategyContext = MoveStrategyContext.FromSelection((ToolBehavior)this, this.primarySelection, this.selectedElements, this.draggedElements, this.DuplicationOffset, this.dragStartPosition);
                this.dragContainer       = (BaseFrameworkElement)null;
                bool         flag          = false;
                SceneElement sceneElement1 = (SceneElement)null;
                foreach (SceneElement sceneElement2 in (IEnumerable <SceneElement>) this.selectedElements)
                {
                    BaseFrameworkElement frameworkElement = (BaseFrameworkElement)null;
                    BaseFrameworkElement editingContainer = viewModel.FindPanelClosestToActiveEditingContainer();
                    if (editingContainer != null && editingContainer.IsAncestorOf((SceneNode)sceneElement2))
                    {
                        frameworkElement = editingContainer;
                    }
                    if (!flag)
                    {
                        flag = true;
                        this.dragContainer = frameworkElement;
                        sceneElement1      = sceneElement2.ParentElement;
                    }
                    else if (sceneElement2.ParentElement != sceneElement1)
                    {
                        this.dragContainer = (BaseFrameworkElement)null;
                        break;
                    }
                    if (frameworkElement != this.dragContainer)
                    {
                        this.dragContainer = (BaseFrameworkElement)null;
                        break;
                    }
                }
                if (this.dragContainer != null)
                {
                    this.moveStrategy = MoveStrategyFactory.Create(this.moveStrategyContext, this.draggedElements[0].ParentElement, this.IsShiftDown);
                    if (this.moveStrategy != null)
                    {
                        this.moveStrategy.BeginDrag(dragStartPosition);
                        this.ToolBehaviorContext.SnappingEngine.Start(this.ToolBehaviorContext, this.primaryDraggedElement, this.draggedElements);
                    }
                    else
                    {
                        this.CancelDrag();
                    }
                }
                else
                {
                    this.CancelDrag();
                }
            }
        }
Beispiel #19
0
        private bool InternalOnDrag(Point dragStartPosition, Point dragCurrentPosition, bool scrollNow)
        {
            if (this.dragCancelled)
            {
                return(true);
            }
            this.EnsureEditTransaction();
            if (!this.HasMouseMovedAfterDown)
            {
                this.InitializeDrag(dragStartPosition);
            }
            if (this.dragCancelled || this.dragContainer == null)
            {
                return(true);
            }
            Point point = dragCurrentPosition;

            dragCurrentPosition = this.SnapPrimarySelectionBounds(dragStartPosition, dragCurrentPosition);
            Point dragStartPosition1 = dragStartPosition;

            this.dragCurrentPosition = dragCurrentPosition;
            Vector vector = this.dragCurrentPosition - this.dragStartPosition;

            this.ActiveView.EnsureVisible(dragStartPosition + vector, scrollNow);
            BaseFrameworkElement hitElement = this.GetHitElement(point, this.draggedElements) ?? this.dragContainer;

            if (this.ActiveSceneViewModel.FindPanelClosestToRoot() != this.dragContainer || hitElement.GetType() == typeof(Viewport3DElement))
            {
                hitElement = this.dragContainer;
            }
            MoveStrategy moveStrategy = MoveStrategyFactory.Create(this.moveStrategyContext, (SceneElement)hitElement, this.IsShiftDown);
            bool         flag         = this.enableReparenting && this.moveStrategy != null && (moveStrategy != null && moveStrategy.LayoutContainer != null) && moveStrategy.LayoutContainer != this.moveStrategy.LayoutContainer && moveStrategy.LayoutContainer.IsViewObjectValid;

            if (flag && this.IsAltDown)
            {
                this.ProvisionalContainer = (BaseFrameworkElement)null;
                this.ToolBehaviorContext.SnappingEngine.Stop();
                this.moveStrategy.EndDrag(false);
                this.ReplaceSubTransaction();
                this.UpdateEditTransaction();
                if (moveStrategy != null)
                {
                    this.moveStrategy = moveStrategy;
                    this.moveStrategy.BeginDrag(dragStartPosition1);
                    if (!this.moveStrategy.LayoutContainer.IsViewObjectValid)
                    {
                        this.CancelDrag();
                        return(true);
                    }
                    this.moveStrategy.ContinueDrag(dragCurrentPosition, hitElement);
                    this.ToolBehaviorContext.SnappingEngine.Start(this.ToolBehaviorContext, this.primaryDraggedElement, this.draggedElements);
                }
            }
            else if (moveStrategy != null)
            {
                if (!flag)
                {
                    this.ProvisionalContainer = (BaseFrameworkElement)null;
                }
                else
                {
                    this.ProvisionalContainer = moveStrategy.LayoutContainer;
                    this.SetTextCuePosition(dragCurrentPosition);
                }
                if (this.moveStrategy == null)
                {
                    this.moveStrategy = moveStrategy;
                    this.moveStrategy.BeginDrag(dragStartPosition);
                    this.ToolBehaviorContext.SnappingEngine.Start(this.ToolBehaviorContext, this.primaryDraggedElement, this.draggedElements);
                }
                this.moveStrategy.ContinueDrag(dragCurrentPosition, hitElement);
            }
            else if (this.moveStrategy != null)
            {
                this.moveStrategy.ContinueDrag(dragCurrentPosition, hitElement);
            }
            this.UpdateEditTransaction();
            if (this.moveStrategy != null && !this.moveStrategy.LayoutContainer.IsViewObjectValid)
            {
                this.CancelDrag();
            }
            return(true);
        }
Beispiel #20
0
        protected static MoveStrategy LookAhead(Piece inPiece, TicTacToeBoard inBoard, ref ushort bestMove)
        {
            // unused dummy value to seend the algorithm
            ushort aDummy = 0;
            // temporary strategy
            MoveStrategy aResponse;
            // the strategy to return
            MoveStrategy outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.OWin - 1 : MoveStrategy.XWin + 1;

            // first check to see if the game is a draw
            if (inBoard.Full())
            {
                outValue = MoveStrategy.Draw;
            }
            // return any move that results in an immediate win
            else if (Computer.ImmediateWin(inPiece, inBoard, ref bestMove))
            {
                outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.XWin : MoveStrategy.OWin;
            }
            // return any move that will result in blocking the other player from an immediate win on his next turn
            else if (Computer.ImmediateBlock(inPiece, inBoard, ref bestMove))
            {
                outValue = (inPiece.Value == Piece.PieceValue.X) ? MoveStrategy.XBlock : MoveStrategy.OBlock;
            }
            // no immediate wins so look for a promising move
            else
            {
                for (ushort i = 0; i < inBoard.Length; ++i)
                {
                    if (!inBoard.At(i))
                    {
                        inBoard.Place(inPiece, i);

                        // swap pieces and go down a move
                        Piece aPiece = (inPiece.Value == Piece.PieceValue.X)  ? new Piece(Piece.PieceValue.O) : new Piece(Piece.PieceValue.X);

                        // call look ahead recursively with a copy of the board each time
                        aResponse = LookAhead(aPiece, new TicTacToeBoard(inBoard), ref aDummy);

                        // determine the best move
                        switch (inPiece.Value)
                        {
                        case Piece.PieceValue.X:
                            if (aResponse > outValue)
                            {
                                outValue = aResponse;
                                bestMove = i;
                            }
                            break;

                        case Piece.PieceValue.O:
                            if (aResponse < outValue)
                            {
                                outValue = aResponse;
                                bestMove = i;
                            }
                            break;

                        default:
                            break;
                        } // end switch
                    }     // end if
                }         // end for loop
            }             // end else

            // return the best move strategy
            return(outValue);
        }
Beispiel #21
0
 public void UseRelativeMovement()
 {
     _strategy = MoveStrategy.Relative;
 }
Beispiel #22
0
    public void nextStep()
    {
        MoveStrategy strategy = getNextMoveStratrgy();

        int[] boat_roles = boat.getRolesNum();
        int[] right_boat = new int[2];
        if (strategy == MoveStrategy.P0D1)
        {
            right_boat[0] = 0;
            right_boat[1] = 1;
        }
        else if (strategy == MoveStrategy.P0D2)
        {
            right_boat[0] = 0;
            right_boat[1] = 2;
        }
        else if (strategy == MoveStrategy.P1D1)
        {
            right_boat[0] = 1;
            right_boat[1] = 1;
        }
        else if (strategy == MoveStrategy.P1D0)
        {
            right_boat[0] = 1;
            right_boat[1] = 0;
        }
        else if (strategy == MoveStrategy.P2D0)
        {
            right_boat[0] = 2;
            right_boat[1] = 0;
        }
        else if (strategy == MoveStrategy.END)
        {
            right_boat[0] = 0;
            right_boat[1] = 0;
        }
        else
        {
            return;
        }

        int need_p = right_boat[0] - boat_roles[0];             //船上还需要的牧师数量
        int need_d = right_boat[1] - boat_roles[1];             //船上还需要的魔鬼数量

        while (need_p < 0)
        {
            MoveRole(boat.getRole(1));
            need_p++;
        }
        while (need_d < 0)
        {
            MoveRole(boat.getRole(2));
            need_d++;
        }
        if (boat.getPos() == 0)
        {
            while (need_p > 0)
            {
                MoveRole(src.getRole(1));
                need_p--;
            }
            while (need_d > 0)
            {
                MoveRole(src.getRole(2));
                need_d--;
            }
        }
        else if (boat.getPos() == 2)
        {
            while (need_p > 0)
            {
                MoveRole(dst.getRole(1));
                need_p--;
            }
            while (need_d > 0)
            {
                MoveRole(dst.getRole(2));
                need_d--;
            }
        }
    }
Beispiel #23
0
 public void ResumeClipping()
 {
     _strategy = MoveStrategy.Clipped;
 }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MoveToDetailsViewMessage"/> class.
 /// </summary>
 /// <param name="typeOfDetailsView">The type of details view.</param>
 /// <param name="moveStrategy">The move strategy.</param>
 public MoveToDetailsViewMessage(string typeOfDetailsView, MoveStrategy moveStrategy)
 {
     TypeOfDetailsView = typeOfDetailsView;
     Strategy = moveStrategy;
 }
Beispiel #25
0
 public void UseRelativeMovement()
 {
     _strategy = MoveStrategy.Relative;
 }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MoveToDetailsViewMessage"/> class.
 /// </summary>
 /// <param name="typeOfDetailsView">The type of details view to move to.</param>
 /// <param name="moveStrategy">The move strategy.</param>
 public MoveToDetailsViewMessage(Type typeOfDetailsView, MoveStrategy moveStrategy)
     : this(typeOfDetailsView.ToString(), moveStrategy) { }
Beispiel #27
0
        public static bool MoveTo(this string txt, ref int p, string value, MoveStrategy strategy, char stopChar = '\0')
        {
            var matched = false;
            var i       = p + 1;
            var j       = 0;

            switch (strategy)
            {
            case MoveStrategy.AllAllowed:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        j = 0;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.OnlyWhitespacesAllowed:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        if (!char.IsWhiteSpace(txt[i]))
                        {
                            break;
                        }
                        j = 0;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.AllButNewlinesAllowed:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        if (txt[i] == '\r' || txt[i] == '\n')
                        {
                            break;
                        }
                        j = 0;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.AllButWhitespacesAllowed:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        if (char.IsWhiteSpace(txt[i]))
                        {
                            break;
                        }
                        j = 0;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.ImmediateValue:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        break;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.UntilNewline:
                while (i < txt.Length)
                {
                    if (txt[i] == '\r' || txt[i] == '\n' || i == txt.Length - 1)
                    {
                        matched = true;
                        break;
                    }
                    i++;
                }
                if (i < txt.Length && matched)
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            case MoveStrategy.UntilChar:
                while (i < txt.Length)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == value.Length - 1)
                        {
                            matched = true;
                            break;
                        }
                        j++;
                    }
                    else
                    {
                        if (txt[i] == stopChar)
                        {
                            break;
                        }
                        j = 0;
                    }
                    i++;
                }
                if (i < txt.Length && matched && (txt[i] == ';' || char.IsWhiteSpace(txt[i + 1]) || txt[i + 1] == ';'))
                {
                    p = ++i;
                    return(true);
                }
                return(false);

            default:
                return(false);
            }
        }
Beispiel #28
0
        private void BotTask()
        {
            WaitHandle[] waitHandles =
            {
                _handleNextPieceEvent,
                _stopEvent
            };
            while (true)
            {
                int handle = WaitHandle.WaitAny(waitHandles, SleepTime);
                if (!_handleNextPieceEvent.WaitOne(0) && _client.IsPlaying && !_isConfusionActive)
                {
                    Log.Default.WriteLine(LogLevels.Warning, "!!!!!!!!!!! NextPieceEvent not raised  {0}  {1}", handle, _client.CurrentPiece?.Index ?? -1);
                }
                _handleNextPieceEvent.Reset();
                _stopEvent.Reset();

                if (handle == 1) // stop event
                {
                    break;
                }
                if (handle == 0 /*next piece event*/ && _client.IsPlaying && _client.Board != null && _client.CurrentPiece != null && _client.NextPiece != null)
                {
                    Log.Default.WriteLine(LogLevels.Debug, "NextPieceEvent was raised");

                    int currentPieceIndex = _client.CurrentPiece.Index;
                    //Log.Default.WriteLine(LogLevels.Debug, "Searching best move for Piece {0} {1}", _client.CurrentPiece.Value, _client.CurrentPiece.Index);

                    DateTime searchBestMoveStartTime = DateTime.Now;

                    // Use specials
                    if (SpecialStrategy != null)
                    {
                        List <SpecialAdvice> advices;
                        SpecialStrategy.GetSpecialAdvices(_client.Board, _client.CurrentPiece, _client.NextPiece, _client.Inventory, _client.InventorySize, _client.Opponents.ToList(), out advices);
                        foreach (SpecialAdvice advice in advices)
                        {
                            bool continueLoop = true;
                            switch (advice.SpecialAdviceAction)
                            {
                            case SpecialAdvice.SpecialAdviceActions.Wait:
                                continueLoop = false;
                                break;

                            case SpecialAdvice.SpecialAdviceActions.Discard:
                                _client.DiscardFirstSpecial();
                                continueLoop = true;
                                break;

                            case SpecialAdvice.SpecialAdviceActions.UseSelf:
                                continueLoop = _client.UseFirstSpecial(_client.PlayerId);
                                break;

                            case SpecialAdvice.SpecialAdviceActions.UseOpponent:
                                continueLoop = _client.UseFirstSpecial(advice.OpponentId);
                                break;
                            }
                            if (!continueLoop)
                            {
                                break;
                            }
                            Thread.Sleep(10); // delay next special use
                        }
                    }

                    DateTime specialManaged = DateTime.Now;

                    // No move evaluation if confusion is active
                    if (_isConfusionActive)
                    {
                        Log.Default.WriteLine(LogLevels.Info, "Confusion is active, no move evaluated");
                        continue;
                    }

                    // Get best move
                    if (MoveStrategy != null)
                    {
                        int  bestRotationDelta;
                        int  bestTranslationDelta;
                        bool rotationBeforeTranslation;
                        MoveStrategy.GetBestMove(_client.Board, _client.CurrentPiece, _client.NextPiece, out bestRotationDelta, out bestTranslationDelta, out rotationBeforeTranslation);

                        // TODO: could use an event linked to Client.OnRoundFinished
                        if (_client.CurrentPiece.Index != currentPieceIndex)
                        {
                            Log.Default.WriteLine(LogLevels.Warning, "BOT IS TOO SLOW COMPARED TO AUTOMATIC DROP, skipping to next piece {0} != {1}", _client.CurrentPiece.Index, currentPieceIndex);
                            continue;
                        }

                        DateTime searchBestModeEndTime = DateTime.Now;

                        //Log.Default.WriteLine(LogLevels.Debug, "Rotation: {0} Translation {1}  {2}", bestRotationDelta, bestTranslationDelta, rotationBeforeTranslation);

                        // Perform move

                        if (rotationBeforeTranslation)
                        {
                            // Rotate
                            Rotate(bestRotationDelta);
                            // Translate
                            Translate(bestTranslationDelta);
                        }
                        else
                        {
                            // Translate
                            Translate(bestTranslationDelta);
                            // Rotate
                            Rotate(bestRotationDelta);
                        }
                        // Drop (delayed)
                        TimeSpan timeSpan  = DateTime.Now - searchBestMoveStartTime;
                        double   sleepTime = SleepTime - timeSpan.TotalMilliseconds;
                        if (sleepTime < 10)
                        {
                            sleepTime = 10; // at least 10 ms
                        }
                        //Thread.Sleep((int)sleepTime); // delay drop instead of animating
                        bool stopped = _stopEvent.WaitOne((int)sleepTime);
                        if (stopped)
                        {
                            //Log.Default.WriteLine(LogLevels.Debug, "Stop bot received while sleeping before next move");
                            break;
                        }
                        // TODO: could use an event linked to Client.OnRoundFinished
                        if (_client.CurrentPiece.Index != currentPieceIndex)
                        {
                            Log.Default.WriteLine(LogLevels.Warning, "BOT IS TOO SLOW COMPARED TO AUTOMATIC DROP, skipping to next piece {0} != {1}", _client.CurrentPiece.Index, currentPieceIndex);
                            continue;
                        }
                        // Drop
                        Drop();
                    }
                    //
                    //Log.Default.WriteLine(LogLevels.Debug, "BEST MOVE found in {0} ms and special in {1} ms  {2} {3}", (searchBestModeEndTime - specialManaged).TotalMilliseconds, (specialManaged - searchBestMoveStartTime).TotalMilliseconds, _client.CurrentPiece.Value, _client.CurrentPiece.Index);
                }
            }
        }
        protected override bool GetInsertionInfo(SceneElement container, int insertionIndex, bool isCursorAtEnd, out Point position, out double length, out Orientation orientation)
        {
            position    = new Point();
            length      = 0.0;
            orientation = Orientation.Horizontal;
            IViewPanel viewPanel = MoveStrategy.GetContainerHost(container) as IViewPanel;

            if (container == null || viewPanel == null)
            {
                return(false);
            }
            orientation = viewPanel.Orientation;
            if (viewPanel.ChildrenCount == 0)
            {
                position = new Point(0.0, 0.0);
                length   = orientation == Orientation.Horizontal ? viewPanel.RenderSize.Height : viewPanel.RenderSize.Width;
                return(true);
            }
            List <FlowPanelLayoutUtilities.LineInfo> lines = FlowPanelLayoutUtilities.ExtractLines(container);

            if (lines.Count <= 0)
            {
                return(false);
            }
            FlowPanelLayoutUtilities.LineInfo lineInfo1 = (FlowPanelLayoutUtilities.LineInfo)null;
            IViewVisual          index = (IViewVisual)null;
            ActualBoundsInParent actualBoundsInParent = new ActualBoundsInParent(container);

            foreach (FlowPanelLayoutUtilities.LineInfo lineInfo2 in lines)
            {
                if (lineInfo2.EndElementIndex == insertionIndex - 1 && isCursorAtEnd && insertionIndex < viewPanel.ChildrenCount)
                {
                    index     = viewPanel.GetChild(lineInfo2.EndElementIndex);
                    lineInfo1 = lineInfo2;
                    length    = lineInfo2.LineLength;
                    break;
                }
                if (lineInfo2.StartElementIndex <= insertionIndex && insertionIndex <= lineInfo2.EndElementIndex)
                {
                    index     = viewPanel.GetChild(insertionIndex);
                    lineInfo1 = lineInfo2;
                    length    = lineInfo2.LineLength;
                    break;
                }
            }
            Matrix matrixFromTransform = VectorUtilities.GetMatrixFromTransform(this.AdornerSet.ViewModel.DefaultView.ComputeTransformToVisual((IViewObject)viewPanel, this.Element.Visual));
            Point  point = new Point(matrixFromTransform.OffsetX, matrixFromTransform.OffsetY);

            if (index != null && lineInfo1 != null)
            {
                Rect rect = actualBoundsInParent[index];
                switch (orientation)
                {
                case Orientation.Horizontal:
                    double num1 = isCursorAtEnd ? rect.Right : rect.Left;
                    position = new Point(num1 + point.X, lineInfo1.StartPoint.Y + point.Y);
                    break;

                case Orientation.Vertical:
                    double num2 = isCursorAtEnd ? rect.Bottom : rect.Top;
                    position = new Point(lineInfo1.StartPoint.X + point.X, num2 + point.Y);
                    break;

                default:
                    throw new NotImplementedException(ExceptionStringTable.StackPanelUnrecognizedOrientation);
                }
                return(true);
            }
            FlowPanelLayoutUtilities.LineInfo lineInfo3 = lines[lines.Count - 1];
            if (insertionIndex <= lineInfo3.EndElementIndex)
            {
                return(false);
            }
            IViewVisual child = viewPanel.GetChild(lineInfo3.EndElementIndex);
            Rect        rect1 = actualBoundsInParent[child];

            switch (orientation)
            {
            case Orientation.Horizontal:
                position = new Point(rect1.Right + point.X, lineInfo3.StartPoint.Y + point.Y);
                break;

            case Orientation.Vertical:
                position = new Point(lineInfo3.StartPoint.X + point.X, rect1.Bottom + point.Y);
                break;

            default:
                throw new NotImplementedException(ExceptionStringTable.StackPanelUnrecognizedOrientation);
            }
            length = lineInfo3.LineLength;
            return(true);
        }
Beispiel #30
0
        public static bool MoveFrom(this string txt, ref int p, string value, MoveStrategy strategy, char stopChar = '\0')
        {
            var matched = false;
            var i       = p - 1;
            var j       = value.Length - 1;

            switch (strategy)
            {
            case MoveStrategy.AllAllowed:
                while (i >= 0)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == 0)
                        {
                            matched = true;
                            break;
                        }
                        j--;
                    }
                    else
                    {
                        j = value.Length - 1;
                    }
                    i--;
                }
                if (i >= 0 && matched && (char.IsWhiteSpace(txt[i - 1]) || txt[i] == ';' || txt[i - 1] == ';'))
                {
                    p = --i;
                    return(true);
                }
                return(false);

            case MoveStrategy.OnlyWhitespacesAllowed:
                while (i >= 0)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == 0)
                        {
                            matched = true;
                            break;
                        }
                        j--;
                    }
                    else
                    {
                        if (!char.IsWhiteSpace(txt[i]))
                        {
                            break;
                        }
                        j = value.Length - 1;
                    }
                    i--;
                }
                if (i >= 0 && matched && (char.IsWhiteSpace(txt[i - 1]) || txt[i - 1] == ';'))
                {
                    p = --i;
                    return(true);
                }
                return(false);

            case MoveStrategy.AllButNewlinesAllowed:
                while (i >= 0)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == 0)
                        {
                            matched = true;
                            break;
                        }
                        j--;
                    }
                    else
                    {
                        if (txt[i] == '\r' || txt[i] == '\n')
                        {
                            break;
                        }
                        j = value.Length - 1;
                    }
                    i--;
                }
                if (i >= 0 && matched && (char.IsWhiteSpace(txt[i - 1]) || txt[i - 1] == ';'))
                {
                    p = --i;
                    return(true);
                }
                return(false);

            case MoveStrategy.ImmediateValue:
                while (i >= 0)
                {
                    if (txt[i] == value[j])
                    {
                        if (j == 0)
                        {
                            matched = true;
                            break;
                        }
                        j--;
                    }
                    else
                    {
                        break;
                    }
                    i--;
                }
                if (i >= 0 && matched && (char.IsWhiteSpace(txt[i - 1]) || txt[i - 1] == ';'))
                {
                    p = --i;
                    return(true);
                }
                return(false);

            case MoveStrategy.UntilNewline:
                while (i >= 0)
                {
                    if (txt[i] == '\r' || txt[i] == '\n')
                    {
                        matched = true;
                        break;
                    }
                    i--;
                }
                if (i >= 0 && matched)
                {
                    p = --i;
                    return(true);
                }
                return(false);

            default:
                return(false);
            }
        }
Beispiel #31
0
 public override void lookAhead()
 {
     MoveStrategy.LookAhead();
 }
Beispiel #32
0
 public void SetClip(int x, int y)
 {
     _strategy = MoveStrategy.Clipped;
     _physicalCursorLocation = new Point(x, y);
     _prev = _physicalCursorLocation;
     Win32.SetCursorPos(x, y);
 }
Beispiel #33
0
 public GameState(MoveStrategy strategy)
 {
     Strategy = strategy;
 }
        public static int GetInsertionIndex(SceneElement container, Point position, out bool isCursorAtEnd)
        {
            isCursorAtEnd = false;
            IViewPanel viewPanel = MoveStrategy.GetContainerHost(container) as IViewPanel;

            if (viewPanel == null)
            {
                return(0);
            }
            Orientation orientation = viewPanel.Orientation;

            if (viewPanel.ChildrenCount == 0)
            {
                return(0);
            }
            bool flag = PlatformTypes.StackPanel.IsAssignableFrom((ITypeId)container.Type) || PlatformTypes.VirtualizingStackPanel.IsAssignableFrom((ITypeId)container.Type);
            ActualBoundsInParent actualBoundsInParent = new ActualBoundsInParent(container);

            foreach (FlowPanelLayoutUtilities.LineInfo line in FlowPanelLayoutUtilities.ExtractLines(container))
            {
                if (flag || FlowPanelLayoutUtilities.IsPointInLine(position, line, orientation))
                {
                    if (line.StartElementIndex == line.EndElementIndex)
                    {
                        IViewVisual child = viewPanel.GetChild(line.StartElementIndex);
                        Rect        elementLayoutBounds = actualBoundsInParent[child];
                        if (FlowPanelLayoutUtilities.DoesPointLieBeforeElement(position, elementLayoutBounds, orientation))
                        {
                            isCursorAtEnd = false;
                            return(line.StartElementIndex);
                        }
                        isCursorAtEnd = true;
                        return(line.StartElementIndex + 1);
                    }
                    IViewVisual child1 = viewPanel.GetChild(line.StartElementIndex);
                    IViewVisual child2 = viewPanel.GetChild(line.EndElementIndex);
                    Rect        elementLayoutBounds1 = actualBoundsInParent[child1];
                    Rect        elementLayoutBounds2 = actualBoundsInParent[child2];
                    if (FlowPanelLayoutUtilities.DoesPointLieBeforeElement(position, elementLayoutBounds1, orientation))
                    {
                        isCursorAtEnd = false;
                        return(line.StartElementIndex);
                    }
                    if (FlowPanelLayoutUtilities.DoesPointLieAfterElement(position, elementLayoutBounds2, orientation))
                    {
                        isCursorAtEnd = true;
                        return(line.EndElementIndex + 1);
                    }
                    for (int startElementIndex = line.StartElementIndex; startElementIndex < line.EndElementIndex; ++startElementIndex)
                    {
                        IViewVisual child3 = viewPanel.GetChild(startElementIndex);
                        IViewVisual child4 = viewPanel.GetChild(startElementIndex + 1);
                        Rect        currentElementLayoutBounds = actualBoundsInParent[child3];
                        Rect        nextElementLayoutBounds    = actualBoundsInParent[child4];
                        if (FlowPanelLayoutUtilities.DoesPointLieBetweenElements(position, currentElementLayoutBounds, nextElementLayoutBounds, orientation))
                        {
                            return(startElementIndex + 1);
                        }
                    }
                    break;
                }
            }
            if (flag)
            {
                return(-1);
            }
            isCursorAtEnd = true;
            return(viewPanel.ChildrenCount);
        }
Beispiel #35
0
 public void ClearClip()
 {
     _strategy = MoveStrategy.Standard;
     _physicalCursorLocation = _curr;
     _prev = new Point(_curr.X, _curr.Y);
     Win32.SetCursorPos(_curr.X, _curr.Y);
 }
Beispiel #36
0
 public void ResumeClipping()
 {
     _strategy = MoveStrategy.Clipped;
 }