private void MoveToPostion() { _lastMoveResult = NavExtensions.NavigateTo(Position); if (_lastMoveResult == MoveResult.PathGenerationFailed) { Logger.Log("Error moving to offset x={0} y={1} distance={2:0} position={3}", OffsetX, OffsetY, Position.Distance2D(MyPos), Position); _isDone = true; } }
internal override void PostMove(MoveResult mv, Position2D pos) { base.PostMove(mv, pos); if (mv == MoveResult.CannotMoveLivingEntityInTheWay) { var targetEntity = FadingWorldsGameWindow.Instance.TheGrid.GetBlockAt(pos).Entities.LivingEntity as LivingEntity; if (targetEntity != null && (this is Player)) { //FadingWorldsGameWindow.Instance.TheLoader.connectionLoop.SendCommand("at|" + targetEntity.Id + "|" + // targetEntity.Position.X + "|" + // targetEntity.Position.Y); FadingWorldsGameWindow.Instance.TheLoader.ConnectionLoop.SendPayload(new NetworkPayload { Type = PayloadType.Attack, Params = { targetEntity.Id, ""+targetEntity.Position.X, ""+targetEntity.Position.Y } }); } } }
private void MoveToPostion() { lastMoveResult=Funky.PlayerMover.NavigateTo(Position); if (lastMoveResult==MoveResult.PathGenerationFailed) { isDone=true; } }
// private DateTime lastGeneratedPath=DateTime.MinValue; /// <summary> /// Moves the bot to the next DungeonExplorer node /// </summary> private void MoveToNextNode() { NextNode=BrainBehavior.DungeonExplorer.CurrentNode; Vector3 moveTarget=NextNode.NavigableCenter; string nodeName=String.Format("{0} Distance: {1:0} Direction: {2}", NextNode.NavigableCenter, NextNode.NavigableCenter.Distance(FunkyTrinity.Bot.Character.Position), GetHeadingToPoint(NextNode.NavigableCenter)); //Special cache for skipping locations visited. if (Bot.SettingsFunky.SkipAhead) SkipAheadCache.RecordSkipAheadCachePoint(PathPrecision); LastMoveResult=Navigator.MoveTo(CurrentNavTarget); }
/// <summary> /// Move from cell a to cell b, return time and state /// </summary> /// <param name="cellFrom"></param> /// <param name="cellTo"></param> /// <returns></returns> MoveResult TryMove(Cell from, Cell to, int waterLevel) { MoveResult result = new MoveResult(0, MoveState.CannotMove); if (from.Ceiling - Math.Max(to.Floor, waterLevel) >= 50 || to.Ceiling - Math.Max(from.Floor, waterLevel) >= 50) { if (waterLevel >= from.Floor + 20) { result.Time = 1; result.State = MoveState.KayakWithouWait; } else { result.Time = 10; result.State = MoveState.DragWithouWait; } } else { if (waterLevel >= from.Floor && to.Ceiling - from.Floor >= 50) { result.Time= ((waterLevel - (to.Ceiling - 50)) / 10) + ((to.Ceiling - from.Floor >= 70) ? 1 : 10); result.State = (to.Ceiling - from.Floor >= 70) ? MoveState.KayakWithWait : MoveState.DragWithWait; } else { result.Time = 0; result.State = MoveState.CannotMove; } } return result; }
public bool Follow(bool run, int range) { Point3D goal = GetGoalLocation(); Direction d; if (Check(m_From.Location, goal, range)) { return(true); } bool repathed = CheckPath(); if (!Enabled || !m_Path.Success) { d = m_From.GetDirectionTo(goal); if (run) { d |= Direction.Running; } m_From.SetDirection(d); Move(d); return(Check(m_From.Location, goal, range)); } d = m_From.GetDirectionTo(m_Next); if (run) { d |= Direction.Running; } m_From.SetDirection(d); MoveResult res = Move(d); if (res == MoveResult.Blocked) { if (repathed) { return(false); } m_Path = null; CheckPath(); if (!m_Path.Success) { d = m_From.GetDirectionTo(goal); if (run) { d |= Direction.Running; } m_From.SetDirection(d); Move(d); return(Check(m_From.Location, goal, range)); } d = m_From.GetDirectionTo(m_Next); if (run) { d |= Direction.Running; } m_From.SetDirection(d); res = Move(d); if (res == MoveResult.Blocked) { return(false); } } if (m_From.X == m_Next.X && m_From.Y == m_Next.Y) { if (m_From.Z == m_Next.Z) { ++m_Index; Advance(ref m_Next, m_Index); } else { m_Path = null; } } return(Check(m_From.Location, goal, range)); }
public bool Follow(bool run, int range) { Point3D goal = this.GetGoalLocation(); Direction d; if (this.Check(this.m_From.Location, goal, range)) { return(true); } bool repathed = this.CheckPath(); if (!Enabled || !this.m_Path.Success) { d = this.m_From.GetDirectionTo(goal); if (run) { d |= Direction.Running; } this.m_From.SetDirection(d); this.Move(d); return(this.Check(this.m_From.Location, goal, range)); } d = this.m_From.GetDirectionTo(this.m_Next); if (run) { d |= Direction.Running; } this.m_From.SetDirection(d); MoveResult res = this.Move(d); if (res == MoveResult.Blocked) { if (repathed) { return(false); } this.m_Path = null; this.CheckPath(); if (!this.m_Path.Success) { d = this.m_From.GetDirectionTo(goal); if (run) { d |= Direction.Running; } this.m_From.SetDirection(d); this.Move(d); return(this.Check(this.m_From.Location, goal, range)); } d = this.m_From.GetDirectionTo(this.m_Next); if (run) { d |= Direction.Running; } this.m_From.SetDirection(d); res = this.Move(d); if (res == MoveResult.Blocked) { return(false); } } if (this.m_From.X == this.m_Next.X && this.m_From.Y == this.m_Next.Y) { if (this.m_From.Z == this.m_Next.Z) { ++this.m_Index; this.Advance(ref this.m_Next, this.m_Index); } else { this.m_Path = null; } } return(this.Check(this.m_From.Location, goal, range)); }
/// <summary> /// Called when [start]. /// </summary> public override void OnStart() { // set defaults if (Math.Abs(PathPrecision) < 1f) PathPrecision = 20; if (PathPointLimit == 0) PathPointLimit = 250; if (Math.Abs(InteractRange) < 1f) InteractRange = 10; if (InteractAttempts == 0) InteractAttempts = 5; if (FailedAttemptMax <= 0) FailedAttemptMax = 1; _lastMoveResult = MoveResult.Moved; _completedInteractAttempts = 0; _startWorldId = ZetaDia.CurrentWorldId; Navigator.Clear(); Logger.Debug("Initialized {0}", Status()); }
public static bool IsDoneMoving(this MoveResult moveResult) { return(moveResult == MoveResult.Done || moveResult == MoveResult.ReachedDestination || moveResult == MoveResult.Failed || moveResult == MoveResult.Failure || moveResult == MoveResult.PathGenerationFailed); }
public void HandleMoveResult(MoveResult result) { }
/// <summary> /// Initializes a new instance of the <see cref="MoveFinishedEventArgs"/> class. /// </summary> public MoveFinishedEventArgs(MoveResult result) { Result = result; }
public override void ResetCachedDone() { _isDone = false; _lastGeneratedNavPoint = DateTime.MinValue; _lastMoveResult = MoveResult.Moved; _tagStartTime = DateTime.MinValue; CurrentObject = null; }
public override void OnStart() { if (PathPrecision == 0) PathPrecision = 15; if (Timeout == 0) Timeout = 180; _lastGeneratedNavPoint = DateTime.MinValue; _lastMoveResult = MoveResult.Moved; _tagStartTime = DateTime.UtcNow; UpdateObject(); //PositionCache.Cache.Clear(); Navigator.Clear(); Logger.DBLog.DebugFormat("Initialized {0}", Status()); }
void Update() { if (Input.GetButtonDown("Fire1")) { if (!m_PlayerList.ContainsKey(m_MyPlayerID)) { // not receive join return; } Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit)) { // send to server my move GameObject myPlayer = m_PlayerList[m_MyPlayerID]; PlayerController myPlayerControl = myPlayer.GetComponent <PlayerController>(); Vector3 rayPos = hit.point; Vector3 vector = transform.position - rayPos; Vector3 normal = vector.normalized; float angle = NormalAngle(normal); angle -= 90; try { MoveRequest moveRequestPay = new MoveRequest(); moveRequestPay.m_PlayerID = myPlayerControl.m_PlayerID; moveRequestPay.m_PosX = rayPos.x; moveRequestPay.m_PosY = rayPos.y; moveRequestPay.m_PosZ = rayPos.z; moveRequestPay.m_Angle = angle; moveRequestPay.m_Speed = myPlayerControl.m_Speed; string requestPayload = JsonFx.Json.JsonWriter.Serialize(moveRequestPay); NetworkManager.GetInstance().SendPacket(PacketTypes.PKT_CS_MOVE, requestPayload); } catch (Exception e) { Debug.LogError(e); } } } if (joinList.Count > 0) { JoinResult packet = joinList[0]; //Debug.Log("X:"+packet.m_PosX+" Y:"+packet.m_PosY+" Z:"+ packet.m_PosZ); if (packet.m_PlayerID == -4444) { foreach (GameObject player in m_PlayerList.Values) { Destroy(player); } m_PlayerList.Clear(); joinList.RemoveAt(0); return; } Vector3 pos = new Vector3(packet.m_PosX, packet.m_PosY, packet.m_PosZ); Vector3 rot = new Vector3(0.0f, packet.m_Angle, 0.0f); float speed = packet.m_Speed; int playerID = packet.m_PlayerID; GameObject newPlayer = Instantiate(m_PlayerObject, pos, Quaternion.Euler(rot)) as GameObject; PlayerController newPlayerControl = newPlayer.GetComponent <PlayerController>(); newPlayerControl.m_Speed = speed; newPlayerControl.m_PlayerID = playerID; m_PlayerList.Add(playerID, newPlayer); joinList.RemoveAt(0); } if (moveList.Count > 0) { MoveResult packet = moveList[0]; try { GameObject player = m_PlayerList[packet.m_PlayerID]; PlayerController playerControl = player.GetComponent <PlayerController>(); playerControl.AddMoveResult(packet); } catch (Exception e) { //no character sync Debug.LogError(e); } moveList.RemoveAt(0); } }
public void AddMoveResult(MoveResult packet) { moveList.Add(packet); Debug.Log("AddMoveResult!:" + packet.m_PlayerID); }
bool RequestFleePath(Vector3 fromPosition) { if (_movementType != MoveTypes.FleePathing) { return false; } if (!_seeker.IsDone()) { return false; } _moveResult = MoveResult.Preparing; var fp = FleePath.Construct(transform.position, fromPosition, 2000); fp.aim = (transform.position - fromPosition)*10; fp.aimStrength = 5f; _seeker.StartPath(fp, OnPathCompleted); return true; }
public MoveResult FleeFrom(Vector3 position) { _movementType = MoveTypes.FleePathing; if (_lastRequestedMoveTargetPosition != position) { _pathToTarget.Clear(); _moveResult = MoveResult.Preparing; _lastRequestedMoveTargetPosition = position; if (!RequestFleePath(position)) { _lastRequestedMoveTargetPosition = transform.position; } } return _moveResult; }
public MoveResult MoveFleet(MoveRequest request) { var result = new MoveResult(); // non-zero ships if(request.NumberOfShips <= 0) { result.Success = false; result.Message = "Can't send a zero fleet"; return result; } var validSourcePlanets = _getPlanetsForPlayer(request.AuthToken); // A planet of the requested source ID exists, belongs to that planer, AND it has enough ships var sourceValid = validSourcePlanets.FirstOrDefault(p => p.Id == request.SourcePlanetId && request.NumberOfShips <= p.NumberOfShips); // A planet of the requested destination ID exists var destinationValid = _planets.FirstOrDefault(p => p.Id == request.DestinationPlanetId); if (sourceValid != null && destinationValid != null) { lock (synclock) { // Subtract ships from planet sourceValid.NumberOfShips -= request.NumberOfShips; // Build fleet var newFleet = new Fleet() { Id = _MAXFLEETID++, OwnerId = _authTokenToId(request.AuthToken), Source = sourceValid, Destination = destinationValid, NumberOfShips = request.NumberOfShips, NumberOfTurnsToDestination = (int)Math.Ceiling(sourceValid.Position.Distance(destinationValid.Position)) }; _fleets.Add(newFleet); result.Fleet = Mapper.Map<Shared.Fleet>(newFleet); result.Success = true; } } else { result.Success = false; result.Message = "Invalid move command, check if the planet of the requested source/dest ID exists, belongs to that player, AND it has enough ships."; } return result; }
/// <summary> /// Main MoveToMapMarker Behavior /// </summary> /// <returns></returns> protected override Composite CreateBehavior() { return (new Sequence( new DecoratorContinue(ret => ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld, new Sequence( new Action(ret => Logger.Log("IsDead={0} IsLoadingWorld={1}", ZetaDia.Me.IsDead, ZetaDia.IsLoadingWorld)), new Action(ret => RunStatus.Failure) ) ), CheckTimeout(), new Action(ret => FindMiniMapMarker()), new DecoratorContinue(ret => _miniMapMarker != null, new Action(ret => RefreshActorInfo()) ), //new DecoratorContinue(ret => _interactObject == null && _miniMapMarker == null && Position == Vector3.Zero, // new Sequence( // new Action(ret => _miniMapMarker = GetRiftExitMarker()) // ) //), new DecoratorContinue(ret => _interactObject == null && _miniMapMarker == null && Position == Vector3.Zero, new Sequence( new Action(ret => Logger.Debug("Error: Could not find MiniMapMarker nor PortalObject nor Position {0}", Status())), new Action(ret => _isDone = true) ) ), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination && _interactObject == null, new Sequence( new Action(ret => Logger.Log("ReachedDestination, no object found - finished!")), new Action(ret => _isDone = true), new Action(ret => RunStatus.Failure) ) ), new Sequence( new Action(ret => GameUI.SafeClickUIButtons()), new PrioritySelector( new Decorator(ret => GameUI.IsPartyDialogVisible, new Action(ret => Logger.Log("Party Dialog is visible")) ), new Decorator(ret => GameUI.IsElementVisible(GameUI.GenericOK), new Action(ret => Logger.Log("Generic OK is visible")) ), new Decorator(ret => DestinationWorldId == -1 && ZetaDia.CurrentWorldId != _startWorldId, new Sequence( new Action(ret => Logger.Log("World changed ({0} to {1}), destinationWorlId={2}, finished {3}", _startWorldId, ZetaDia.CurrentWorldId, DestinationWorldId, Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => DestinationWorldId != 0 && ZetaDia.CurrentWorldId == DestinationWorldId, new Sequence( new Action(ret => Logger.Log("DestinationWorlId matched, finished {0}", Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => _completedInteractAttempts > 1 && _lastPosition.Distance(ZetaDia.Me.Position) > 4f && DestinationWorldId != _startWorldId, new Sequence( new Action(ret => _isDone = true), new Action(ret => Logger.Log("Moved {0:0} yards after interaction, finished {1}", _lastPosition.Distance(ZetaDia.Me.Position), Status())) ) ), new Decorator(ret => _interactObject != null && _interactObject.IsValid, new PrioritySelector( new Decorator(ret => _lastMoveResult != MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Debug("Moving to actor {0} {1}", _interactObject.ActorSNO, Status())), new Action(ret => _lastMoveResult = Navigator.MoveTo(_interactObject.Position)) ) ), new Decorator(ret => _lastMoveResult == MoveResult.ReachedDestination && _interactObject.Distance > InteractRange, new Sequence( new Action(ret => Logger.Log("ReachedDestination but not within InteractRange, finished")), new Action(ret => _isDone = true) ) ), new Decorator(ret => ZetaDia.Me.Movement.IsMoving, new Action(ret => CommonBehaviors.MoveStop())), new Sequence( new Action(ret => _lastPosition = ZetaDia.Me.Position), new Action(ret => _interactObject.Interact()), new Action(ret => _completedInteractAttempts++), new Action(ret => Logger.Debug("Interacting with portal object {0}, result: {1}", _interactObject.ActorSNO, Status())), new Sleep(500), new Action(ret => GameEvents.FireWorldTransferStart()) ) ) ), new Decorator(ret => _miniMapMarker != null && _interactObject == null, new PrioritySelector( new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) > PathPrecision, new Sequence( new Action(ret => Logger.Debug("Moving to Map Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new Action(ret => _lastMoveResult = Navigator.MoveTo(_miniMapMarker.Position)) ) ), new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) < PathPrecision, new Sequence( new Action(ret => Logger.Debug("Successfully Moved to Map Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new Action(ret => _isDone = true) ) ) ) ), new Decorator(ret => _miniMapMarker == null && Position != Vector3.Zero, new Sequence( new Action(ret => _lastMoveResult = Navigator.MoveTo(Position)), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Log("ReachedDestination of Position, finished.")), new Action(ret => _isDone = true) ) ) ) ), new Action(ret => Logger.LogError("MoveToMapMarker Error: marker={0} actor={1}/{2} completedInteracts={3} isPortal={4} dist={5} interactRange={6}", _miniMapMarker != null, _interactObject != null, (_interactObject != null && _interactObject.IsValid), _completedInteractAttempts, IsPortal, (_interactObject != null ? _interactObject.Position.Distance(ZetaDia.Me.Position) : 0f), InteractRange)) ) ) )); }
private void Move_GameFinished_NoMovePossible() { // arrange #region Moves of a finished Game var movesForFinishedGame = new List <Move> { new Move { Player = Player.Cross, BoardPosition = new Position(0, 0), TilePosition = new Position(0, 0), MoveNumber = 1 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 0), TilePosition = new Position(2, 0), MoveNumber = 2 }, new Move { Player = Player.Cross, BoardPosition = new Position(2, 0), TilePosition = new Position(0, 2), MoveNumber = 3 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 2), TilePosition = new Position(2, 0), MoveNumber = 4 }, new Move { Player = Player.Cross, BoardPosition = new Position(2, 0), TilePosition = new Position(0, 1), MoveNumber = 5 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 1), TilePosition = new Position(2, 0), MoveNumber = 6 }, new Move { Player = Player.Cross, BoardPosition = new Position(2, 0), TilePosition = new Position(0, 0), MoveNumber = 7 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 0), TilePosition = new Position(1, 0), MoveNumber = 8 }, new Move { Player = Player.Cross, BoardPosition = new Position(1, 0), TilePosition = new Position(2, 2), MoveNumber = 9 }, new Move { Player = Player.Circle, BoardPosition = new Position(2, 2), TilePosition = new Position(0, 0), MoveNumber = 10 }, new Move { Player = Player.Cross, BoardPosition = new Position(0, 0), TilePosition = new Position(0, 1), MoveNumber = 11 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 1), TilePosition = new Position(0, 0), MoveNumber = 12 }, new Move { Player = Player.Cross, BoardPosition = new Position(0, 0), TilePosition = new Position(0, 2), MoveNumber = 13 }, new Move { Player = Player.Circle, BoardPosition = new Position(0, 2), TilePosition = new Position(1, 0), MoveNumber = 14 }, new Move { Player = Player.Cross, BoardPosition = new Position(1, 0), TilePosition = new Position(2, 0), MoveNumber = 15 }, new Move { Player = Player.Circle, BoardPosition = new Position(1, 1), TilePosition = new Position(1, 0), MoveNumber = 16 }, new Move { Player = Player.Cross, BoardPosition = new Position(1, 0), TilePosition = new Position(2, 1), MoveNumber = 17 } }; #endregion var game = new TicTacToeGame(movesForFinishedGame); // act MoveResult result = game.Move(new Move { Player = Player.Circle, BoardPosition = new Position(2, 1), TilePosition = new Position(2, 1), MoveNumber = 18 }); // assert result.IsValid.Should().BeFalse(); result.InvalidReason.Should().Be(ExceptionMessages.GameFinished); }
/// <summary> /// Safely Moves the player to the requested destination <seealso cref="MoveToObjectiveTag.PathPointLimit" /> /// </summary> /// <param name="newpos">Vector3 of the new position</param> /// <param name="destinationName">For logging purposes</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private bool Move(Vector3 newpos, string destinationName = "") { bool result = false; if (StraightLinePathing) { Navigator.PlayerMover.MoveTowards(newpos); _lastMoveResult = MoveResult.Moved; result = true; } if (_clientNavFailed && PathPointLimit > 20) { PathPointLimit = PathPointLimit - 10; } else if (_clientNavFailed && PathPointLimit <= 20) { PathPointLimit = 250; } if (newpos.Distance(ZetaDia.Me.Position) > PathPointLimit) { newpos = MathEx.CalculatePointFrom(ZetaDia.Me.Position, newpos, newpos.Distance(ZetaDia.Me.Position) - PathPointLimit); var endposDistance = _mapMarkerLastPosition.Distance(ZetaDia.Me.Position); Logger.Log("Plotting closer point: {0}{5} Distance={1} on path to {2}{6} Distance={3} (PPL:{4})", newpos, newpos.Distance(ZetaDia.Me.Position), _mapMarkerLastPosition, endposDistance, PathPointLimit, ProfileUtils.CanPathToLocation(newpos) ? " (Navigable)" : string.Empty, ProfileUtils.CanPathToLocation(_mapMarkerLastPosition) ? " (Navigable)" : string.Empty ); } float destinationDistance = newpos.Distance(ZetaDia.Me.Position); _lastMoveResult = _qtNavigator.MoveTo(newpos, destinationName + String.Format(" distance={0:0}", destinationDistance)); switch (_lastMoveResult) { case MoveResult.Moved: case MoveResult.ReachedDestination: case MoveResult.UnstuckAttempt: _clientNavFailed = false; result = true; break; case MoveResult.PathGenerated: case MoveResult.PathGenerating: case MoveResult.PathGenerationFailed: case MoveResult.Failed: Navigator.PlayerMover.MoveTowards(Position); result = false; _clientNavFailed = true; break; } if (QuestTools.EnableDebugLogging) { Logger.Debug("MoveResult: {0}, newpos={1} Distance={2}, destinationName={3}", _lastMoveResult.ToString(), newpos, newpos.Distance(ZetaDia.Me.Position), destinationName); } return result; }
public override void MoveIllegal(MoveResult moveResult) { throw new Exception("This should never be called."); }
private RunStatus GotoPool(WoWGameObject pool) { if (_lastPoolGuid != pool.Guid) { MoveToPoolSW.Reset(); MoveToPoolSW.Start(); _lastPoolGuid = pool.Guid; if (!FindPoolPoint(pool) || PoolPoints.Count == 0) { Utils.BlacklistPool(pool, TimeSpan.FromDays(1), "Found no landing spots"); return(RunStatus.Success);// return sucess so Behavior stops and starts at begining on next tick. } } // should never be true.. but being safe.. if (PoolPoints.Count == 0) { Utils.BlacklistPool(pool, TimeSpan.FromDays(1), "Pool landing points mysteriously disapear..."); return(RunStatus.Success);// return sucess so Behavior stops and starts at begining on next tick. } TreeRoot.StatusText = "Moving to " + pool.Name; if (_me.Location.Distance(PoolPoints[0]) > 3) { _movetoConcludingSW.Reset(); if (!MoveToPoolSW.IsRunning) { MoveToPoolSW.Start(); } if (_me.IsSwimming) { if (_me.GetMirrorTimerInfo(MirrorTimerType.Breath).CurrentTime > 0) { WoWMovement.Move(WoWMovement.MovementDirection.JumpAscend); } else if (_me.MovementInfo.IsAscending || _me.MovementInfo.JumpingOrShortFalling) { WoWMovement.MoveStop(WoWMovement.MovementDirection.JumpAscend); } } if (AutoAngler.Instance.MySettings.Fly) { // don't bother mounting up if we can use navigator to walk over if it's less than 25 units away if (_me.Location.Distance(PoolPoints[0]) < 25 && !_me.Mounted) { MoveResult moveResult = Navigator.MoveTo(PoolPoints[0]); if (moveResult == MoveResult.Failed || moveResult == MoveResult.PathGenerationFailed) { Flightor.MountHelper.MountUp(); } else { return(RunStatus.Success); } } else if (!_me.Mounted && !SpellManager.GlobalCooldown) { Flightor.MountHelper.MountUp(); } Flightor.MoveTo(WoWMathHelper.CalculatePointFrom(_me.Location, PoolPoints[0], -1f)); } else { if (!StyxWoW.Me.Mounted && Mount.ShouldMount(PoolPoints[0]) && Mount.CanMount()) { Mount.MountUp(() => PoolPoints[0]); } MoveResult moveResult = Navigator.MoveTo(PoolPoints[0]); if (moveResult == MoveResult.UnstuckAttempt || moveResult == MoveResult.PathGenerationFailed || moveResult == MoveResult.Failed) { if (!RemovePointAtTop(pool)) { return(RunStatus.Success); } AutoAngler.Instance.Debug("Unable to path to pool point, switching to a new point"); PoolPoints.Sort((a, b) => a.Distance(_me.Location).CompareTo(b.Distance(_me.Location))); } } // if it takes more than 25 seconds to get to a point remove that point and try another. if (MoveToPoolSW.ElapsedMilliseconds > 25000) { if (!RemovePointAtTop(pool)) { return(RunStatus.Failure); } MoveToPoolSW.Reset(); MoveToPoolSW.Start(); } return(RunStatus.Success); } // allow small delay so clickToMove can run its course before dismounting. better landing precision.. if (!_movetoConcludingSW.IsRunning) { _movetoConcludingSW.Start(); } if (_movetoConcludingSW.ElapsedMilliseconds < 1500) { if (_me.Location.Distance2D(PoolPoints[0]) > 0.5) { WoWMovement.ClickToMove(PoolPoints[0]); } return(RunStatus.Success); } if (_me.Mounted) { if (_me.Class == WoWClass.Druid && (_me.Shapeshift == ShapeshiftForm.FlightForm || _me.Shapeshift == ShapeshiftForm.EpicFlightForm)) { Lua.DoString("CancelShapeshiftForm()"); } else { Lua.DoString("Dismount()"); } } // can't fish while swimming.. if (_me.IsSwimming && !WaterWalking.CanCast) { AutoAngler.Instance.Debug("Moving to new PoolPoint since I'm swimming at current PoolPoint"); RemovePointAtTop(pool); return(RunStatus.Success); } return(RunStatus.Failure); }
private static string FormatPostion(MoveResult result) { return($"{(char)('A' + result.Position.X)}{result.Position.Y + 1}"); }
public void Collide(MoveResult result, double speed) { }
public MoveResult MakeMove(int gameId, D.Stone newStone) { MoveResult result = new MoveResult(); Game game = _gameRepository.Get(gameId).ToClient(); if (game is null) { throw new GameException(GameResult.GameNotExist, HttpStatusCode.NotFound, "Game do not exist"); } if (!(game.Result is null)) { throw new GameException(GameResult.GameFinished, HttpStatusCode.BadRequest, "Game already finished"); } result.BlackCapture = game.BlackCapture; result.WhiteCapture = game.WhiteCapture; result.KoInfo = game.KoInfo; if (newStone.Color is true && game.WhiteState != true || newStone.Color is false && game.BlackState != true) { throw new GameException(GameResult.OtherPlayerTurn, HttpStatusCode.BadRequest, "Not your turn"); } game.Rule = _ruleRepository.Get(game.Rule.Id); List <D.Stone> stones = _stoneRepository.Get(gameId).ToList(); Board board = new Board(stones, game.Size, game.Size, game.BlackPlayer, game.WhitePlayer, game.BlackCapture, game.WhiteCapture, game.KoInfo); if (!board.IsValid()) { throw new GameException(GameResult.BoardNotValid, HttpStatusCode.BadRequest, "Board not valid"); } board.SetCaptures(game.BlackPlayer, game.BlackCapture); board.SetCaptures(game.WhitePlayer, game.WhiteCapture); if (!board.Has(newStone) || newStone.Color is null) { throw new GameException(GameResult.InvalidMove, HttpStatusCode.BadRequest, "Invalid move"); } Board move = board.MakeMove(newStone, game.Rule.Suicide, game.Rule.Overwrite, game.Rule.Ko); result = board.Diff(move); foreach (D.Stone stone in result.Stones) { _ = stone.Color is null?_stoneRepository.DeleteStone(gameId, stone) : _stoneRepository.AddStone(gameId, stone); } result.BlackState = !(game.BlackState is true); result.WhiteState = !(game.WhiteState is true); game.BlackCapture = move.GetCaptures(game.BlackPlayer); game.WhiteCapture = move.GetCaptures(game.WhitePlayer); game.BlackState = result.BlackState; game.WhiteState = result.WhiteState; game.KoInfo = move.KoInfo; _gameRepository.Update(gameId, game.ToDal()); return(result); }
private bool Movement(Vector3 pos) { lastMoveResult=Navigator.MoveTo(pos); return true; }
private MoveResult ModifyPlayerState(MoveResult result, Game game, int userId) { if (game.BlackPlayer.UserId == userId && game.WhitePlayer.UserId == userId) { if (game.BlackState == true) { game.BlackState = null; } if (game.WhiteState == true) { game.WhiteState = null; } if (game.BlackState == null && game.WhiteState == null) { result.Result = "P+O"; } else { result.BlackState = game.BlackState is null ? null : !game.BlackState; result.WhiteState = game.WhiteState is null ? null : !game.WhiteState; } } else if (game.BlackPlayer.UserId == userId) { if (!(game.BlackState == true)) { throw new GameException(GameResult.OtherPlayerTurn, HttpStatusCode.BadRequest, "Not your turn"); } game.BlackState = null; if (game.BlackState == null && game.WhiteState == null) { //TODO: implement end of game result.Result = "TODO"; } else { result.BlackState = game.BlackState is null ? null : !game.BlackState; result.WhiteState = game.WhiteState is null ? null : !game.WhiteState; } } else if (game.WhitePlayer.UserId == userId) { if (!(game.WhiteState == true)) { throw new GameException(GameResult.OtherPlayerTurn, HttpStatusCode.BadRequest, "Not your turn"); } game.WhiteState = null; if (game.BlackState == null && game.WhiteState == null) { //TODO: implement end of game result.Result = "TODO"; } else { result.BlackState = game.BlackState is null ? null : !game.BlackState; result.WhiteState = game.WhiteState is null ? null : !game.WhiteState; } } else { throw new GameException(GameResult.NotParticipate, HttpStatusCode.BadRequest, "User don't participate"); } return(result); }
internal virtual void PostMove(MoveResult mv, Position2D pos) { if (mv == MoveResult.CannotMoveLivingEntityInTheWay) { TryAttack(pos); } }
public override void ChooseMovesAsP(MoveResult moveResult) { }
void OnPathCompleted(Path p) { if (_movementType != MoveTypes.Pathing && _movementType != MoveTypes.FleePathing) { return; } if (p.error) { _pathToTarget.Clear(); _moveResult = MoveResult.TargetNotReachable; SetAnimatorSpeed(NotMoving); return; } switch (extraPathSmoothing) { default: _pathToTarget = p.vectorPath; break; case MovePathSmoothing.Force: _pathToTarget = GameWorld.Instance.SmoothPath(p.vectorPath, false); break; case MovePathSmoothing.LikeSlime: _pathToTarget = GameWorld.Instance.SmoothPath(p.vectorPath, true); break; } }
public override void OnStart() { // set defaults if (Math.Abs(PathPrecision) < 1f) PathPrecision = 20; if (PathPointLimit == 0) PathPointLimit = 250; if (Math.Abs(InteractRange) < 1f) InteractRange = 10; if (InteractAttempts == 0) InteractAttempts = 5; if (TimeoutSeconds == 0) TimeoutSeconds = TimeoutSecondsDefault; if (MaxSearchDistance <= 0) MaxSearchDistance = 10; _behaviorStartTime = DateTime.UtcNow; _lastPosition = Vector3.Zero; _stuckStart = DateTime.UtcNow; _lastCheckedStuck = DateTime.UtcNow; _lastMoveResult = MoveResult.Moved; _completedInteractAttempts = 0; _startWorldId = ZetaDia.CurrentWorldId; _miniMapMarker = null; _mapMarkerLastPosition = Vector3.Zero; _interactObject = null; Navigator.Clear(); Logger.Debug("Initialized {0}", Status()); }
bool RequestPath(Vector3 position) { if (_movementType != MoveTypes.Pathing) { return false; } if (!_seeker.IsDone()) { return false; } _moveResult = MoveResult.Preparing; _seeker.StartPath(transform.position, position, OnPathCompleted); return true; }
/// <summary> /// Main MoveToMapMarker Behavior /// </summary> /// <returns></returns> protected override Composite CreateBehavior() { return new Sequence( new DecoratorContinue(ret => ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld, new Sequence( new Action(ret => Logger.Log("IsDead={0} IsLoadingWorld={1}", ZetaDia.Me.IsDead, ZetaDia.IsLoadingWorld)), new Action(ret => RunStatus.Failure) ) ), CheckTimeout(), new Action(ret => FindMiniMapMarker()), new DecoratorContinue(ret => _miniMapMarker != null, new Action(ret => RefreshActorInfo()) ), //new DecoratorContinue(ret => _interactObject == null && _miniMapMarker == null && Position == Vector3.Zero, // new Sequence( // new Action(ret => _miniMapMarker = GetRiftExitMarker()) // ) //), new DecoratorContinue(ret => _interactObject == null && _miniMapMarker == null && Position == Vector3.Zero, new Sequence( new Action(ret => Logger.Debug("Error: Could not find MiniMapMarker nor PortalObject nor Position {0}", Status())), new Action(ret => _isDone = true) ) ), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination && _interactObject == null, new Sequence( new Action(ret => Logger.Log("ReachedDestination, no object found - finished!")), new Action(ret => _isDone = true), new Action(ret => RunStatus.Failure) ) ), new Sequence( new Action(ret => GameUI.SafeClickUIButtons()), new PrioritySelector( new Decorator(ret => GameUI.IsPartyDialogVisible, new Action(ret => Logger.Log("Party Dialog is visible")) ), new Decorator(ret => GameUI.IsElementVisible(GameUI.GenericOK), new Action(ret => Logger.Log("Generic OK is visible")) ), new Decorator(ret => DestinationWorldId == -1 && ZetaDia.CurrentWorldId != _startWorldId, new Sequence( new Action(ret => Logger.Log("World changed ({0} to {1}), destinationWorlId={2}, finished {3}", _startWorldId, ZetaDia.CurrentWorldId, DestinationWorldId, Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => DestinationWorldId != 0 && ZetaDia.CurrentWorldId == DestinationWorldId, new Sequence( new Action(ret => Logger.Log("DestinationWorlId matched, finished {0}", Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => _completedInteractAttempts > 1 && _lastPosition.Distance(ZetaDia.Me.Position) > 4f && DestinationWorldId != _startWorldId, new Sequence( new Action(ret => _isDone = true), new Action(ret => Logger.Log("Moved {0:0} yards after interaction, finished {1}", _lastPosition.Distance(ZetaDia.Me.Position), Status())) ) ), new Decorator(ret => _interactObject != null && _interactObject.IsValid, new PrioritySelector( new Decorator(ret => _lastMoveResult != MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Debug("Moving to actor {0} {1}", _interactObject.ActorSNO, Status())), new ActionRunCoroutine(async ret => _lastMoveResult = await Navigator.MoveTo(_interactObject.Position)) ) ), new Decorator(ret => _lastMoveResult == MoveResult.ReachedDestination && _interactObject.Distance > InteractRange, new Sequence( new Action(ret => Logger.Log("ReachedDestination but not within InteractRange, finished")), new Action(ret => _isDone = true) ) ), new Decorator(ret => ZetaDia.Me.Movement.IsMoving, new Action(ret => CommonBehaviors.MoveStop())), new Sequence( new Action(ret => _lastPosition = ZetaDia.Me.Position), new Action(ret => _interactObject.Interact()), new Action(ret => _completedInteractAttempts++), new Action(ret => Logger.Debug("Interacting with portal object {0}, result: {1}", _interactObject.ActorSNO, Status())), new Sleep(500), new Action(ret => GameEvents.FireWorldTransferStart()) ) ) ), new Decorator(ret => _miniMapMarker != null && _interactObject == null, new PrioritySelector( new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) > PathPrecision, new Sequence( new Action(ret => Logger.Debug("Moving to Map Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new ActionRunCoroutine(async ret => _lastMoveResult = await Navigator.MoveTo(_miniMapMarker.Position)) ) ), new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) < PathPrecision, new Sequence( new Action(ret => Logger.Debug("Successfully Moved to Map Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new Action(ret => _isDone = true) ) ) ) ), new Decorator(ret => _miniMapMarker == null && Position != Vector3.Zero, new Sequence( new ActionRunCoroutine(async ret => _lastMoveResult = await Navigator.MoveTo(Position)), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Log("ReachedDestination of Position, finished.")), new Action(ret => _isDone = true) ) ) ) ), new Action(ret => Logger.Error("MoveToMapMarker Error: marker={0} actor={1}/{2} completedInteracts={3} isPortal={4} dist={5} interactRange={6}", _miniMapMarker != null, _interactObject != null, (_interactObject != null && _interactObject.IsValid), _completedInteractAttempts, IsPortal, (_interactObject != null ? _interactObject.Position.Distance(ZetaDia.Me.Position) : 0f), InteractRange)) ) ) ); }
//Methods// public static void Move(Room selectedRoom, Layout background, out MoveResult result) { result = MoveResult.None; bool b = true; while (b) { char input = Console.ReadKey().KeyChar; switch (input) { case 'z': { if (selectedRoom.Pos.X > 0) { selectedRoom.MoveUp(); } b = false; break; } case 's': { if (selectedRoom.Pos.X + selectedRoom.Layout.Size.X < background.Size.X) { selectedRoom.MoveDown(); } b = false; break; } case 'q': { if (selectedRoom.Pos.Y > 0) { selectedRoom.MoveLeft(); } b = false; break; } case 'd': { if (selectedRoom.Pos.Y + selectedRoom.Layout.Size.Y < background.Size.Y) { selectedRoom.MoveRight(); } b = false; break; } case 'a': { if (selectedRoom.Pos.Y + selectedRoom.Layout.Size.X < background.Size.Y && selectedRoom.Pos.X + selectedRoom.Layout.Size.Y < background.Size.X) { selectedRoom.RotateACW(); } b = false; break; } case 'e': { if (selectedRoom.Pos.Y + selectedRoom.Layout.Size.X < background.Size.Y && selectedRoom.Pos.X + selectedRoom.Layout.Size.Y < background.Size.X) { selectedRoom.RotateCW(); } b = false; break; } case ' ': { if (LayoutHelper.IsValid(background, selectedRoom)) { LayoutHelper.MergeRoom(background, selectedRoom); DisplayHelper.DisplayMoreSpace(); result = MoveResult.Placed; return; } break; } case 'n': { result = MoveResult.GaveUp; return; } default: { continue; } } } return; }
/// <summary> /// Safely Moves the player to the requested destination <seealso cref="MoveToMapMarkerTag.PathPointLimit"/> /// </summary> /// <param name="newpos">Vector3 of the new position</param> /// <param name="destinationName">For logging purposes</param> /// <returns></returns> private bool Move(Vector3 newpos, string destinationName = "") { bool result = false; if (StraightLinePathing) { Navigator.PlayerMover.MoveTowards(newpos); _lastMoveResult = MoveResult.Moved; result = true; } if (!ZetaDia.WorldInfo.IsGenerated) { if (_clientNavFailed && PathPointLimit > 20) { PathPointLimit = PathPointLimit - 10; } else if (_clientNavFailed && PathPointLimit <= 20) { PathPointLimit = 250; } if (newpos.Distance(ZetaDia.Me.Position) > PathPointLimit) { newpos = MathEx.CalculatePointFrom(ZetaDia.Me.Position, newpos, newpos.Distance(ZetaDia.Me.Position) - PathPointLimit); } } float destinationDistance = newpos.Distance(ZetaDia.Me.Position); _lastMoveResult = _qtNavigator.MoveTo(newpos, destinationName); switch (_lastMoveResult) { case MoveResult.Moved: case MoveResult.ReachedDestination: case MoveResult.UnstuckAttempt: _clientNavFailed = false; result = true; break; case MoveResult.PathGenerated: case MoveResult.PathGenerating: case MoveResult.PathGenerationFailed: case MoveResult.Failed: Navigator.PlayerMover.MoveTowards(Position); result = false; _clientNavFailed = true; break; } if (QuestTools.EnableDebugLogging) { Logger.Debug("MoveResult: {0}, newpos={1} destinationName={2}", _lastMoveResult.ToString(), newpos, destinationName); } return result; }
private void _board_CheckerMoved(bool direction, Address startPos, Address endPos, MoveResult moveResult, int stepCount) { UpdateLog(direction, startPos, endPos, moveResult, stepCount); tsmiSaveGame.Enabled = tsbSaveGame.Enabled = true; }
public override void ResetCachedDone() { _isDone = false; _behaviorStartTime = DateTime.UtcNow; _lastPosition = Vector3.Zero; _stuckStart = DateTime.UtcNow; _lastCheckedStuck = DateTime.UtcNow; _lastMoveResult = MoveResult.Moved; _completedInteractAttempts = 0; _startWorldId = ZetaDia.CurrentWorldId; _miniMapMarker = null; _mapMarkerLastPosition = Vector3.Zero; _interactObject = null; base.ResetCachedDone(); }
/// <summary> /// Do not remove nav server logging. We need to be able to identify the cause of stuck issues users report /// and to do that we need to be able to differentiate between bugs in trinity and navigation server problems. /// </summary> public static void NavServerReport(bool silent = false, MoveResult moveResult = default(MoveResult), [System.Runtime.CompilerServices.CallerMemberName] string caller = "") { if (Navigator.SearchGridProvider.Width == 0 || Navigator.SearchGridProvider.SearchArea.Length == 0) { if(silent) Logger.LogVerbose("Waiting for Navigation Server... ({0})", caller); else Logger.Log("Waiting for Navigation Server... ({0})", caller); } else if (moveResult == MoveResult.PathGenerating) { Logger.LogVerbose("Navigation Path is Generating... ({0})", caller); } else if (moveResult == MoveResult.PathGenerationFailed) { Logger.LogVerbose("Navigation Path Failed to Generate... ({0})", caller); } }
private MoveResult Reposition(IHitBox hitBox, MoveResult result, Vector2 interpolation) { AxisAlignedBoundingBox aabb = hitBox.BoundingBox; var moveX = result.HasFlag(MoveResult.X) && !result.HasFlag(MoveResult.BlockedOnNegativeX) && !result.HasFlag(MoveResult.BlockedOnPositiveX); if (moveX) { aabb.Position.X += interpolation.X; } bool surfaced = CanSetSurfaced(hitBox); var moveY = result.HasFlag(MoveResult.Y) && !result.HasFlag(MoveResult.BlockedOnNegativeY) && !result.HasFlag(MoveResult.BlockedOnPositiveY); if ((moveY || !surfaced) && !result.HasFlag(MoveResult.Died)) { hitBox.State = HitBoxState.Airborne; } else { hitBox.State = HitBoxState.Surfaced; } if (moveY && !result.HasFlag(MoveResult.Died)) { aabb.Position.Y += interpolation.Y; } var reverse = CollisionDetection.CanMove(aabb.Bounds, -interpolation, DetectionType.Retrace); if (moveX) // fix issue when moving on X axis to the left. { if (reverse.HasFlag(MoveResult.BlockedOnNegativeX) && interpolation.X > 0) { aabb.Position.X -= interpolation.X; result &= ~MoveResult.X; } else if (reverse.HasFlag(MoveResult.BlockedOnPositiveX) && interpolation.X < 0) { aabb.Position.X -= interpolation.X; result &= ~MoveResult.X; } } if (moveY) // fix issue when hitting an impassable on Y axis when jumping. { if (reverse.HasFlag(MoveResult.BlockedOnNegativeY) && interpolation.Y > 0) { aabb.Position.Y -= interpolation.Y; result &= ~MoveResult.Y; } else if (reverse.HasFlag(MoveResult.BlockedOnPositiveY) && interpolation.Y < 0) { aabb.Position.Y -= interpolation.Y; result &= ~MoveResult.Y; } } return(result); }
protected async Task<bool> MoveToObjectiveRoutine() { if (ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld) { Logger.Log("IsDead={0} IsLoadingWorld={1}", ZetaDia.Me.IsDead, ZetaDia.IsLoadingWorld); return false; } SceneSegmentation.Update(); if (_route.Any() || _currentRouteDestination != Vector3.Zero) { return MoveAlongRoute(_route); } // If the bot has failed to run directly towards the objective marker too many times // We'll blacklist it for 30 seconds to allow adjacent scenes to be explored. if (FailedAttempts >= FailedAttemptMax) { Logger.Log("Blacklisting Objective Marker for 60 seconds"); BlacklistMarkerExpires = DateTime.UtcNow.AddSeconds(60); FailedAttempts = 0; _route = CreateRouteToUnexploredScene(); return false; } // While the bot is currently blacklisted from directly running at the objective // Generate a route to go through some nearby scenes if (DateTime.UtcNow < BlacklistMarkerExpires) { _route = CreateRouteToObjective(); return false; } // 'ReachedDestination' is returned when finding a path to destination has failed. if (_lastMoveResult == MoveResult.ReachedDestination && _objectiveObject == null) { if (_miniMapMarker != null && _miniMapMarker.IsValid && _miniMapMarker.IsPointOfInterest) { var distance = ZetaDia.Me.Position.Distance(_miniMapMarker.Position); if (distance > 100) { FailedAttempts++; Logger.Log("Direct Pathfinding failed towards Objective Marker. Attempts={0}/{1}", FailedAttempts, FailedAttemptMax); } else if (distance < 30) { Logger.Log("ReachedDestination no Objective found - finished!"); _isDone = true; return true; } } } // Find the objective minimap marker FindObjectiveMarker(); // If the marker is found or was previously found, find a nearby actor if (_mapMarkerLastPosition != Vector3.Zero) RefreshActorInfo(); if (_objectiveObject == null && _miniMapMarker == null && Position == Vector3.Zero) { Logger.Log("Error: Could not find Objective Marker! {0}", Status()); _isDone = true; return true; } // Finish if World Changed if (ZetaDia.CurrentWorldId != _startWorldId) { Logger.Log("World changed from {0} to {1}, finished {2}", _startWorldId, ZetaDia.CurrentWorldId, Status()); _isDone = true; return true; } // Finish because Objective Found if (IsValidObjective() && _objectiveObject is DiaUnit && _objectiveObject.Position.Distance(ZetaDia.Me.Position) <= PathPrecision) { Logger.Log("We found the objective and its a monster, ending tag so we can kill it. {0}", Status()); _isDone = true; return true; } // Objective Object is available if (_objectiveObject != null && _objectiveObject.IsFullyValid()) { // Move Closer to Objective Object if (_lastMoveResult != MoveResult.ReachedDestination) { Logger.Debug("Moving to actor {0} {1}", _objectiveObject.ActorSNO, Status()); _lastMoveResult = await CommonCoroutines.MoveTo(_objectiveObject.Position); return true; } if (_objectiveObject is GizmoPortal) { if (_lastMoveResult == MoveResult.ReachedDestination && _objectiveObject.Distance > InteractRange) { Logger.Log("ReachedDestination but not within InteractRange, finished"); _isDone = true; return true; } if (GameUI.PartyLeaderBossAccept.IsVisible || GameUI.PartyFollowerBossAccept.IsVisible) { Logger.Debug("Party Boss Button visible"); return true; } if (ZetaDia.Me.Movement.IsMoving) { await CommonBehaviors.MoveStop().ExecuteCoroutine(); } _objectiveObject.Interact(); _completedInteractAttempts++; Logger.Debug("Interacting with portal object {0}, result: {1}", _objectiveObject.ActorSNO, Status()); await Coroutine.Sleep(500); GameEvents.FireWorldTransferStart(); return true; } } if (_miniMapMarker != null && ObjectiveObjectIsNullOrInvalid()) { if (_miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) > PathPrecision) { Logger.Debug("Moving to Objective Marker {0}, {1}", _miniMapMarker.NameHash, Status()); _lastMoveResult = await CommonCoroutines.MoveTo(_miniMapMarker.Position); return true; } if (_miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) < PathPrecision) { Logger.Debug("Successfully Moved to Objective Marker {0}, {1}", _miniMapMarker.NameHash, Status()); _isDone = true; return true; } } if (_miniMapMarker == null && Position != Vector3.Zero && Position.Distance(ZetaDia.Me.Position) > PathPrecision) { _lastMoveResult = CommonCoroutines.MoveTo(Position).Result; if (_lastMoveResult == MoveResult.ReachedDestination) { Logger.Log("ReachedDestination of Position, minimap marker not found, finished."); _isDone = true; return true; } } Logger.Error("MoveToObjective Error: marker={0} actorNull={1} actorValid={2} completedInteracts={3} isPortal={4} dist={5} interactRange={6}", _miniMapMarker != null, _objectiveObject != null, (_objectiveObject != null && _objectiveObject.IsFullyValid()), _completedInteractAttempts, IsPortal, (_objectiveObject != null && _objectiveObject.IsFullyValid() ? _objectiveObject.Position.Distance(ZetaDia.Me.Position) : 0f), InteractRange); return false; }
public void start() { GameParameters parameters = new GameParameters(); parameters.MapSize = Convert.ToInt32(ConfigurationManager.AppSettings["MapSize"]); parameters.PawnMovementRange = Convert.ToInt32(ConfigurationManager.AppSettings["MovementRange"]); parameters.NumberPlayers = Convert.ToInt32(ConfigurationManager.AppSettings["NumberPlayers"]); parameters.NumberPawnMvt2 = Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt2"]); parameters.NumberPawnMvt3 = Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt3"]); parameters.NumberPawnMvt4 = Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt4"]); parameters.NumberPawn = Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt2"]) + Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt3"]) + Convert.ToInt32(ConfigurationManager.AppSettings["NumberPawnMvt4"]); if (parameters.MapSize > 26 || parameters.PawnMovementRange < 1) { parameters = GameParameters.Default; } Game currentGame = new Game(parameters); GameGrid grid = new GameGrid { GameState = currentGame }; bool shouldExit = false; int tourPlayer = 0; int[] tour = new int[2]; tour[0] = 0; tour[1] = 0; do { //Console.Clear(); Console.WriteLine("(Type 'exit' to leave the game.)"); Console.WriteLine(); currentGame.updatePlayerTour(tourPlayer); grid.Draw(tourPlayer); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("[PLAYER " + (tourPlayer + 1) + "]"); Console.Write("Enter coordinates to move Pawn" + tour[tourPlayer] + " to: "); string input = Console.ReadLine(); shouldExit = !String.IsNullOrWhiteSpace(input) && input.ToLower() == _exitCode; MapCoordinates destination; if (!shouldExit && CoordinateConverter.TryParse(input, out destination)) { MoveResult result = currentGame.MovePawnTo(destination); switch (result) { case MoveResult.Illegal: Console.WriteLine(); Console.WriteLine("Can't move there. Press any key to retry."); Console.ReadKey(); break; case MoveResult.OK: tour[tourPlayer] = (tour[tourPlayer] + 1) % 5; tourPlayer = (tourPlayer + 1) % 2; continue; default: Console.WriteLine(); Console.WriteLine("Let's not do that again, ok ? Press any key to retry."); Console.ReadKey(); break; } } else { if (!shouldExit) { Console.WriteLine(); Console.WriteLine("Invalid Input. Press any key to retry."); Console.ReadKey(); } } }while (!shouldExit && !currentGame.CurrentPlayer.isFailed()); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("BRAVO Player " + tourPlayer); Console.ReadKey(); }
public override void ChooseMovesAsPBar(MoveResult moveResult) { // not used }
private void SetMindField(MoveResult result) { _mindField.Setup(m => m.Move(It.IsAny <CompassDirection>())).Returns(result); }
/** * @fn MakeMove * @brief Makes a move. * * Makes a move, switches the @c PlayerToMove variable, * and updates piece legal moves. */ public MoveResult MakeMove(byte source, byte destination, PieceType?promoteTo = null) { MoveResult ret = MoveResult.None; if (!IsMoveValid(source, destination)) { throw new InvalidOperationException("Invalid move entered."); } Piece movingPiece = Squares [source].Piece; // Forbid castling if the king moves. if (movingPiece.Type == PieceType.King) { if (movingPiece.Colour == PieceColour.White) { WhiteCastledR = true; WhiteCastledL = true; } else { BlackCastledR = true; BlackCastledL = true; } } if (movingPiece.Type == PieceType.Rook) { if (source == 0) { BlackCastledL = true; } else if (source == 7) { BlackCastledR = true; } else if (source == 56) { WhiteCastledL = true; } else if (source == 63) { WhiteCastledR = true; } } // Special rules for castling if (movingPiece.Type == PieceType.King && (source == 4 || source == 60) && Array.IndexOf(castleDestinations, destination) != -1) { ret = destination - source > 0 ? MoveResult.KingsideCastle : MoveResult.QueensideCastle; Square castleRookSquare = destination - source > 0 ? Squares [destination + 1] : Squares [destination - 2]; Squares [destination].Piece = movingPiece; Squares [source].Piece = null; Squares [destination - source > 0 ? destination - 1 : destination + 1].Piece = castleRookSquare.Piece; castleRookSquare.Piece = null; } else { // Handle pawn moves if (Squares [source].Piece.Type == PieceType.Pawn) { ret = MoveResult.PawnMove; // Handle en passant creation if (Array.IndexOf(enPassantStartSquares, source) > -1 && Array.IndexOf(enPassantEndSquares, destination) > -1) { EnPassantColour = Squares [source].Piece.Colour; EnPassantSquare = EnPassantColour == PieceColour.White ? (byte)(destination + 8) : (byte)(destination - 8); } } if (Squares [destination].Piece != null) { ret = MoveResult.Capture; } switch (promoteTo) { case PieceType.Bishop: Squares [destination].Piece = new Piece(movingPiece.Colour, PieceType.Bishop); Squares [source].Piece = null; break; case PieceType.Knight: Squares [destination].Piece = new Piece(movingPiece.Colour, PieceType.Knight); Squares [source].Piece = null; break; case PieceType.Rook: Squares [destination].Piece = new Piece(movingPiece.Colour, PieceType.Rook); Squares [source].Piece = null; break; case PieceType.Queen: Squares [destination].Piece = new Piece(movingPiece.Colour, PieceType.Queen); Squares [source].Piece = null; break; default: // Handle en passant capture if (movingPiece.Type == PieceType.Pawn && destination == EnPassantSquare && EnPassantSquare != 0) { byte captureSquare = EnPassantColour == PieceColour.White ? (byte)(destination - 8) : (byte)(destination + 8); Squares [destination].Piece = movingPiece; Squares [captureSquare].Piece = null; Squares [source].Piece = null; ret = MoveResult.Capture; EnPassantSquare = 0; } else { Squares [destination].Piece = movingPiece; Squares [source].Piece = null; if (movingPiece.Type != PieceType.Pawn) { EnPassantSquare = 0; } } break; } Gtk.Application.Invoke(delegate { MainClass.win.UpdateMaterialDifference(new Board(this)); }); } if (PlayerToMove == PieceColour.White) { PlayerToMove = PieceColour.Black; } else { PlayerToMove = PieceColour.White; } PiecePseudoLegalMoves.GeneratePseudoLegalMoves(this); PieceLegalMoves.GenerateLegalMoves(this); return(ret); }
public override MoveResult EvaluateLeafNodeMove(Move move) { TankAction[] actions_p_i; TankAction[] actions_p_iBar = new TankAction[0]; TankAction[] actions_pBar_j; TankAction[] actions_pBar_jBar; MobileState tankState_j = GetTankState(move.pBar, move.j); MobileState tankState_jBar = GetTankState(move.pBar, move.jBar); MoveResult moveResult = new MoveResult(move); if (!IsValid(move)) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Invalid; return(moveResult); } // Get the attack distance of player p's tank i to the enemy base: int A_p_i = GetAttackDistanceOfTankToEnemyBaseFromDirection(move.p, move.i, move.dir1); if (A_p_i >= Constants.UNREACHABLE_DISTANCE) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Invalid; return(moveResult); } // In this scenario the other tank (iBar) is either dead or too far from the action to be of any use: int A_p_iBar = GetAttackDistanceOfTankToEnemyBaseFromDirection(move.p, move.iBar, move.dir1); if (A_p_iBar < A_p_i) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Invalid; return(moveResult); } // Set the recommended action for the attacking tank: actions_p_i = GetActionsToAttackEnemyBaseFromDirection(move.p, move.i, move.dir1); TankActionRecommendation tankActionRec = new TankActionRecommendation { IsAMoveRecommended = true, RecommendedTankAction = actions_p_i[0] }; moveResult.SetTankActionRecommendation(move.p, move.i, tankActionRec); // *** The role for tank p_i is to attack the enemy base along direction dir1. // Get the minimum attack distance of player pBar's tanks: int A_pBar_j = GetAttackDistanceOfTankToEnemyBase(move.pBar, move.j); int A_pBar_jBar = GetAttackDistanceOfTankToEnemyBase(move.pBar, move.jBar); int A_pBar_MIN = Math.Min(A_pBar_j, A_pBar_jBar); // iBar is not part of this scenario. Ensure they can't interfere with the defence: int D_p_iBar = GetCentralLineOfFireDefenceDistanceToHomeBase(move.p, move.iBar); if (D_p_iBar <= A_pBar_MIN) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Invalid; return(moveResult); } // Calculate slack A as p's attack distance less pBar's attack distance int slackA = A_p_i - A_pBar_MIN; // *** slackA is the attack slack (p's attack distance less pBar's best attack distance) // Get the minimum defence distances of player pBar's tank j to the base: int D_pBar_j = GetLineOfFireDefenceDistanceToHomeBaseByIncomingAttackDirection(move.pBar, move.j, move.dir1); int D_pBar_jBar = GetLineOfFireDefenceDistanceToHomeBaseByIncomingAttackDirection(move.pBar, move.jBar, move.dir1); int D_pBar_MIN = Math.Min(D_pBar_j, D_pBar_jBar); // Calculate slack D as p's attack distance less pBar's defence distance // (to the same base and on the same direction of attack): int slackD = A_p_i - D_pBar_MIN; // *** slackD is the defence slack (defender distance to defence less attacker distance to attack with direction dir1 // Get the overall slack (distance to activating this scenario): int slack = Math.Max(slackA, slackD); moveResult.Slack = slack; if (slack < 0) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Current; } else if (slack <= EVALUATION_OUTCOME_CLOSE_THRESHOLD) { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Close; } else { moveResult.EvaluationOutcome = ScenarioEvaluationOutcome.Possible; } // Calculate best defensive actions for the defender: bool pBar_j_defends; bool pBar_jBar_defends; if (slackD < slackA) { // Defending is the smallest slack, so put best defensive effort here: if (D_pBar_j < D_pBar_jBar) { pBar_j_defends = true; pBar_jBar_defends = false; // *** Tank goal: pBar_j defends base from incoming attack with direction dir1 // *** Tank goal: pBar_jBar does nothing } else { pBar_j_defends = false; pBar_jBar_defends = true; // *** Tank goal: pBar_j does nothing // *** Tank goal: pBar_jBar defends base from incoming attack with direction dir1 } } else { // Attacking is the smallest slack, so put most effort here: if (A_pBar_j < A_pBar_jBar) { pBar_j_defends = false; pBar_jBar_defends = true; // *** Tank goal: pBar_j does nothing // *** Tank goal: pBar_jBar defends base from incoming attack with direction dir1 } else { pBar_j_defends = true; pBar_jBar_defends = false; // *** Tank goal: pBar_j defends base from incoming attack with direction dir1 // *** Tank goal: pBar_jBar does nothing } } // Determine best action for pBar.j: // TODO: Check if is alive, is locked down, is locked in a quadrant, already has a move assigned, etc. if (pBar_j_defends) { actions_pBar_j = base.GetActionsToReachLineOfFireDefencePointByIncomingAttackDirection(move.pBar, move.j, move.dir1); } else { actions_pBar_j = GetActionsToAttackEnemyBase(move.pBar, move.j); } if (actions_pBar_j != null && actions_pBar_j.Length > 0) { tankActionRec = new TankActionRecommendation { IsAMoveRecommended = true, RecommendedTankAction = actions_pBar_j[0] }; moveResult.SetTankActionRecommendation(move.pBar, move.j, tankActionRec); } // Determine best action for pBar.jBar: // TODO: Check if is alive, is locked down, is locked in a quadrant, already has a move assigned, etc. if (pBar_jBar_defends) { actions_pBar_jBar = base.GetActionsToReachLineOfFireDefencePointByIncomingAttackDirection(move.pBar, move.jBar, move.dir1); } else { actions_pBar_jBar = GetActionsToAttackEnemyBase(move.pBar, move.jBar); } if (actions_pBar_jBar != null && actions_pBar_jBar.Length > 0) { tankActionRec = new TankActionRecommendation { IsAMoveRecommended = true, RecommendedTankAction = actions_pBar_jBar[0] }; moveResult.SetTankActionRecommendation(move.pBar, move.jBar, tankActionRec); } return(moveResult); }
public bool TryMove(int startIdx, int targetIdx, Piece promotionPiece, out MoveResult result) { result = MoveResult.None; var color = BoardValueToColor(m_Board[startIdx]); if (color != CurrentPlayer) { Assert.IsTrue(false); return(false); } if (!IsLegalMove(startIdx, targetIdx, out var move)) { return(false); } MakeMove(move, promotionPiece); m_HalfMoveCountSincePawnMoveOrCapture += 1; bool isCapture = move.CapturedValue != k_EmptySquare; bool isPawnMove = IsPawn(BoardValueToPiece(move.StartValue)); if (isCapture || isPawnMove) { m_HalfMoveCountSincePawnMoveOrCapture = 0; } m_CurrentEnPassantTargetIdx = move.EnPassantTargetIdx; bool nextPlayerInCheck = IsInCheck(NextPlayer, out _); var nextPlayerHasMoves = HasAnyLegalMoves(NextPlayer); bool checkmate = nextPlayerInCheck && !nextPlayerHasMoves; bool stalemate = !nextPlayerInCheck && !nextPlayerHasMoves; if (checkmate) { result = NextPlayer == Color.White ? MoveResult.WhiteCheckmated : MoveResult.BlackCheckmated; } else if (stalemate) { result = MoveResult.StaleMate; } m_LastMove = move; CurrentPlayer = CurrentPlayer == Color.White ? Color.Black : Color.White; var currentPositionHash = ZobristHashing.HashPosition(m_Board, CurrentPlayer); if (!m_PositionCountsByHash.ContainsKey(currentPositionHash)) { m_PositionCountsByHash[currentPositionHash] = 0; } m_PositionCountsByHash[currentPositionHash] += 1; bool threefoldRepetition = m_PositionCountsByHash[currentPositionHash] >= 3; bool fiftyMoveRule = m_HalfMoveCountSincePawnMoveOrCapture >= 100; CanDrawBeClaimed = fiftyMoveRule || threefoldRepetition; return(true); }
/// <summary> /// Main MoveToObjective Behavior /// </summary> /// <returns></returns> protected override Composite CreateBehavior() { return (new Sequence( new DecoratorContinue(ret => ZetaDia.Me.IsDead || ZetaDia.IsLoadingWorld, new Sequence( new Action(ret => Logger.Log("IsDead={0} IsLoadingWorld={1}", ZetaDia.Me.IsDead, ZetaDia.IsLoadingWorld)), new Action(ret => RunStatus.Failure) ) ), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination && _objectiveObject == null, new Sequence( new Action(ret => Logger.Log("ReachedDestination, no Objective found - finished!")), new Action(ret => _isDone = true), new Action(ret => RunStatus.Failure) ) ), new Action(ret => FindObjectiveMarker()), new DecoratorContinue(ret => _mapMarkerLastPosition != Vector3.Zero, new Action(ret => RefreshActorInfo()) ), new DecoratorContinue(ret => _objectiveObject == null && _miniMapMarker == null && Position == Vector3.Zero, new Sequence( new Action(ret => Logger.Log("Error: Could not find Objective Marker! {0}", Status())), new Action(ret => _isDone = true) ) ), new Sequence( new PrioritySelector( new Decorator(ret => ZetaDia.CurrentWorldId != _startWorldId, new Sequence( new Action(ret => Logger.Log("World changed from {0} to {1}, finished {2}", _startWorldId, ZetaDia.CurrentWorldId, Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => IsValidObjective() && _objectiveObject is DiaUnit && _objectiveObject.Position.Distance(ZetaDia.Me.Position) <= PathPrecision, new Sequence( new Action(ret => Logger.Log("We found the objective and its a monster, ending tag so we can kill it. {0}", Status())), new Action(ret => _isDone = true) ) ), new Decorator(ret => _objectiveObject != null && _objectiveObject.IsValid, new PrioritySelector( new Decorator(ret => _lastMoveResult != MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Debug("Moving to actor {0} {1}", _objectiveObject.ActorSNO, Status())), new Action(ret => _lastMoveResult = Navigator.MoveTo(_objectiveObject.Position)) ) ), new Decorator(ret => _objectiveObject is GizmoPortal, new PrioritySelector( new Decorator(ret => _lastMoveResult == MoveResult.ReachedDestination && _objectiveObject.Distance > InteractRange, new Sequence( new Action(ret => Logger.Log("ReachedDestination but not within InteractRange, finished")), new Action(ret => _isDone = true) ) ), new Decorator(ret => ZetaDia.Me.Movement.IsMoving, new Action(ret => CommonBehaviors.MoveStop())), new Sequence( new Action(ret => _objectiveObject.Interact()), new Action(ret => _completedInteractAttempts++), new Action(ret => Logger.Debug("Interacting with portal object {0}, result: {1}", _objectiveObject.ActorSNO, Status())), new Sleep(500), new Action(ret => GameEvents.FireWorldTransferStart()) ) ) ) ) ), new Decorator(ret => _miniMapMarker != null && _objectiveObject == null, new PrioritySelector( new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) > PathPrecision, new Sequence( new Action(ret => Logger.Debug("Moving to Objective Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new Action(ret => _lastMoveResult = Navigator.MoveTo(_miniMapMarker.Position)) ) ), new Decorator(ret => _miniMapMarker != null && _miniMapMarker.Position.Distance(ZetaDia.Me.Position) < PathPrecision, new Sequence( new Action(ret => Logger.Debug("Successfully Moved to Objective Marker {0}, {1}", _miniMapMarker.NameHash, Status())), new Action(ret => _isDone = true) ) ) ) ), new Decorator(ret => _miniMapMarker == null && Position != Vector3.Zero && Position.Distance(ZetaDia.Me.Position) > PathPrecision, new Sequence( new Action(ret => _lastMoveResult = Navigator.MoveTo(Position)), new DecoratorContinue(ret => _lastMoveResult == MoveResult.ReachedDestination, new Sequence( new Action(ret => Logger.Log("ReachedDestination of Position, finished.")), new Action(ret => _isDone = true) ) ) ) ), new Action(ret => Logger.LogError("MoveToObjective Error: marker={0} actor={1}/{2} completedInteracts={3} isPortal={4} dist={5} interactRange={6}", _miniMapMarker != null, _objectiveObject != null, (_objectiveObject != null && _objectiveObject.IsValid), _completedInteractAttempts, IsPortal, (_objectiveObject != null && _objectiveObject.IsValid ? _objectiveObject.Position.Distance(ZetaDia.Me.Position) : 0f), InteractRange) ) ) ) )); }
public BoardState(MoveResult moveResult, string boardLayout, Player player) { MoveResult = moveResult; BoardLayout = boardLayout; Player = player; }
ConquestResult TryConquest(Country invader, IReadOnlySquad invaderSquad, Location loc, MoveResult moveResult) { if (!moveResult.Success) { return(RaiseConquestResult(new ConquestResult(loc, invader, null, null, null, false, moveResult))); } _discovery.MarkDiscovered(invader, loc); if (loc.Owner == null) { OnConquestSuccess(invader, invaderSquad, loc); Debug.WriteLine($"ConquestController.TryConquest: {invader} auto-conquest '{loc.Name}'"); return(RaiseConquestResult(new ConquestResult(loc, invader, null, new SquadInfo(invaderSquad.Count, 0), null, true, moveResult))); } else { var defender = loc.Owner; var defenderSquad = _army.AquireMaxSquad(defender); var conquestResult = TryDefeat(loc, moveResult, invader, ref invaderSquad, defender, ref defenderSquad); if (conquestResult.Success) { OnConquestSuccess(invader, invaderSquad, loc); } if (defenderSquad != null) { _army.ReleaseSquad(defender, defenderSquad); } Debug.WriteLine( $"ConquestController.TryConquest: {invader} conquest '{loc.Name}', result: ({conquestResult.Success}, " + $"invader: {conquestResult.InvaderSquad.Count} - {conquestResult.InvaderSquad.Loses}," + $"defender: {conquestResult.DefenderSquad.Count} - {conquestResult.DefenderSquad.Loses})" ); return(RaiseConquestResult(conquestResult)); } }
public bool ApplyMovement(Direction direction, MoveResult result, ref int destinationX, ref int destinationY, ref bool isOnGround, ref bool isSurfing) { bool success = false; switch (result) { case MoveResult.Success: success = true; break; case MoveResult.Jump: success = true; switch (direction) { case Direction.Down: destinationY++; break; case Direction.Left: destinationX--; break; case Direction.Right: destinationX++; break; } break; case MoveResult.Sliding: success = true; break; case MoveResult.Icing: success = true; break; case MoveResult.OnGround: success = true; isOnGround = true; break; case MoveResult.NoLongerOnGround: success = true; isOnGround = false; break; case MoveResult.NoLongerSurfing: success = true; isSurfing = false; break; } return success; }
public string Hook_MoveSplitItem(Item item, BaseOven oven, int totalSlots) { MoveResult result = MoveSplitItem(item, oven, totalSlots); return(result.ToString()); }
private void RefreshDiagnostics(DetectionType detectionType, FitResult fit, FitResult fitX, FitResult fitY, MoveResult flags) { if (detectionType == DetectionType.Collision) { Diagnostic.Write("fit ", fit); Diagnostic.Write("fitX", fitX); Diagnostic.Write("fitY", fitY); Diagnostic.Write("rslt", flags); } else if (detectionType == DetectionType.Retrace) { Diagnostic.Write("rFt ", fit); Diagnostic.Write("rFtX", fitX); Diagnostic.Write("rFtY", fitY); Diagnostic.Write("RSLT", flags); } }
private bool Movement(Vector3 pos) { lastMoveResult = Navigator.MoveTo(pos); return(true); }
/// <summary> /// Determines if the current node can be marked as Visited, and does so if needed /// </summary> /// <returns></returns> private Composite CheckNodeFinished() { return new PrioritySelector( new Decorator(ret => LastMoveResult==MoveResult.ReachedDestination, new Sequence( new Action(ret => SetNodeVisited("Reached Destination")), new Action(ret => LastMoveResult=MoveResult.Moved), new Action(ret => UpdateRoute()) ) ), new Decorator(ret => GetRouteUnvisitedNodeCount()==0||!BrainBehavior.DungeonExplorer.CurrentRoute.Any(), //new Action(ret => DbHelper.Log(TrinityLogLevel.Normal, LogCategory.ProfileTag, "Error - CheckIsNodeFinished() called while Route is empty!")), new Action(ret => UpdateRoute()) ), new Decorator(ret => CurrentNavTarget.Distance2D(myPos)<=PathPrecision, new Sequence( new Action(ret => SetNodeVisited(String.Format("Node {0} is within PathPrecision ({1:0}/{2:0})", CurrentNavTarget, CurrentNavTarget.Distance2D(myPos), PathPrecision))), new Action(ret => UpdateRoute()) ) ), new Decorator(ret => CurrentNavTarget.Distance2D(myPos)<=90f&&!gp.CanStandAt(gp.WorldToGrid(CurrentNavTarget.ToVector2())), new Sequence( new Action(ret => SetNodeVisited("Center Not Navigable")), new Action(ret => UpdateRoute()) ) ), new Decorator(ret => ObjectCache.Obstacles.IsPositionWithinAny(CurrentNavTarget), new Sequence( new Action(ret => SetNodeVisited("Navigation obstacle detected at node point")), new Action(ret => UpdateRoute()) ) ), new Decorator(ret => !FunkyTrinity.Bot.NavigationCache.currentMovementState.HasFlag(MovementState.WalkingInPlace|MovementState.None)&&myPos.Distance2D(CurrentNavTarget)<=50f&&!Navigator.Raycast(myPos, CurrentNavTarget), new Sequence( new Action(ret => SetNodeVisited("Stuck moving to node point, marking done (in LoS and nearby!)")), new Action(ret => UpdateRoute()) ) ), new Decorator(ret => SkipAheadCache.CheckPositionForSkipping(CurrentNavTarget), new Sequence( new Action(ret => SetNodeVisited("Found node to be in skip ahead cache, marking done")), new Action(ret => UpdateRoute()) ) ), CheckIgnoredScenes() ); }
/// <summary> /// ignores pathfinding to reach the target /// </summary> public MoveResult MoveToDirect(Vector3 position) { _movementType = MoveTypes.Direct; if (_lastRequestedMoveTargetPosition != position) { _moveResult = MoveResult.Moving; _pathToTarget = new List<Vector3> {position}; _lastRequestedMoveTargetPosition = position; } return _moveResult; }
internal virtual void PostMove(MoveResult mr, Position2D pos) { }
public void StopMovement() { _movementType = MoveTypes.Direct; _pathToTarget = new List<Vector3> {transform.position}; _moveResult = MoveResult.ReachedTarget; SetAnimatorSpeed(NotMoving); }
internal static MoveResult NavigateTo(Vector3 destination, string destinationName = "") { if (_navigateToCoroutine == null || _navigateToCoroutine.IsFinished) { Trinity.NavServerReport(); if (!ZetaDia.Me.Movement.IsMoving && LastDestination != destination && ZetaDia.IsInGame) { Logger.LogVerbose(LogCategory.Movement, "NavigateTo: Starting Movement Towards {0} ({1})", destination, destinationName); Instance.MoveTowards(destination); } _navigateToCoroutine = new Coroutine(async () => { _lastResult = await NavigateToTask(destination, destinationName); return _lastResult; }); } LastDestination = destination; _navigateToCoroutine.Resume(); if (_navigateToCoroutine.Status == CoroutineStatus.RanToCompletion) { return (MoveResult)_navigateToCoroutine.Result; } Trinity.NavServerReport(false, _lastResult); return MoveResult.Moved; }
public void UpdateMovement(float deltaTime) { TimeOutSpeedmods(); if (Time.time - _lastPathRequestTime > RepathRate) { if (_movementType == MoveTypes.Pathing) { if (RequestPath(_lastRequestedMoveTargetPosition)) { _lastPathRequestTime = Time.time; } } if (_movementType == MoveTypes.FleePathing) { if (RequestFleePath(_lastRequestedMoveTargetPosition)) { _lastPathRequestTime = Time.time; } } } if (_pathToTarget.Count > 0) { SetAnimatorSpeed(Moving); if (AstarMath.SqrMagnitudeXZ(_pathToTarget[0], transform.position) <= TargetReachDistance) { _pathToTarget.RemoveAt(0); if (_pathToTarget.Count == 0) { _moveResult = MoveResult.ReachedTarget; SetAnimatorSpeed(NotMoving); return; } LookAt(_pathToTarget[0]); } if (_pathToTarget.Count > 0) { transform.position = Vector3.MoveTowards(transform.position, _pathToTarget[0], deltaTime*_effectiveMovespeed); _moveResult = MoveResult.Moving; } } if (_lookDirection != Vector3.zero) { transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(_lookDirection), deltaTime/turnSpeed); } }