public AGSSliderComponent(IGameState state, IInput input, IGameEvents gameEvents) { _state = state; _input = input; _gameEvents = gameEvents; OnValueChanged = new AGSEvent<SliderValueEventArgs> (); }
public static void SetGameState(IGameState newState) { if (_currentState != null){ throw new Exception("gamestate has to be cleared before setting a new state"); } _currentState = newState; }
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(); }
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); }
protected override void execute() { _log = Context.Get<IScriptLog>(); _gameState = Context.Get<IGameState>(); Pause(Token); }
public void Start(Game game) { this.game = game; FirstTurn firstturn = new FirstTurn(); this.NewState = firstturn; NewState.Enter(this); }
public override void SpecificHandle(IGameState previous, IGameState next) { //if (!_optionMenuControls.IsCheckBoxAvailable()) // return; var checkboxCopy = _optionMenuControls.CreateCheckboxCopy(); }
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; }
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; }
public override void SpecificHandle(IGameState previous, IGameState next) { //if (!_optionMenuControls.IsSliderAvailable()) // return; var sliderCopy = _optionMenuControls.CreateSliderCopy(); }
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()); }
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; } }
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; } } } }
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; }
public override void Rollback(IGameState state) { var s = state as ChessState; s.Castling = _Castling; RollbackMovePiece(From, To, state); RollbackMovePiece(RookFrom, RookTo, state); }
/// <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); }
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); }; }
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(); }
public AGSDialogFactory(IContainer resolver, IGameState gameState, IUIFactory ui, IObjectFactory obj) { _resolver = resolver; _gameState = gameState; _ui = ui; _object = obj; }
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); }
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); }
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; }
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()); } }
public int CalculateScore(IGameState state) { return(_output); }
public SomeObject(IGameState gameState) { _gameState = gameState; }
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); }
/// <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()); } }
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)); }
public void NextState() { IGameState newState = this.m_ActiveState.GetNextState(); this.ChangeState(newState); }
public static MiniMaxNode GenerateFromGameState(IGameState state) { return(new MiniMaxNode(state)); }
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; }
public abstract Func <T> GenerateChildFunction(IAction aAction, IGameState aState);
public void Start() { this.Active = true; this.m_ActiveState = new MainMenuState(); this.m_ActiveState.Start(); }
/// <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; }
public virtual T GetChildWithState(IGameState aStateToMatch) { return(Children.Where(c => c.NodeState.Equals(aStateToMatch)).FirstOrDefault()); }
public void ChangedTo(IGameState newState) { }
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++; }
public IGameMove FindBestMove(IGameState gameState, GamePlayer player) { Dictionary <String, Int32> ratesMap = new Dictionary <String, Int32>(); return(FindBestMoveImpl(gameState, player, ratesMap)); }
public void ChangedFrom(IGameState oldState) { Load(); }
object IEvaluatable.Evaluate(IGameState gameState) => Evaluate(gameState);
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); }
/// <summary>Evaluate the operand and return the absolute value of it.</summary> public double Evaluate(IGameState gameState) => Math.Abs(Operand.Evaluate(gameState));
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); }
public (int, IEnumerable <TMove>) Lookup( IGameState <TMove> gameState, Func <IGameState <TMove>, (int, IEnumerable <TMove>)> producer) =>
/// <summary>Simply returns the constant value specified by the user</summary> public double Evaluate(IGameState gameState) => Value;