public AGSSliderComponent(IGameState state, IInput input, IGameEvents gameEvents)
		{
			_state = state;
			_input = input;
			_gameEvents = gameEvents;
			OnValueChanged = new AGSEvent<SliderValueEventArgs> ();
		}
示例#2
0
 public static void SetGameState(IGameState newState)
 {
     if (_currentState != null){
         throw new Exception("gamestate has to be cleared before setting a new state");
     }
     _currentState = newState;
 }
示例#3
0
		public AGSUIFactory(IContainer resolver, IGameState gameState, IGraphicsFactory graphics, IObjectFactory obj)
		{
			_resolver = resolver;
			_gameState = gameState;
			_graphics = graphics;
			_object = obj;
		}
        public bool consumeEvent(IEvent e)
        {
            if (currentState.getTransitionableState().Keys.Contains(e.getEventName()))
            {
                LOG.Info("Consuming game event name=" + e.getEventName());
                this.currentState = (IGameState)this.currentState.getTransitionableState()[e.getEventName()];
                this.currentState.run(e);
                return true;
            }
            else if (currentState.isSubmachineEvent(e))
            {
                // Transport event to submachine like PlayerMachine or BoardMachine
                LOG.Info("Transport submachine event with name=" + e.getEventName());
                try
                {
                    currentState.submachineConsumeEvent(e);
                }
                catch (EventNotAcceptableException ex)
                {
                    return false;
                }
                return true;
            }
            else
            {
                // Reject unvalid event
                LOG.Info("Unvalid event in current state (" + this.currentState.getStateName() + ") event name=" + e.getEventName());
                return false;
            }

        }
 public static void ReturnToLastState()
 {
     currentState.LeaveState();
     if (!lastState.IsReady)
         lastState.EnterState();
     nextState = lastState;
 }
 public PauseMenu(IGameState prevGameState, Game1 game)
 {
     this.game = game;
     this.prevGameState = prevGameState;
     currentSelection = Selections.Resume;
     font = MenuSpriteFactory.CreateHUDFont();
 }
示例#7
0
 protected override void OnLoad(EventArgs args)
 {
     _curr = new IntroState(new FPS.Game.PlayState());
     _curr.Init(this);
     //Misc
     _timer = new Stopwatch();
 }
		public AGSInventoryWindowComponent(IGameState state, IGameEvents gameEvents)
		{
			_state = state;
			_inventoryItems = new List<IObject> (20);
			_gameEvents = gameEvents;
			_gameEvents.OnRepeatedlyExecute.Subscribe(onRepeatedlyExecute);
		}
示例#9
0
        protected override void execute()
        {
            _log = Context.Get<IScriptLog>();
            _gameState = Context.Get<IGameState>();

            Pause(Token);
        }
示例#10
0
 public void Start(Game game)
 {
     this.game = game;
     FirstTurn firstturn = new FirstTurn();
     this.NewState = firstturn;
     NewState.Enter(this);
 }
示例#11
0
        public override void SpecificHandle(IGameState previous, IGameState next)
        {
            //if (!_optionMenuControls.IsCheckBoxAvailable())
            //    return;

            var checkboxCopy = _optionMenuControls.CreateCheckboxCopy();
        }
示例#12
0
 public override void Become(IGameState prevState)
 {
     PuzzleBoardViewModel.StartPauseButtonCaption = "Game Over :-)";
     PuzzleBoardViewModel.PauseTimer();
     PuzzleBoardViewModel.FireGameCompleteMessage();
     base.Become(prevState);
 }
 public DoublePipe(IGameState gameState, Game1 game)
 {
     myGame = game;
     pipeSprite = TileSpriteFactory.CreateDoublePipeSprite();
     isWarpPipe = true;
     this.gameState = gameState;
 }
示例#14
0
文件: MyBot.cs 项目: Lapixx/CS-UU-KI2
        public State CalculateState(Location a, IGameState state)
        {
            State s = new State();
            Location l;
            Tile t;
            for (int x = -radius; x <= radius; x++)
            {
                for (int y = -radius; y <= radius; y++)
                {
                    if (x == 0 && y == 0)
                        continue;

                    l = (a + new Location(y, x)) % new Location(state.Height, state.Width);
                    t = state[l];
                    if (t == Tile.Ant)
                    {
                        if(state.MyAnts.Contains(new Ant(l.Row, l.Col, state.MyAnts[0].Team)))
                            s.MyAnt = true;
                        else
                            s.EnemyAnt = true;
                    }
                    else if (t == Tile.Food)
                        s.Food = true;
                    else if (t == Tile.Hill)
                    {
                        if (state.MyHills.Contains(new AntHill(l.Row, l.Col, state.MyHills[0].Team)))
                            s.MyHill = true;
                        else
                            s.EnemyHill = true;
                    }
                }
            }
            s.AirSuperiority = state.MyAnts.Count > state.EnemyAnts.Count;
            return s;
        }
示例#15
0
        public override void SpecificHandle(IGameState previous, IGameState next)
        {
            //if (!_optionMenuControls.IsSliderAvailable())
            //    return;

            var sliderCopy = _optionMenuControls.CreateSliderCopy();
        }
示例#16
0
        public override TankUpdate Update(IGameState gameState)
        {
            // Pick a random goal to defend
            if (_goalToDefend == null && gameState.Goals.Count > 0)
            {
                var shuffledGoals = gameState.Goals.OrderBy(a => Guid.NewGuid());
                _goalToDefend = shuffledGoals.First();
            }

            TankUpdate tankUpdate = new TankUpdate();

            if (gameState.Foes.Any() && gameState.Goals.Any())
            {
                if (_targetFoe == null || _targetFoe.Health <= 0)
                {
                    // Pick a random target
                    var shuffledFoes = gameState.Foes.OrderBy(a => Guid.NewGuid());
                    _targetFoe = shuffledFoes.First();
                }

                if (_targetFoe != null)
                {
                    // Target the foe's current location
                    tankUpdate.ShotTarget = _targetFoe.Center;
                }

                // Move toward tower
                tankUpdate.MovementTarget = LocationProvider.GetLocation(_goalToDefend.X, _goalToDefend.Y);
                tankUpdate.Bullet = new Bullet { Damage = 200, Freeze = 0, SplashRange = 0 };
            }

            return tankUpdate;
        }
        public GameStateManager( Game game )
        {
            _game = game;

            _gameStates = new Dictionary<string,IGameState>();
            _currentGameState = null;
        }
    public void GameOver()
    {
        _currentGameState = null;

        _camEffects.JAMMERIntensity = 2;
        _camEffects.RelativeSpeed = 0;
        Player.enabled = false;

        Player.OnCollision -= OnPlayerCollision;
        Player.OnBeingHit -= OnPlayerBeingHit;

        _hud.Unsub();

        Spawner.ForeachLiveObject((x) =>
        {
            x.RelativeSpeed = 0;
        });

        foreach (var item in _jammers)
        {
            item.RelativeSpeed = 0;
        }

        StartCoroutine(OnDeathCoroutine());
    }
示例#19
0
        public void Update(Camera camera, GameTime gameTime, ref IGameState gameState)
        {
            _turnAround ^= _serpents.Camera.KeyboardState.IsKeyPressed(Keys.Down);

            SerpentCamera.Move(gameTime);
            _serpents.Update(camera, gameTime);
            _serpents.UpdateScore();
            //camera.UpdateFreeFlyingCamera(gameTime);

            switch (_serpents.GameStatus())
            {
                case Serpents.Result.LevelComplete:
                    _delayAfterLevelComplete += (float) gameTime.ElapsedGameTime.TotalSeconds;
                    if (_delayAfterLevelComplete > 3)
                    {
                        _serpents.PlayerSerpent.DirectionTaker = null;
                        gameState = new LevelCompleteState(_serpents);
                    }
                    break;

                case Serpents.Result.PlayerDied:
                    _serpents.PlayerSerpent.DirectionTaker = null;
                    gameState = new DieState(_serpents);
                    break;
            }
        }
示例#20
0
        private static void DrawGridCells(IGameState state)
        {
            GL.LineWidth(5.0f);
            var deltaX = 2.0f / (float)state.GridWidth;
            var deltaY = 2.0f / (float)state.GridHeight;
            var cell = new Box2D(0, 0, deltaX, deltaY);
            for (int u = 0; u < state.GridWidth; ++u)
            {
                for (int v = 0; v < state.GridHeight; ++v)
                {
                    cell.X = deltaX * u - 1.0f;
                    cell.Y = 1.0f - deltaY * (v + 1);
                    switch (state[u, v])
                    {
                        case FieldType.DIAMONT:
                            DrawDiamont(cell);
                            break;
                        case FieldType.CROSS:
                            DrawCross(cell);
                            break;
                        default: break;
                    }

                }
            }
        }
示例#21
0
        public override TankUpdate Update(IGameState gameState)
        {
            TankUpdate tankUpdate = new TankUpdate();

            if (gameState.Foes.Any() && gameState.Goals.Any())
            {
                tankUpdate.ShotTarget = LocationProvider.GetLocation(_xTarget, _yTarget);
                ChangeBulletPower(tankUpdate.ShotTarget, gameState);

                var range = GetDistanceFromTank(LocationProvider.GetLocation(_xTarget, _yTarget)) + 1;
                if (Bullet.GetReloadTime((int)range) < 1000 || range < 100)
                {
                    tankUpdate.Bullet = Bullet;
                }
                else
                {
                    tankUpdate.Bullet = new Bullet();
                }

                UpdateMovementTarget(tankUpdate, gameState);
            }

            tankUpdate.TankColor = ConvertColorToHexString(Color.CornflowerBlue);

            return tankUpdate;
        }
示例#22
0
 public override void Rollback(IGameState state)
 {
     var s = state as ChessState;
     s.Castling = _Castling;
     RollbackMovePiece(From, To, state);
     RollbackMovePiece(RookFrom, RookTo, state);
 }
示例#23
0
 /// <summary>
 /// Removes the current running state and insert the state provide.
 /// </summary>
 /// <param name="gameState">State of the game.</param>
 public void ChangeState(IGameState gameState)
 {
     PopStack();
     
     gameState.LoadContent();
     _gameStates.Push(gameState);
 }
示例#24
0
        public AGSInteractions (IInteractions defaultInteractions, IObject obj, IGameState state)
		{
            _events = new ConcurrentDictionary<string, IEvent<ObjectEventArgs>>();
            _inventoryEvents = new ConcurrentDictionary<string, IEvent<InventoryInteractEventArgs>>();
            var defaultInteractionEvent = new AGSInteractionEvent<ObjectEventArgs>(
                new List<IEvent<ObjectEventArgs>>(), DEFAULT, obj, state);
            var defaultInventoryEvent = new AGSInteractionEvent<InventoryInteractEventArgs>(
                new List<IEvent<InventoryInteractEventArgs>>(), DEFAULT, obj, state);
            _events.TryAdd(DEFAULT, defaultInteractionEvent);
            _inventoryEvents.TryAdd(DEFAULT, defaultInventoryEvent);

            _factory = verb =>
            {
                List<IEvent<ObjectEventArgs>> interactions = new List<IEvent<ObjectEventArgs>> { defaultInteractionEvent };
                if (defaultInteractions != null)
                {
                    interactions.Add(defaultInteractions.OnInteract(verb));
                    if (verb != DEFAULT) interactions.Add(defaultInteractions.OnInteract(DEFAULT));
                }
                return new AGSInteractionEvent<ObjectEventArgs>(interactions, verb, obj, state);
            };
            _inventoryFactory = verb =>
            {
                List<IEvent<InventoryInteractEventArgs>> interactions = new List<IEvent<InventoryInteractEventArgs>> { defaultInventoryEvent };
                if (defaultInteractions != null)
                {
                    interactions.Add(defaultInteractions.OnInventoryInteract(verb));
                    if (verb != DEFAULT) interactions.Add(defaultInteractions.OnInventoryInteract(DEFAULT));
                }
                return new AGSInteractionEvent<InventoryInteractEventArgs>(interactions, verb, obj, state);
            };
		}
示例#25
0
        static void handleNewGameState()
        {
            switch (currentGameState)
            {
                case GameState.None:
                    running = false;
                    break;

                case GameState.MainMenu:
                    state = new MainMenuState();
                    break;

                case GameState.InGame:
                    state = new InGameState();
            //        win.SetTitle("Shøøp" + " score{" + InGameState.WinCount0 + " : " + InGameState.WinCount1 + ")");
                    break;

                case GameState.Reset:
                    currentGameState = prevGameState;
                    prevGameState = GameState.Reset;
                    handleNewGameState();
                    break;
            }

            prevGameState = currentGameState;

            resetView();
        }
示例#26
0
		public AGSDialogFactory(IContainer resolver, IGameState gameState, IUIFactory ui, IObjectFactory obj)
		{
			_resolver = resolver;
			_gameState = gameState;
			_ui = ui;
			_object = obj;
		}
示例#27
0
        public ITrade HandleTrade(IGameState state, ITrade offer, int proposingPlayerId)
        {
            // accept if convert extras to needed and opponent < 7 points
            List<Resource> extras = new List<Resource>();
            foreach (Resource r in Enum.GetValues(typeof(Resource)))
            {
                int extra = state.GetOwnResources().Count(res => res == r) - 1;
                for (int i = 0; i < extra; i++) extras.Add(r);
            }

            // good offer?
            var valid = offer.Give.Where(o => o.All(r => o.Count(cur => cur == r) <= extras.Count(e => e == r)));

            if (valid.Count() == 0) return offer.Decline();

            // take the one with least cards to give, and then by most duplicates
            List<Resource> bestGive = valid.OrderBy(o => o.Count)
                .ThenByDescending(o => state.GetOwnResources().Sum(r => state.GetOwnResources().Count(res => res == r)))
                .First();

            // find best "take" (cards we get) kind of the opposite of above
            List<Resource> bestTake = offer.Take.OrderBy(o => o.Count)
                .ThenBy(o => state.GetOwnResources().Sum(r => state.GetOwnResources().Count(res => res == r)))
                .First();

            return offer.Respond(bestGive, bestTake);
        }
示例#28
0
        public RoomState(IGameState previousState, IGameStateService gameStateService, IGuiService guiService,
                        IInputService inputService, GraphicsDeviceManager graphics,
                        ContentManager content)
        {
            this.gameStateService = gameStateService;
            this.guiService = guiService;
            this.inputService = inputService;
            this.graphics = graphics;
            this.content = content;

            this.previousState = previousState;
            this.mouseMove = new MouseMoveDelegate(mouseMoved);

            this.teamA = new List<Peer>();
            this.teamB = new List<Peer>();

            playerIDLabels = new List<LabelControl>();
            panelVisibility = new List<bool>();
            roomScreen = new Screen(1184, 682);

            Game1.main_console.StartEvent += Start;

            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

            LoadContent(roomScreen, content);
        }
示例#29
0
        public override TankUpdate Update(IGameState gameState)
        {
            TankUpdate tankUpdate = new TankUpdate();
            tankUpdate.TankColor = ConvertColorToHexString(Color.Blue);

            if (gameState.Foes.Any() && gameState.Goals.Any())
            {
                var target = gameState.Foes
                    .Where(foe => 1000 / GetDistanceFromTank(foe) >= 2)
                    .OrderBy(foe => GetDistanceToGoal(foe, gameState.Goals) + GetTimeToGoal(foe, gameState.Goals) + GetDistanceFromTank(foe))
                    .FirstOrDefault();

                if (target != null)
                {
                    tankUpdate.ShotTarget = target.Center;
                    ChangeBulletPower(target);
                    tankUpdate.Bullet = Bullet;
                }

                var x = (gameState.Foes.Max(foe => foe.X) + 9 * gameState.Goals.Last().X) / 10;
                var y = (gameState.Foes.Max(foe => foe.Y) + 9 * gameState.Goals.Last().Y) / 10;
                tankUpdate.MovementTarget = LocationProvider.GetLocation(x, y);
            }

            return tankUpdate;
        }
示例#30
0
 public InformState(string message, IGameState nextstate, Color color, bool isCard = false)
 {
     this.message = message;
     this.nextState = nextstate;
     this.color = color;
     this.isCard = isCard;
 }
        private Int32 FindMoveScore(IGameState gameState, GamePlayer currentPlayer, Int32 depth, Int32 alfa, Int32 beta)
        {
            if (depth <= 0 || _gameLogic.IsFinished(gameState))
            {
                return(_stateEvaluator.Evaluate(gameState, currentPlayer));
            }

            IGameMove[] moves = _gameLogic.GetPossibleMoves(gameState, currentPlayer);

            if (moves.Length <= 0)
            {
                //// there are no more possible moves to analyse, so return current state evaluation

                return(_stateEvaluator.Evaluate(gameState, currentPlayer));
            }

            if (currentPlayer == GamePlayer.PlayerMax)
            {
                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), depth - 1, alfa, beta);

                    alfa = Math.Max(alfa, moveScore);

                    if (alfa >= beta)
                    {
                        break;
                    }
                }

                return(alfa);
            }
            else if (currentPlayer == GamePlayer.PlayerMin)
            {
                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), depth - 1, alfa, beta);

                    beta = Math.Min(beta, moveScore);

                    if (alfa >= beta)
                    {
                        break;
                    }
                }

                return(beta);
            }
            else
            {
                throw new NotSupportedException(currentPlayer.ToString());
            }
        }
示例#32
0
 public int CalculateScore(IGameState state)
 {
     return(_output);
 }
 public SomeObject(IGameState gameState)
 {
     _gameState = gameState;
 }
示例#34
0
        public void PlayHand(IGameState gameState, Func <ICard> chooseHumanCard)
        {
            //play a hand
            //ignoring loners for now
            for (var i = 0; i < 5; i++)
            {
                //play a trick
                for (var j = 0; j < 4; j++)
                {
                    ICard chosenCard = null;

                    if (gameState.CurrentPlayer.IsHuman)
                    {
                        chosenCard = chooseHumanCard();

                        gameState.CurrentHand.Add(new PlayedCard
                        {
                            Player = gameState.CurrentPlayer,
                            Card   = chosenCard
                        });

                        gameState.CurrentPlayer.Cards.Remove(chosenCard);
                    }
                    else
                    {
                        chosenCard = gameState.CurrentPlayer.ChooseCardToPlay(gameState);

                        gameState.CurrentHand.Add(new PlayedCard
                        {
                            Player = gameState.CurrentPlayer,
                            Card   = chosenCard
                        });

                        OnAiPlayedCard?.Invoke(this, new AiPlayedCardEventArgs(chosenCard));

                        gameState.CurrentPlayer.Cards = gameState.CurrentPlayer.Cards.ToList().Except(new List <ICard> {
                            chosenCard
                        }).ToList();
                    }

                    if (gameState.LeadSuit == null)
                    {
                        if (chosenCard.IsTheLeft(gameState.Trump))
                        {
                            gameState.LeadSuit = CardHelper.GetOppositeSuit(chosenCard.Suit);
                        }
                        else
                        {
                            gameState.LeadSuit = chosenCard.Suit;
                        }
                    }

                    gameState.AdvanceToNextPlayer();
                }

                _evaluateTrick(gameState);
                gameState.CurrentHand.Clear();
                gameState.LeadSuit = null;
            }

            _evaluateHand(gameState);

            foreach (var player in gameState.Players)
            {
                player.TricksTaken = 0;
            }
        }
        private static void AddSelection(Game1 game, KeyboardController keyboard, GamepadController gamepad, IGameState state)
        {
            ICommand upSelection = new UpSelection(state);

            keyboard.Add((int)Keys.Up, upSelection);
            gamepad.Add((int)Buttons.DPadUp, upSelection);

            ICommand downSelection = new DownSelection(state);

            keyboard.Add((int)Keys.Down, downSelection);
            gamepad.Add((int)Buttons.DPadDown, downSelection);

            ICommand select = new MadeSelection(game, state);

            keyboard.Add((int)Keys.Enter, select);
            gamepad.Add((int)Buttons.A, select);
        }
        public static void PauseControllers(Game1 game, KeyboardController keyboard, GamepadController gamepad, IGameState state)
        {
            keyboard.ClearDictionary();
            gamepad.ClearDictionary();


            ICommand unpause = new UnpauseCommand();

            keyboard.Add((int)Keys.P, unpause);
            gamepad.Add((int)Buttons.X, unpause);
            //Add the Exit Command to the controllers
            ICommand exitcommand = new ExitCommand(game);

            keyboard.Add((int)Keys.Q, exitcommand);
            gamepad.Add((int)Buttons.Start, exitcommand);
            ICommand resetcommand = new RestartCommand();

            keyboard.Add((int)Keys.R, resetcommand);
            gamepad.Add((int)Buttons.Back, resetcommand);
            AddSelection(game, keyboard, gamepad, state);
        }
示例#37
0
 /// <summary>
 /// Switches to the given state and calls its invoke() method.
 /// </summary>
 public void ChangeState(IGameState newGameState)
 {
     currentState = newGameState;
     currentState?.InvokeState();
 }
        private IGameMove FindBestMoveImpl(IGameState gameState, GamePlayer currentPlayer)
        {
            IGameMove[] moves = _gameLogic.GetPossibleMoves(gameState, currentPlayer);

            if (moves.Length <= 0)
            {
                return(null);
            }

            Int32 alfa = Int32.MinValue;

            Int32 beta = Int32.MaxValue;

            IGameMove selectedMove = null;

            if (currentPlayer == GamePlayer.PlayerMax)
            {
                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), _depth - 1, alfa, beta);

                    if (moveScore > alfa || selectedMove == null)
                    {
                        alfa         = moveScore;
                        selectedMove = nextMove;
                    }

                    if (alfa >= beta)
                    {
                        break;
                    }
                }

                return(selectedMove);
            }
            else if (currentPlayer == GamePlayer.PlayerMin)
            {
                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), _depth - 1, alfa, beta);

                    if (moveScore < beta || selectedMove == null)
                    {
                        beta         = moveScore;
                        selectedMove = nextMove;
                    }

                    if (alfa >= beta)
                    {
                        break;
                    }
                }

                return(selectedMove);
            }
            else
            {
                throw new NotSupportedException(currentPlayer.ToString());
            }
        }
示例#39
0
        public void Update(List <IGameComponent> components, IGameState gameState)
        {
            IShowState currentState = _router.CurrentState;

            foreach (IGameComponent component in components)
            {
                bool previousActiveState = (component.IsActive == true);
                if (component.IsActive)
                {
                    component.Update(gameState);
                }
                // update active status
                if (component.ActiveUnderState == "Root" || currentState.IsCalled(component.ActiveUnderState))
                {
                    component.IsActive = true;
                }
                else
                {
                    component.IsActive = false;
                }
                // specific cases
                if (component is StoryComponent)
                {
                    if (component.IsActive)
                    {
                        if ((component as StoryComponent).Choosing)
                        {
                            _router.RouteTo("Reading/Choosing");
                            _router.SetRedirect("Reading", 1);
                        }
                        _refreshEditing = (component as StoryComponent).NewConversation;
                        _currLine       = (component as StoryComponent).CurrentLine;
                    }
                }
                if (component is ChoiceComponent)
                {
                    if (component.IsActive)
                    {
                        if ((component as ChoiceComponent).Chosen)
                        {
                            _router.RouteTo("Reading/Story");
                            _router.SetRedirect("Reading", 0);
                        }
                    }
                }
                if (component is PersonalityComponent)
                {
                    if (_refreshEditing)
                    {
                        (component as PersonalityComponent).RefreshActive();
                    }
                }
                if (component is GraphicComponent)
                {
                    (component as GraphicComponent).CurrentLine = _currLine;
                }
                // setup if reactivated
                if (component.IsActive && !previousActiveState)
                {
                    component.Setup(gameState);
                }
            }
        }
 public IGameMove FindBestMove(IGameState gameState, GamePlayer player)
 {
     return(FindBestMoveImpl(gameState, player));
 }
示例#41
0
        public void NextState()
        {
            IGameState newState = this.m_ActiveState.GetNextState();

            this.ChangeState(newState);
        }
示例#42
0
 public static MiniMaxNode GenerateFromGameState(IGameState state)
 {
     return(new MiniMaxNode(state));
 }
示例#43
0
        public override void DoTurn(IGameState state)
        {
            // Match Init
            if (++turn == 1)
            {
            }

            try
            {
                // Turn init
                gameState = state;
                antDestinations.Clear();
                guards.Clear();
                foreach (var hill in gameState.MyHills)
                {
                    guards.Add(hill, gameState.MyAnts.FindAll(ant => gameState.GetRealDistance2(hill, ant) <= 2));
                }

                // Once we have enough ants, protect hills agains wild Jonathans
                if (gameState.MyAnts.Count > (gameState.MyHills.Count * MIN_ANTS_PER_HILL_BEFORE_GUARDING_HILLS))
                {
                    foreach (var hill in gameState.MyHills)
                    {
                        // Is there an ant on the hill?
                        var antOnHill = gameState.MyAnts.Find(x => x.IsAt(hill));
                        if (antOnHill != null)
                        {
                            // First, try to fill an empty adjacent spot
                            if (!HasImmediateGuard(hill, out Direction emptyImmediateSpot))
                            {
                                IssueOrderOrThrow(antOnHill, emptyImmediateSpot);
                            }
                            // Second, try to push a guard to fill all 8 spots
                            else if (!HasFullGuard(hill, out Direction8 emptyDiagonalSpot))
                            {
                                gameState.FindClosest(gameState.GetDestination(hill, emptyDiagonalSpot), guards[hill], out Location guardPostToReplace, out List <Direction> path);

                                IssueOrderOrThrow(guards[hill].Find(x => x.IsAt(guardPostToReplace)), path.Single().Flip());
                                IssueOrderOrThrow(antOnHill, gameState.GetDirections(antOnHill, guardPostToReplace).Single());
                            }
                            // Else, push one guard away
                            else
                            {
                                foreach (Direction direction in Enum.GetValues(typeof(Direction)))
                                {
                                    var guard = gameState.MyAnts.Find(x => x.IsAt(gameState.GetDestination(antOnHill, direction)));
                                    if (guard == null)
                                    {
                                        continue;
                                    }
                                    var hasMoved = TryIssueOrder(guard, direction);
                                    if (hasMoved)
                                    {
                                        IssueOrderOrThrow(antOnHill, direction);
                                        guards[hill].Remove(guard);
                                        break;
                                    }
                                }
                            }
                        }

                        foreach (var guard in guards[hill])
                        {
                            DontMove(guard);
                        }
                    }
                }

                // Food is #1 priority. Make sure all food is assigned to an ant
                foreach (var food in gameState.FoodTiles)
                {
                    // check if we have time left to calculate more orders
                    if (gameState.TimeRemaining < 10)
                    {
                        break;
                    }

                    if (gameState.FindClosest(food, gameState.MyAnts.Select(x => x as Location), out var closestAnt, out var path))
                    {
                        var assignee = gameState.MyAnts.Find(x => x.IsAt(closestAnt));
                        // Path is from food to ant, need to reverse direction
                        TryIssueOrder(assignee, path.Last().Flip());
                    }
                }

                // If no food in sight, move along
                foreach (Ant ant in gameState.MyAnts.Where(x => !x.HasOrder))
                {
                    // check if we have time left to calculate more orders
                    if (gameState.TimeRemaining < 10)
                    {
                        break;
                    }

                    MoveAlong(ant);
                }
            }
            catch (Exception e)
            {
                Log.Error($"Error at turn {turn}: {e}");
            }
        }
 public AGSScrollingComponent(IGameState state)
 {
     _state = state;
 }
示例#45
0
 public abstract Func <T> GenerateChildFunction(IAction aAction, IGameState aState);
示例#46
0
 public void Start()
 {
     this.Active        = true;
     this.m_ActiveState = new MainMenuState();
     this.m_ActiveState.Start();
 }
示例#47
0
 /// <summary>
 /// A copy constructor, creates a GameState instance based on the data from the passed GameState instance.
 /// </summary>
 /// <param name="other_state">The passed GameState</param>
 public GameState(IGameState other_state) : base()
 {
     _ParsedData = other_state._ParsedData;
     json        = other_state.json;
 }
示例#48
0
 public virtual T GetChildWithState(IGameState aStateToMatch)
 {
     return(Children.Where(c => c.NodeState.Equals(aStateToMatch)).FirstOrDefault());
 }
示例#49
0
 public void ChangedTo(IGameState newState)
 {
 }
示例#50
0
 public AGSCollider(IGameState state)
 {
     _state = state;
 }
 public AnswersConfirmedGameState(IGameState previousState) : base(previousState)
 {
     Answers = previousState?.Answers.Shuffle().ToList() ?? Enumerable.Empty <Answer>();
 }
 public override void OnApply(IGameState gameState)
 {
     gameState.Money++;
 }
示例#53
0
        public IGameMove FindBestMove(IGameState gameState, GamePlayer player)
        {
            Dictionary <String, Int32> ratesMap = new Dictionary <String, Int32>();

            return(FindBestMoveImpl(gameState, player, ratesMap));
        }
示例#54
0
 public void ChangedFrom(IGameState oldState)
 {
     Load();
 }
示例#55
0
 object IEvaluatable.Evaluate(IGameState gameState) => Evaluate(gameState);
示例#56
0
        private Int32 FindMoveScore(IGameState gameState, GamePlayer currentPlayer, Int32 depth, Int32 alfa, Int32 beta, Dictionary <String, Int32> ratesMap)
        {
            Int32 result;

            if (depth <= 0 || _gameLogic.IsFinished(gameState))
            {
                result = _stateEvaluator.Evaluate(gameState, currentPlayer);

                //Console.WriteLine();

                //Console.WriteLine(result);

                //Console.WriteLine(gameState.ToString());

                //Console.WriteLine();

                //ratesMap[gameState.Key] = result;

                return(result);
            }

            IGameMove[] moves = _gameLogic.GetPossibleMoves(gameState, currentPlayer);

            if (moves.Length <= 0)
            {
                //// there are no more possible moves to analyse, so return current state evaluation

                result = _stateEvaluator.Evaluate(gameState, currentPlayer);

                //ratesMap[gameState.Key] = result;

                return(result);
            }

            if (currentPlayer == GamePlayer.PlayerMax)
            {
                Int32 maxMoveScore = Int32.MinValue;

                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 rawMoveScore;

                    if (!ratesMap.TryGetValue(newState.Key, out rawMoveScore))
                    {
                        rawMoveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), depth - 1, alfa, beta, ratesMap);
                    }
                    else
                    {
                    }

                    Int32 moveScore = (Int32)(rawMoveScore * FutureDiscount);

                    maxMoveScore = Math.Max(maxMoveScore, moveScore);

                    alfa = Math.Max(alfa, maxMoveScore);

                    if (beta <= alfa)
                    {
                        break;
                    }
                }

                // ratesMap[gameState.Key] = maxMoveScore;

                result = maxMoveScore;
            }
            else if (currentPlayer == GamePlayer.PlayerMin)
            {
                Int32 minMoveScore = Int32.MaxValue;

                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 rawMoveScore;

                    if (!ratesMap.TryGetValue(newState.Key, out rawMoveScore))
                    {
                        rawMoveScore = FindMoveScore(newState, OtherPlayer(currentPlayer), depth - 1, alfa, beta, ratesMap);
                    }
                    else
                    {
                    }

                    Int32 moveScore = (Int32)(rawMoveScore * FutureDiscount);

                    minMoveScore = Math.Min(minMoveScore, moveScore);

                    beta = Math.Min(beta, minMoveScore);

                    if (beta <= alfa)
                    {
                        break;
                    }
                }

                // ratesMap[gameState.Key] = minMoveScore;

                result = minMoveScore;
            }
            else
            {
                throw new NotSupportedException(currentPlayer.ToString());
            }

            return(result);
        }
示例#57
0
 /// <summary>Evaluate the operand and return the absolute value of it.</summary>
 public double Evaluate(IGameState gameState) => Math.Abs(Operand.Evaluate(gameState));
示例#58
0
        private IGameMove FindBestMoveImpl(IGameState gameState, GamePlayer currentPlayer, Dictionary <String, Int32> ratesMap)
        {
            IGameMove[] moves = _gameLogic.GetPossibleMoves(gameState, currentPlayer);

            if (moves.Length <= 0)
            {
                return(null);
            }

            Int32 alfa = Int32.MinValue;

            Int32 beta = Int32.MaxValue;

            IGameMove selectedMove = null;

            //Console.WriteLine();

            if (currentPlayer == GamePlayer.PlayerMax)
            {
                Int32 maxMoveScore = Int32.MinValue;

                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = (Int32)(FindMoveScore(newState, OtherPlayer(currentPlayer), _depth - 1, alfa, beta, ratesMap) * FutureDiscount);

                    //Console.WriteLine("{0} ", moveScore);

                    //Console.WriteLine(newState.ToString());

                    if (moveScore > alfa || selectedMove == null)
                    {
                        maxMoveScore = Math.Max(maxMoveScore, moveScore);

                        alfa = Math.Max(alfa, maxMoveScore);

                        selectedMove = nextMove;
                    }

                    if (alfa >= beta)
                    {
                        break;
                    }
                }
            }
            else if (currentPlayer == GamePlayer.PlayerMin)
            {
                Int32 minMoveScore = Int32.MaxValue;

                for (Int32 q = 0; q < moves.Length; q++)
                {
                    IGameMove nextMove = moves[q];

                    IGameState newState = _gameLogic.MakeMove(nextMove, gameState);

                    Int32 moveScore = (Int32)(FindMoveScore(newState, OtherPlayer(currentPlayer), _depth - 1, alfa, beta, ratesMap) * FutureDiscount);

                    //Console.WriteLine("{0} ", moveScore);

                    //Console.WriteLine(newState.ToString());

                    if (moveScore < beta || selectedMove == null)
                    {
                        minMoveScore = Math.Min(minMoveScore, moveScore);

                        beta = Math.Min(beta, minMoveScore);

                        selectedMove = nextMove;
                    }

                    if (alfa >= beta)
                    {
                        break;
                    }
                }
            }
            else
            {
                throw new NotSupportedException(currentPlayer.ToString());
            }

            //Console.WriteLine();

            return(selectedMove);
        }
示例#59
0
 public (int, IEnumerable <TMove>) Lookup(
     IGameState <TMove> gameState,
     Func <IGameState <TMove>, (int, IEnumerable <TMove>)> producer) =>
示例#60
0
 /// <summary>Simply returns the constant value specified by the user</summary>
 public double Evaluate(IGameState gameState) => Value;