Esempio n. 1
0
        public override bool IsValidMove(IPlayer player, IMove move)
        {
            var checkersBoard = (CheckersBoard)CurrentGameState;
            var checkersMove = (CheckersMove)move;
            var checkersPlayer = (CheckersPlayer)player;
            var startPiece = (CheckersPiece)checkersBoard.GetPieceAt(checkersMove.MovePath[0]);

            if (startPiece==null) return false;
            if (startPiece.Color != checkersPlayer.Color) return false;

            int maxEat=0;
            bool eatMove=false;

            foreach (var piece in checkersBoard.GetPiecesOfColor(startPiece.Color))
            {
                var possibleMoves = piece.PossibleMoves;
                if (possibleMoves.Count > 0)
                {
                    var otherMove = possibleMoves[0] as CheckersMove;
                    if (maxEat < otherMove.MovePath.Length)
                    {
                        maxEat = otherMove.MovePath.Length;
                    }
                    if (otherMove.EatMove)
                        eatMove = true;
                }
            }

            bool isPossible = startPiece.PossibleMoves.Cast<CheckersMove>().Contains(checkersMove);
            return
                eatMove==checkersMove.EatMove &&
                checkersMove.MovePath.Length==maxEat &&
                isPossible;
        }
Esempio n. 2
0
 internal NodeBase(INode parentNode, IMove move, float uctk, IPlayer player)
 {
     this.parent = parentNode;
     this.move = move;
     this.uctk = uctk;
     this.playerJustMoved = player;
 }
Esempio n. 3
0
 internal Pouring(IReadOnlyList<int> capacities, IReadOnlyList<int> state, Pouring previous, IMove move)
 {
     Capacities = capacities;
     State = state;
     Move = move;
     Previous = previous;
 }
Esempio n. 4
0
 public DeliverGoods(Actor self)
 {
     trader = self.Trait<Trader>();
     traderInfo = self.Info.Traits.Get<TraderInfo>();
     move = self.Trait<IMove>();
     pathFinder = self.World.WorldActor.Trait<IPathFinder>();
 }
Esempio n. 5
0
 protected Enter(Actor self, Actor target, int maxTries = 1, bool targetCenter = false)
 {
     this.move = self.Trait<IMove>();
     this.target = Target.FromActor(target);
     this.maxTries = maxTries;
     this.targetCenter = targetCenter;
 }
Esempio n. 6
0
        public GameState Execute()
        {
            _numPushed = 0;
            _oldPieceToMove = _state.PieceToMove;
            _oldLastMove = _state.LastMove;
            _start = _piece.Position;

            int ystep = _end.Y - _start.Y;

            _state.BoardPositions[_piece.Position.Y][_piece.Position.X] = null;
            Piece currentPiece = _piece;
            while (_state.BoardPositions[currentPiece.Position.Y + ystep][currentPiece.Position.X] != null)
            {
                Piece next = _state.BoardPositions[currentPiece.Position.Y + ystep][currentPiece.Position.X];
                _state.BoardPositions[currentPiece.Position.Y + ystep][currentPiece.Position.X] = currentPiece;
                currentPiece.Position = new Point(currentPiece.Position.X, currentPiece.Position.Y + ystep);
                currentPiece = next;
                _numPushed++;
            }

            _state.BoardPositions[currentPiece.Position.Y + ystep][currentPiece.Position.X] = currentPiece;
            currentPiece.Position = new Point(currentPiece.Position.X, currentPiece.Position.Y + ystep);

            _state.IsPlayerTwo = !_state.IsPlayerTwo;
            _state.PieceToMove = currentPiece;
            _state.LastMove = this;

            List<IMove> possible = new List<IMove>();
            possible.Add(new SumoDazedMove(_state, currentPiece));
            _state.PossibleMoves = possible;

            return _state;
        }
Esempio n. 7
0
 public Contrail(Actor self, ContrailInfo info)
 {
     contrailTurret = new Turret(info.ContrailOffset);
     history = new ContrailHistory(info.TrailLength,
         info.UsePlayerColor ? ContrailHistory.ChooseColor(self) : info.Color);
     facing = self.Trait<IFacing>();
     move = self.Trait<IMove>();
 }
Esempio n. 8
0
        public Follow(Actor self, Target target, WRange minRange, WRange maxRange)
        {
            this.target = target;
            this.minRange = minRange;
            this.maxRange = maxRange;

            move = self.Trait<IMove>();
        }
Esempio n. 9
0
 public Refuel(Actor self, Actor host)
 {
     move = self.TraitOrDefault<IMove>();
     this.host = host;
     target = Target.FromActor(host);
     refuels = host.TraitOrDefault<RefuelsUnits>();
     fueltank = self.TraitOrDefault<Fueltank>();
 }
Esempio n. 10
0
 public LayMines(Actor self)
 {
     minelayer = self.TraitOrDefault<Minelayer>();
     info = self.Info.TraitInfo<MinelayerInfo>();
     ammoPools = self.TraitsImplementing<AmmoPool>().ToArray();
     movement = self.Trait<IMove>();
     rearmBuildings = info.RearmBuildings;
 }
Esempio n. 11
0
		public Drag(Actor self, WPos start, WPos end, int length)
		{
			positionable = self.Trait<IPositionable>();
			movement = self.TraitOrDefault<IMove>();
			moveDisablers = self.TraitsImplementing<IDisableMove>().ToArray();
			this.start = start;
			this.end = end;
			this.length = length;
		}
Esempio n. 12
0
        public static Computer getInstance(IMove lvl)
        {
            if (instance == null)
            {
                instance = new Computer(lvl);
            }
            return instance;

        }
Esempio n. 13
0
    protected virtual void Start()
    {
        this.moveBehaviour = this.GetComponent<IMove> ();
        if (this.moveBehaviour == null) {
            this.moveBehaviour = this.gameObject.AddComponent<EmptyMove> ();
        }

        this.moveBehaviour.Init (this.sea);
    }
Esempio n. 14
0
 public PutShipsUserControl(IMove lvl)
 {
     InitializeComponent();
     computer = Computer.getInstance(lvl);
     DisableComputerBoard();
     computerShipsAdded = computer.PutComputerShips();
     MessageBox.AppendText("Dodano wszystkie statki przeciwnika.");
     MessageBox.AppendText(Environment.NewLine + "Proszę dodać dwumasztowy statek.");
 }
Esempio n. 15
0
        public Board(int[,] data, IMove move)
        {
            if (data == null) { throw new ArgumentNullException(nameof(data)); }

            _data = (int[,])data.Clone();
            _data[move.Row, move.Column] = move.Value;

            // Validate(_data);
        }
Esempio n. 16
0
 public Drag(Actor self, WPos start, WPos end, int length)
 {
     positionable = self.Trait<IPositionable>();
     movement = self.TraitOrDefault<IMove>();
     disableable = movement as IDisabledTrait;
     this.start = start;
     this.end = end;
     this.length = length;
 }
Esempio n. 17
0
 internal SingleThreadedNode(INode parent, IMove move, IGameState gameState, float uctk)
     : base(parent, move, uctk, gameState.PlayerJustMoved)
 {
     this.wins = 0L;
     this.visits = 0L;
     this.childs = new List<INode>();
     var moves = gameState.GetMoves();
     var shuffled = moves.Shuffle();
     this.untriedMoves = new Stack<IMove>(shuffled); //randomize Moves
 }
        protected override bool CanStrategyMovePiece(IPlayer player, IBoard board, IMove move, IGameRuleStrategyContext context)
        {
            if (board.Bar.Any(x => x.Player == player.Name))
            {
                context.IsDone = true;
                return this.IsMoveValid(board, move.Die.Value, player.Name);
            }

            return false;
        }
 public bool CanMovePiece(IPlayer player, IBoard board, IMove move)
 {
     var context = new DefaultGameRuleStrategyContext();
     var canMovePiece = false;
     for (var strategy = this; !context.IsDone && !canMovePiece && strategy != null; strategy = strategy.next)
     {
         canMovePiece = strategy.CanStrategyMovePiece(player, board, move, context);
     }
     return canMovePiece;
 }
Esempio n. 20
0
 public PickupUnit(Actor self, Actor cargo)
 {
     this.cargo = cargo;
     carryable = cargo.Trait<Carryable>();
     cargoFacing = cargo.Trait<IFacing>();
     movement = self.Trait<IMove>();
     carryall = self.Trait<Carryall>();
     helicopter = self.Trait<Helicopter>();
     selfFacing = self.Trait<IFacing>();
     state = State.Intercept;
 }
Esempio n. 21
0
		public Attack(Actor self, Target target, WRange minRange, WRange maxRange, bool allowMovement)
		{
			Target = target;
			this.minRange = minRange;
			this.maxRange = maxRange;

			attack = self.Trait<AttackBase>();
			facing = self.Trait<IFacing>();

			move = allowMovement ? self.TraitOrDefault<IMove>() : null;
		}
Esempio n. 22
0
            public AttackActivity(Actor self, Target target, bool allowMove)
            {
                attack = self.Trait<AttackFollow>();
                move = allowMove ? self.TraitOrDefault<IMove>() : null;

                // HACK: Mobile.OnRails is horrible
                var mobile = move as Mobile;
                if (mobile != null && mobile.Info.OnRails)
                    move = null;

                this.target = target;
            }
Esempio n. 23
0
        public GameState Execute()
        {
            _oldPieceToMove = _state.PieceToMove;
            _oldLastMove = _state.LastMove;

            _state.IsPlayerTwo = !_state.IsPlayerTwo;
            _state.PieceToMove = _state.PiecePositions[_state.IsPlayerTwo ? 1 : 0][(int)Board.Tile[_end.Y, _end.X]];
            _state.PossibleMoves = null;
            _state.LastMove = this;

            return _state;
        }
Esempio n. 24
0
		public Attack(Actor self, Target target, bool allowMovement, bool forceAttack)
		{
			Target = target;

			this.forceAttack = forceAttack;

			attack = self.Trait<AttackBase>();
			facing = self.Trait<IFacing>();
			positionable = self.Trait<IPositionable>();

			move = allowMovement ? self.TraitOrDefault<IMove>() : null;
		}
Esempio n. 25
0
		public DeliverUnit(Actor self)
		{
			carryall = self.Trait<Carryall>();
			this.self = self;
			cargo = carryall.Carrying;
			movement = self.Trait<IMove>();
			carryable = cargo.Trait<Carryable>();
			aircraft = self.Trait<Aircraft>();
			positionable = cargo.Trait<IPositionable>();
			cargoFacing = cargo.Trait<IFacing>();
			selfFacing = self.Trait<IFacing>();
			state = State.Transport;
		}
Esempio n. 26
0
        public PickupUnit(Actor self, Actor cargo, int delay)
        {
            this.cargo = cargo;
            this.delay = delay;
            carryable = cargo.Trait<Carryable>();
            carryableFacing = cargo.Trait<IFacing>();
            carryableBody = cargo.Trait<BodyOrientation>();

            movement = self.Trait<IMove>();
            carryall = self.Trait<Carryall>();
            carryallFacing = self.Trait<IFacing>();

            state = State.Intercept;
        }
 /// <summary>
 /// Initializes a new instance of the RotationInfo class
 /// </summary>
 /// <param name="move">Move or move collection that will be rotated animated</param>
 /// <param name="milliseconds">Duration of animated rotation</param>
 public RotationInfo(IMove move, int milliseconds)
 {
     this.Milliseconds = milliseconds;
     this.Name = move.Name;
     this.Moves = new List<AnimatedLayerMove>();
     if (move.MultipleLayers)
     {
         foreach (var m in (LayerMoveCollection)move)
         {
             this.Moves.Add(new AnimatedLayerMove(m));
         }
     }
     else
     {
         this.Moves.Add(new AnimatedLayerMove((LayerMove)move));
     }
 }
Esempio n. 28
0
        public Board(IBoard board, IMove move)
        {
            if (board == null) { throw new ArgumentNullException(nameof(board)); }
            Board other = (Board)board;

            if (other != null) {
                _data = (int[,])other._data.Clone();

                if (move != null) {
                    _data[move.Row, move.Column] = move.Value;
                }
            }
            else {
                throw new ArgumentException($"Unknown board type {nameof(board)}");
            }

            // Validate(_data);
        }
 protected override bool CanStrategyMovePiece(IPlayer player, IBoard board, IMove move, IGameRuleStrategyContext context)
 {
     var targetIndex = move.LaneIndex + move.Die.Value;
     if (targetIndex < board.Lanes.Count || this.NeedToMovePiece(board, player.Name))
         return false;
     else if (targetIndex == board.Lanes.Count)
         return true;
     else
     {
         for (var i = (board.Lanes.Count * 3) / 4; i < move.LaneIndex; i++)
         {
             var lane = board.Lanes[i];
             if (lane.Count > 0 && lane[0].Player == player.Name)
                 return false;
         }
         return true;
     }
 }
Esempio n. 30
0
        private int Compute(ref IMove bestMove, GameBoard board, PlayerColor currentPlayer, int startDepth, int depth)
        {
            CheckForStop();

            if (depth == 0) return Evaluator.Evaluate(board, currentPlayer);

            var moves = RuleEngine.GetAllMovesForPlayer(board, currentPlayer);

            CheckForStop();

            if (moves.Count() == 0) return Evaluator.Evaluate(board, currentPlayer);

            int bestValue = int.MinValue;
            PlayerColor opponent = GameUtils.OtherPlayer(currentPlayer);
            GameBoard boardCopy = board.Copy();

            CheckForStop();

            foreach (var move in moves)
            {
                CheckForStop();
                boardCopy.DoMove(move, true);
                int moveValue = -Compute(ref bestMove, boardCopy, opponent, startDepth, depth - 1);
                IMove revMove = move.Reverse();
                boardCopy.DoMove(revMove, true);
                CheckForStop();

                if (depth == startDepth)
                {
                    Trace.WriteLine(string.Format("Move: {0} Value: {1}", move.ToString(), moveValue.ToString()));

                    if (bestMove == null || moveValue > bestValue)
                    {
                        bestMove = move;
                    }
                }

                bestValue = Math.Max(bestValue, moveValue);
            }

            return bestValue;
        }
Esempio n. 31
0
 public void BeginBestMove()
 {
     stani = false;
     //
     Task.Run(() =>
     {
         int i = 1;
         while (true)
         {
             if (stani)
             {
                 stani = false;
                 break;
             }
             BestMove = ContextMakao.AlfaBeta(context, i, int.MinValue, int.MaxValue);
             i++;
         }
     } //
              );
 }
Esempio n. 32
0
 public void Bacenekarte(List <Karta> karte, Boja boja, int BrojKarataProtivnika)
 {
     if (karte != null && karte.Count > 0)
     {
         talon = karte.Last();
         remainingCards.remove(karte);
     }
     novaBoja        = boja;
     brojKarataEnemy = BrojKarataProtivnika;
     BestMove        = new Move();
     kupio           = false;
     if (karte != null && karte.Count > 0)
     {
         kupioKaznene = false;
     }
     else
     {
         kupioKaznene = true;
     }
 }
Esempio n. 33
0
        public void ApplyMove(IMove move)
        {
            Requires.IsNotNull(move, "move");

            if (move.Column < 0 || move.Column >= Width)
            {
                throw new InvalidColumnException(
                          StringResources.ColumnOutsideTheScope("ApplyMove", move.Column));
            }

            if (fields[move.Row, move.Column].PlayerId == 0)
            {
                fields[move.Row, move.Column].PlayerId = move.PlayerId;
                LastMove = move;
                return;
            }

            throw new InvalidColumnException(
                      StringResources.ColumnIsFull("ApplyMove", move.Column));
        }
Esempio n. 34
0
        private async void CPUMove()
        {
            while (game.players[playerTurn].GetPlayerType() == PlayerType.CPU)
            {
                IMove move = null;
                var   task = Task.Run(() =>
                {
                    move = game.AIMakeMove();
                });
                await task;

                if (move == null)
                {
                    watch.Stop();
                    return;
                }
                var btn = buttons[10000 * move.GetField().GetX() + move.GetField().GetY()];
                UpdateGUI(btn);
            }
        }
Esempio n. 35
0
        public Ship(IMove moveImplementation, IRotation rotationImplementation, IShoot shootImplementation,
                    Transform transform, ITransformRegistry transformRegistry, Stat health,
                    ShipMarkUp shipGameObjectMarkUp)
        {
            _moveImplementation     = moveImplementation;
            _rotationImplementation = rotationImplementation;
            shooter = shootImplementation;

            GameTransform         = transform;
            TransformRegistryBind = transformRegistry;
            TransformRegistryBind.RegisterTransform(this, GameTransform);

            StatHolder = new StatHolder();
            healthStat = health;
            healthStat.CurrentChanged += ProcessHealthChange;
            StatHolder.AddStat(StatType.Health, healthStat);

            colliderListener = shipGameObjectMarkUp.ColliderListener;
            colliderListener.EnterCollider += ProcessCollisions;
        }
Esempio n. 36
0
            public bool CompareTo(IMove move)
            {
                var cmp = move as ChainMove;

                if (cmp != null)
                {
                    for (int i = 0; i < cmp.Moves.Count; i++)
                    {
                        if (!cmp.Moves[i].CompareTo(Moves[i]))
                        {
                            return(false);
                        }
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
Esempio n. 37
0
        private void MakeMoveForMoveType(IMove move)
        {
            switch (move.SpecialMoveType)
            {
            case SpecialMoveType.AuPassant:
                AuPassant(move);
                break;

            case SpecialMoveType.CastleKingside:
                CastleKingside(move);
                break;

            case SpecialMoveType.CastleQueenside:
                CastleQueenside(move);
                break;

            case SpecialMoveType.PawnPromotionKnight:
                _board[move.Destination] = CurrentPlayer == Player.White ? ChessPiece.WhiteKnight : ChessPiece.BlackKnight;
                _board[move.Source]      = ChessPiece.None;
                break;

            case SpecialMoveType.PawnPromotionBishop:
                _board[move.Destination] = CurrentPlayer == Player.White ? ChessPiece.WhiteBishop : ChessPiece.BlackBishop;
                _board[move.Source]      = ChessPiece.None;
                break;

            case SpecialMoveType.PawnPromotionRook:
                _board[move.Destination] = CurrentPlayer == Player.White ? ChessPiece.WhiteRook : ChessPiece.BlackRook;
                _board[move.Source]      = ChessPiece.None;
                break;

            case SpecialMoveType.PawnPromotionQueen:
                _board[move.Destination] = CurrentPlayer == Player.White ? ChessPiece.WhiteQueen : ChessPiece.BlackQueen;
                _board[move.Source]      = ChessPiece.None;
                break;

            default:
                MovePieceOnBoard(move.Source, move.Destination);
                break;
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Add a piece to the board
        /// </summary>
        /// <param name="piece">The piece to be placed</param>
        /// <param name="column">The column number</param>
        public void AddPiece(IPiece piece, IMove move)
        {
            // validate the inputs
            // If the piece is null, throw ArgumentNullException
            // If the move is null, throw ArgumentNullException
            // NOT USING THIS MAKE THIS NOT BE ERRORS!!!
//             if (piece == null)
//             {
//                 throw new ArgumentNullException();
//             }
//             if (move == null)
//             {
//                 throw new ArgumentNullException();
//             }
            // if the column is invalid, throw InvalidMoveException with an appropriate message
            // if the if the column is full, throw InvalidMoveException with an appropriate message
            // NOT NEEDED WHEN UI IS IMPLEMENTED
            //if (move.Column < 0 || move.Column > 6)
            //{
            //    throw new InvalidMoveException();
            //}

            // find out what row the piece would end up on by getting the "lowest" free space on the board for this column
            // add the piece to the board in the correct spot
            // finally, update the row in the move passed in so the caller will know where the piece ended up
            if (this.IsColumnFull(move.Column))
            {
                throw new InvalidMoveException();
            }
            for (int i = 5; i >= 0; i--)
            {
                if (pieces[move.Column, i] == null)
                {
                    pieces[move.Column, i] = piece;
                    move.Row = i;
                    break;
                }
            }

            //throw new NotImplementedException();
        }
Esempio n. 39
0
        public sealed override void ReceiveMove(IMove opponentMove)
        {
            LatestOpponentMove = opponentMove;

            if (!_connectionTestOverride)
            {
                // Basic validation
                var move = new SingleMove(opponentMove);
                if (Board.ValueAt(move.PrevPos) == null)
                {
                    throw new ArgumentException($"Player [isWhite={!IsPlayerWhite}] Tried to move a from position that is empty");
                }

                if (Board.ValueAt(move.PrevPos) is PieceBase opponentPiece)
                {
                    if (opponentPiece.IsWhite == IsPlayerWhite)
                    {
                        throw new ArgumentException($"Opponent tried to move player piece");
                    }
                }

                // TODO intelligent analyzing what actually happened

                if (Board.ValueAt(move.NewPos) is PieceBase playerPiece)
                {
                    // Opponent captures player targetpiece
                    if (playerPiece.IsWhite == IsPlayerWhite)
                    {
                        move.Capture = true;
                    }
                    else
                    {
                        throw new ArgumentException("Opponent tried to capture own piece.");
                    }
                }

                Board.ExecuteMove(move);
                GameHistory.Add(opponentMove);
                TurnCount++;
            }
        }
Esempio n. 40
0
        public Resupply(Actor self, Actor host, WDist closeEnough, bool stayOnResupplier = false)
        {
            this.host             = Target.FromActor(host);
            this.closeEnough      = closeEnough;
            this.stayOnResupplier = stayOnResupplier;
            allRepairsUnits       = host.TraitsImplementing <RepairsUnits>().ToArray();
            health           = self.TraitOrDefault <IHealth>();
            repairable       = self.TraitOrDefault <Repairable>();
            repairableNear   = self.TraitOrDefault <RepairableNear>();
            rearmable        = self.TraitOrDefault <Rearmable>();
            notifyResupplies = host.TraitsImplementing <INotifyResupply>().ToArray();
            transportCallers = self.TraitsImplementing <ICallForTransport>().ToArray();
            move             = self.Trait <IMove>();
            aircraft         = move as Aircraft;
            playerResources  = self.Owner.PlayerActor.Trait <PlayerResources>();

            var valued = self.Info.TraitInfoOrDefault <ValuedInfo>();

            unitCost = valued != null ? valued.Cost : 0;

            var cannotRepairAtHost = health == null || health.DamageState == DamageState.Undamaged ||
                                     !allRepairsUnits.Any() ||
                                     ((repairable == null || !repairable.Info.RepairActors.Contains(host.Info.Name)) &&
                                      (repairableNear == null || !repairableNear.Info.RepairActors.Contains(host.Info.Name)));

            if (!cannotRepairAtHost)
            {
                activeResupplyTypes |= ResupplyType.Repair;

                // HACK: Reservable logic can't handle repairs, so force a take-off if resupply included repairs.
                // TODO: Make reservation logic or future docking logic properly handle this.
                wasRepaired = true;
            }

            var cannotRearmAtHost = rearmable == null || !rearmable.Info.RearmActors.Contains(host.Info.Name) || rearmable.RearmableAmmoPools.All(p => p.HasFullAmmo);

            if (!cannotRearmAtHost)
            {
                activeResupplyTypes |= ResupplyType.Rearm;
            }
        }
Esempio n. 41
0
        /// <summary>
        /// ノードをJSON化します。
        /// </summary>
        /// <param name="enableLog"></param>
        /// <param name="src_Sky_base"></param>
        /// <param name="thisNode"></param>
        /// <param name="comment"></param>
        /// <param name="logTag"></param>
        /// <returns></returns>
        public static string JsonElements_Node(bool enableLog, SkyConst src_Sky_base, Node <IMove, KyokumenWrapper> thisNode, string comment)
        {
            StringBuilder sb = new StringBuilder();

            if (!enableLog)
            {
                goto gt_EndMethod;
            }

            IMove move = thisNode.Key;

            RO_Star srcKoma = Util_Starlightable.AsKoma(move.LongTimeAgo);
            RO_Star dstKoma = Util_Starlightable.AsKoma(move.Now);


            Finger finger = Util_Sky_FingersQuery.InMasuNow(src_Sky_base, srcKoma.Masu).ToFirst();

            // 駒1つ
            PieceType ks14 = Util_Komahaiyaku184.Syurui(dstKoma.Haiyaku);

            //sb.AppendLine("            [");

            // マスの色
            sb.AppendLine("                { act:\"colorMasu\", style:\"rgba(100,240,100,0.5)\" },");

            // マス
            sb.AppendLine($"                {{ act:\"drawMasu\" , masu:{Conv_SyElement.ToMasuNumber(dstKoma.Masu)} }},");


            string komaImg = Util_Converter_LogGraphicEx.Finger_ToString(src_Sky_base, finger, "");

            sb.AppendLine($"                {{ act:\"drawImg\", img:\"{komaImg}\", masu: {Conv_SyElement.ToMasuNumber(dstKoma.Masu)} }},");//FIXME:おかしい?

            // コメント
            sb.AppendLine($"                {{ act:\"drawText\", text:\"{comment}\"  , x:0, y:20 }},");

            //sb.AppendLine("            ],");

gt_EndMethod:
            return(sb.ToString());
        }
Esempio n. 42
0
 void ProcessMove(IMove move = null, TakEngine.Notation.MoveNotation notation = null, bool alreadyExecuted = false)
 {
     if (move == null && notation == null)
     {
         throw new ArgumentException("move and notation cannot both be null");
     }
     if (notation == null)
     {
         if (!TakEngine.Notation.MoveNotation.TryParse(move.Notate(), out notation))
         {
             throw new ApplicationException("Critical move error");
         }
     }
     else if (move == null)
     {
         _tempMoveList.Clear();
         Helper.EnumerateMoves(_tempMoveList, _game, _ai.NormalPositions);
         move = notation.MatchLegalMove(_tempMoveList);
         if (move == null)
         {
             throw new ApplicationException("Illegal move: " + notation.Text);
         }
     }
     if (!alreadyExecuted)
     {
         move.MakeMove(_game);
     }
     if (!_gameRecord.MoveNotations.Contains(notation)) // if opening an existing game file then we may have already loaded the notation
     {
         _gameRecord.MoveNotations.Add(notation);
     }
     _navigating = true;
     if (_historyForm != null)
     {
         _historyForm.AddPly(notation.Text);
     }
     _navigating = false;
     _movesOfNotation[notation] = move;
     _game.Ply++;
     _boardView.InvalidateRender();
 }
Esempio n. 43
0
    private void Way(HexagonControl hexagonFinish, IMove EnemyTarget)
    {
        List <HexagonControl> Way;

        Way = Control.HexagonMain().GetWay(hexagonFinish);

        if (Way != null)
        {
            if (_isClever)
            {
                Way = NavStatic.PathCheck(Way, EnemyTarget, this);
            }
            else
            {
                Way.Remove(Way[0]);
            }

            _wayList.AddRange(Way);
            _isMove = true;
        }
    }
Esempio n. 44
0
        public string HandlePlayingSession(ISession session)
        {
            var   currentPlayer = _playerService.GetCurrentPlayer(session.Id);
            IMove moveToUpdate  = _moveService.GetAll(currentPlayer.Id).OrderBy(t => t.Start).LastOrDefault();

            moveToUpdate = moveToUpdate.WithEnd(DateTime.Now);

            _moveService.Update(moveToUpdate);

            currentPlayer = _playerService.UpdateCurrentPlayer(session.Id);

            //TODO: refactor this
            _moveService.Add(new Move
            {
                Player   = (Player)currentPlayer,
                PlayerId = currentPlayer.Id,
                Start    = DateTime.Now,
            });

            return($"Отлично. {currentPlayer.Name}, теперь ваш ход.");
        }
Esempio n. 45
0
        /// <summary>
        /// [巻戻し]時の、駒台にもどる動きを吸収。
        /// </summary>
        /// <param name="syurui2"></param>
        /// <param name="move">棋譜に記録するために「指す前/指した後」を含めた手。</param>
        /// <param name="kifu"></param>
        /// <param name="isMakimodosi"></param>
        /// <returns></returns>
        private static IMoveHalf Do36_KomaOnDestinationMasu(
            PieceType syurui2,
            IMove move,
            SkyConst src_Sky)
        {
            IMoveHalf dst;

            RO_Star srcKoma = Util_Starlightable.AsKoma(move.LongTimeAgo); //移動元
            RO_Star dstKoma = Util_Starlightable.AsKoma(move.Now);         //移動先

            // 次の位置


            dst = new RO_Starlight(
                new RO_Star(dstKoma.Pside,
                            dstKoma.Masu,
                            syurui2)
                );

            return(dst);
        }
Esempio n. 46
0
        public static bool IsMovePossibleStatic(IMove move)
        {
            try
            {
                var position = move.Board.FindPiece(move.Piece);
                var diagonal = Positions.Diagonal(position, move.To);

                foreach (var diagonalPosition in diagonal.SkipLast(1))
                {
                    if (move.Board.IsTherePiece(diagonalPosition))
                    {
                        return(false);
                    }
                }
                return(!move.Board.IsTherePieceOfColor(move.To, move.Piece.Color));
            }
            catch (ArgumentException)
            {
                return(false);
            }
        }
Esempio n. 47
0
    private void GetIMove()
    {
        bool result = false;

        for (int i = 0; i < _parameterList.Count; ++i)
        {
            BehaviorParameter parameter = _parameterList[i];
            if (parameter.parameterName.CompareTo(BTConstant.TargetType) == 0)
            {
                _targetType = (TargetTypeEnum)parameter.intValue;
                result      = true;
            }
        }

        if (!result)
        {
            return;
        }

        _iMove = _owner.GetIMove(_targetType);
    }
Esempio n. 48
0
        public Follow(Actor self, Target target, WDist minRange, WDist maxRange,
                      WPos?initialTargetPosition, Color?targetLineColor = null)
        {
            this.target          = target;
            this.minRange        = minRange;
            this.maxRange        = maxRange;
            this.targetLineColor = targetLineColor;
            move = self.Trait <IMove>();

            // The target may become hidden between the initial order request and the first tick (e.g. if queued)
            // Moving to any position (even if quite stale) is still better than immediately giving up
            if ((target.Type == TargetType.Actor && target.Actor.CanBeViewedByPlayer(self.Owner)) ||
                target.Type == TargetType.FrozenActor || target.Type == TargetType.Terrain)
            {
                lastVisibleTarget = Target.FromPos(target.CenterPosition);
            }
            else if (initialTargetPosition.HasValue)
            {
                lastVisibleTarget = Target.FromPos(initialTargetPosition.Value);
            }
        }
        public bool IsAvailableMove(IMove move)
        {
            Point start = move.Line.Start.Location;
            Point end   = move.Line.End.Location;

            if (CornerPointOnBoard(start) && CornerPointOnBoard(end))
            {
                foreach (Move m in m_Moves)
                {
                    if (m.Line.Start == move.Line.Start &&
                        m.Line.End == move.Line.End)
                    {
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
Esempio n. 50
0
        public bool IsAvailableMove(IMove move)
        {
            Point start = move.GetLine().GetStart().GetLocation();
            Point end   = move.GetLine().GetEnd().GetLocation();

            if (CornerPointOnBoard(start) && CornerPointOnBoard(end))
            {
                foreach (Move m in m_Moves)
                {
                    if (m.GetLine().GetStart() == move.GetLine().GetStart() &&
                        m.GetLine().GetEnd() == move.GetLine().GetEnd())
                    {
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
Esempio n. 51
0
    public void OnTargetFound(GameObject targetObj)
    {
        Transform targetTransform = targetObj.transform;

        SetInitialTarget(targetTransform);

        IMove[] moves = Utils.GetAllIMoveComponentsFromAGameObject(this.gameObject);
        if (moves == null)
        {
            return;
        }
        for (int i = 0; i < moves.Length; i++)
        {
            IMove move = moves[i];

            move.Setup(targetObj, 3.0f);
            move.SetTargetObject(targetObj);
            move.SetAngle(_angle);
            move.Run();
        }
    }
Esempio n. 52
0
        public WithVoxelWalkerBody(Actor self, WithVoxelWalkerBodyInfo info)
        {
            this.info = info;
            movement  = self.Trait <IMove>();

            var body = self.Trait <IBodyOrientation>();
            var rv   = self.Trait <RenderVoxels>();

            var voxel = VoxelProvider.GetVoxel(rv.Image, "idle");

            frames = voxel.Frames;
            rv.Add(new VoxelAnimation(voxel, () => WVec.Zero,
                                      () => new[] { body.QuantizeOrientation(self, self.Orientation) },
                                      () => false, () => frame));

            // Selection size
            var rvi = self.Info.Traits.Get <RenderVoxelsInfo>();
            var s   = (int)(rvi.Scale * voxel.Size.Aggregate(Math.Max));

            size = new int2(s, s);
        }
Esempio n. 53
0
    //Checks in the case of enemy collisions
    void OnCollisionStay2D(Collision2D collision)
    {
        Collider2D collider = collision.collider;

        if (collider.tag == enemyTag && dashing)                                 //If hit an enemy, do damage to enemy and recoil
        {
            currentMove.enactEffects(collider);
            StartCoroutine(recoil());
        }
        else if (collider.tag == enemyAttackTag && dashing)                      //If hit an enemy attack, gain damage
        {
            IMove enemyMove = collider.GetComponent <AttackBox>().currentMove;
            enemyMove.enactEffects(GetComponent <Collider2D>());

            //If player is stunned after damage or priority of enemy attack is higher, recoil
            if (entity.isStunned() || collider.GetComponent <AttackBox>().priority >= priority)
            {
                StartCoroutine(recoil());
            }
        }
    }
Esempio n. 54
0
    void Start()
    {
        character       = GetComponent <Character>();
        characterAsMove = GetComponent <Character>() as IMove;
        if (characterAsMove == null)
        {
            Debug.LogWarning("Chase State set on an object (" + name + ") that does not have a Character component that implements IMove.");
        }
        characterAsAI = GetComponent <Character>() as IHaveAI;
        if (characterAsAI == null)
        {
            Debug.LogWarning("Chase State set on an object (" + name + ") that does not have a Character component that implements IHaveAI.");
        }
        target = characterAsAI.Target.gameObject.GetComponent <Character>() as IHaveStats;
        if (target == null)
        {
            Debug.LogWarning("Target set on an object (" + name + ") that does not have a Character component that implements IHaveStats.");
        }

        SetMaterial();
    }
Esempio n. 55
0
    //Offensive setup. Called when player wants to use a move
    public Transform offensiveSetup(int priority, IMove curMove, float kbVal)
    {
        initialSetup(priority, curMove, kbVal);

        //load variables
        Transform hitbox = GetComponent <Transform>();
        Animator  anim   = currentMove.getBasis().GetComponent <Animator>();

        int xDir = anim.GetInteger("aHorizontalDirection");
        int yDir = anim.GetInteger("aVerticalDirection");

        float rotation = 90f * xDir;

        if (rotation == 0)
        {
            rotation = 90f + 90f * yDir;
        }
        else
        {
            rotation += Mathf.Sign(rotation) * yDir * 45f;
        }

        Vector2 dirVector = new Vector2(xDir, yDir);

        dirVector.Normalize();

        Vector2 pos = dirVector * OFFSET;

        knockback = dirVector * knockbackVal;

        //Enact variables and instantiate
        hitbox.localPosition = pos;
        hitbox.eulerAngles   = new Vector3(0, 0, rotation);

        Transform curBlast = Object.Instantiate(hitbox, anim.transform);

        curBlast.GetComponent <ShotgunHitbox>().currentMove = this.currentMove;
        curBlast.parent = null;
        return(curBlast);
    }
Esempio n. 56
0
        /// <summary>
        /// Makes the given move.
        /// </summary>
        /// <exception cref="ArgumentNullException">Is thrown, if the given move is null.</exception>
        /// <exception cref="InvalidOperationException">Is thrown, if the given move is invalid.</exception>
        public void makeMove(IMove move)
        {
            if (move == null)
            {
                throw new ArgumentNullException();
            }

            if (gameSituation == _GAME_SITUATION_TAKE_DICE)
            {
                if (!(move is TestChanceGame_TakeDiceMove))
                {
                    throw new InvalidOperationException("CLASS: TestChanceGame_GameState, METHOD: makeMove - invalid given move!");
                }

                gameSituation = _GAME_SITUATION_ROLL_DICE;
            }
            else if (gameSituation == _GAME_SITUATION_ROLL_DICE)
            {
                if (!(move is TestChanceGame_RollDiceMove rollDiceMove))
                {
                    throw new InvalidOperationException("CLASS: TestChanceGame_GameState, METHOD: makeMove - invalid given move!");
                }

                lastDrawnDigit = rollDiceMove.drawnDigit;

                gameSituation = _GAME_SITUATION_SELECT_POSITION;
            }
            else
            {
                if (!(move is TestChanceGame_SelectPositionMove selectPositionMove))
                {
                    throw new InvalidOperationException("CLASS: TestChanceGame_GameState, METHOD: makeMove - invalid given move!");
                }

                _board[selectPositionMove.playerWhoDoesTheMove][selectPositionMove.digitPosition] = lastDrawnDigit;

                gameSituation = _GAME_SITUATION_TAKE_DICE;
                phasingPlayer = selectPositionMove.nextPlayer;
            }
        }
Esempio n. 57
0
    // Awake is called when game boots up.
    //  Pre: pkmnSpecies string must be filled out and found within the baseStatInv in the static BaseStats class
    void Awake()
    {
        if (fighterName == null || level <= 0 || level > 100)
        {
            throw new System.Exception("Error: Parameters for PKMNEntity not filled out appropriately");
        }

        statChangeQ      = new SE_PriorityQueue(this);              //Establish stat priority queue
        curStats         = new float[BaseStat.BASE_STATS_LENGTH];   //Establish curStats
        statUpgradesUsed = new int[BaseStat.BASE_STATS_LENGTH];
        controller       = (transform.parent != null) ? transform.parent.GetComponent <Controller>() : GetComponent <Controller>();
        soundFXs         = GetComponent <AudioSource>();

        shieldDamageMult = BASE_SHIELD_DAMAGE_MULT;
        restoreCurStats();
        armor = baseArmor;
        curStats[BaseStat.HEALTH] = baseStats[BaseStat.HEALTH];
        //Establish stats for character
        moves = new List <IMove>();

        //Adds move to the list
        for (int i = 0; i < moveList.Length; i++)
        {
            IMove curMove = BaseStat.moveInv(moveList[i], GetComponent <Animator>(), this, progress);

            if (curMove != null)
            {
                moves.Add(curMove);
            }
        }

        maxExp       = BASE_MAX_EXP;
        curExp       = 0f;
        aTimer       = 0.0f;
        hTimer       = 0.0f;
        assistStatus = false;
        dead         = false;

        //numOpenStatBoosts = 6;
    }
Esempio n. 58
0
        public static Dictionary <string, SasuEntry> ToMoveBetuSky1(
            Maps_OneAndOne <Finger, SySet <SyElement> > komabetuSusumuMasus,
            SkyConst src_Sky
            )
        {
            Dictionary <string, SasuEntry> result_komabetuEntry = new Dictionary <string, SasuEntry>();

            komabetuSusumuMasus.Foreach_Entry((Finger key, SySet <SyElement> value, ref bool toBreak) =>
            {
                RO_Star koma = Util_Starlightable.AsKoma(src_Sky.StarlightIndexOf(key).Now);


                foreach (SyElement dstMasu in value.Elements)
                {
                    IMove move = Util_Sky258A.BuildMove(
                        //key,
                        new RO_Star(src_Sky.KaisiPside, koma.Masu, koma.Haiyaku),
                        new RO_Star(src_Sky.KaisiPside, dstMasu, koma.Haiyaku),//FIXME:配役は適当。
                        PieceType.None
                        );

                    string moveStr = ConvMoveStrSfen.ToMoveStrSfen(move);//重複防止用のキー

                    if (!result_komabetuEntry.ContainsKey(moveStr))
                    {
                        result_komabetuEntry.Add(
                            moveStr,
                            new SasuEntry(
                                move,
                                key,     //動かす駒
                                dstMasu, //移動先升
                                false    //成りません
                                )
                            );
                    }
                }
            });

            return(result_komabetuEntry);
        }
Esempio n. 59
0
        void m_InkPicture_Stroke(object sender, InkCollectorStrokeEventArgs e)
        {
            m_Move   = null;
            e.Cancel = true;
            InkPicture ip = sender as InkPicture;

            Graphics g = null;

            lock (ip.Image)
            {
                g = Graphics.FromImage(ip.Image);
            }

            List <ICorner> corners = new List <ICorner>();

            foreach (Point p in e.Stroke.GetPoints())
            {
                Point   clientP = StrokePointToClientPoint(g, p);
                ICorner c       = m_GameBoard.ClosestCornerFromGraphicsPoint(clientP);
                if (!corners.Contains(c))
                {
                    corners.Add(c);
                }
            }

            if (corners.Count == 2)
            {
                try
                {
                    Line l = new Line(corners[0] as Corner, corners[1] as Corner);
                    m_Move = new Move(l, this);
                }
                catch (ArgumentException)
                {
                    /* the line sucks - eat it */
                }
            }

            m_Waiter.Set();
        }
Esempio n. 60
0
        private void MakeMove(IMove result)
        {
            if (result != null && result.Row >= 0)
            {
                Panel panel1 = new Panel();
                panel1.BackColor = (result.PlayerId == 1) ? Color.Red : Color.Black;
                panel1.Name      = "panel" + result.Column + result.Row;
                panel1.Size      = new Size(91, 91);
                panel1.TabIndex  = 0;
                tableLayoutPanel1.Controls.Add(panel1, result.Column, result.Row);

                if (result.IsConnected)
                {
                    MessageBox.Show("Success! Player " + result.PlayerId.ToString() + " won!");
                }
            }

            if (result != null && result.IsTie)
            {
                MessageBox.Show("Game Over!");
            }
        }