private static Node CreateInteractionBehavior(Dorf d, IInteractable i) { Condition findWork = new Condition(() => { //TODO: what check here? Maybe an action to get a work-place? return false; }); BehaviorTrees.Action goToWork = new BehaviorTrees.Action(() => { //TODO: replace vector param with location of workplace! var mc = new MoveCommand(d,new Vector3(),WALKSPEED); if (mc.isAllowed()) { mc.execute(); return Node.Status.RUNNING; } else { return Node.Status.FAIL; } }); BehaviorTrees.Action work = new BehaviorTrees.Action(() => { //TODO: replace null value with some kind of interactable variable from d. var ic = new InteractCommand(d,null); if (ic.isAllowed()) { ic.execute(); return Node.Status.RUNNING; } else { return Node.Status.FAIL; } }); SequenceSelector root = new SequenceSelector(findWork,goToWork,work); return root; }
public override bool PerformAction() { if (moveCommand.IsComplete()) { //basically, if we're not moving, harvest or deposit stuff, else, just move and wait if (harvesting) { Collect(); if(unit.currentload >= unit.capacity ||resource.isEmpty()) { //make sure that we have a whole number to avoid bugs //caused by floating point numbers unit.currentload = Mathf.Floor(unit.currentload); //might end up loosing some here... harvesting = false; moveCommand = new MoveCommand (unit, unit.mothership.transform.position); unit.IssueSubCommand (moveCommand); } } else { Deposit(); if(unit.currentload <= 0) { if (!resource.isEmpty ()) { harvesting = true; moveCommand = new MoveCommand (unit,resource.transform.position); unit.IssueSubCommand (moveCommand); } else { complete = true; //just deposited our load and the resource is empty } } } } return complete; }
private void Move(MoveDirection direction) { MoveCommand moveCommand = new MoveCommand(moveCommandReciever, direction, moveDistance, objectToMove); moveCommand.Execute(); commands.Add(moveCommand); currentCommandNum++; }
//STATIC public static Command CreateMoveToCommand(GameObject actor, Vector3 movePosition) { var cmd = new MoveCommand(); cmd.Id = CMD_MOVE_ID; cmd.Name = CMD_MOVE_NAME; cmd.Destination = movePosition; cmd.Actor = actor; return cmd; }
void Move(MoveProperties props) { MoveCommand moveCommand = new MoveCommand(); moveCommand.orginalPosition = transform.position; moveCommand.destPosition = props.dest.transform.position; moveCommand.entityMoved = gameObject; moveCommandSignal.Invoke(moveCommand); }
// Update is called once per frame void Update() { if(Input.GetMouseButtonDown(0)){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Debug.Log("Yeah"); RaycastHit hit; if(Physics.Raycast(ray, out hit)){ if(hit.collider.gameObject.layer == LayerMask.NameToLayer("Enviro")){ //Debug.Log(hit.collider.gameObject.layer+ "vs" + LayerMask.NameToLayer("Enviro")); MoveCommand movec = new MoveCommand(team, hit.point); movec.AddICommand(team); team.AddCommand(movec); //MoveInLineFormation(hit.point); // ExecuteCommand(); } else { if(hit.collider.gameObject.layer == 11 && hit.collider.gameObject.tag == "Door"){ MoveCommand move = new MoveCommand(team, hit.point); move.AddICommand(team); team.AddCommand(move); if(hit.collider.gameObject.GetComponent<Door>().IsLocked()){ C4Command c4 = new C4Command(team); c4.AddICommand(team); team.AddCommand(c4); } else{ DoorCommand door = new DoorCommand(team, hit.collider.gameObject); door.AddICommand(team); team.AddCommand(new DoorCommand(team, hit.collider.gameObject)); } } } } } if(Input.GetMouseButtonDown(1)){ team.ExecuteCommand(); } //TODO: For testing purposes. if(Input.GetKeyDown(KeyCode.G)){ team.AddCommand(new FragGrenadeCommand(team)); } if(Input.GetKeyDown(KeyCode.F)){ team.AddCommand(new FlashbangCommand(team)); } if(Input.GetKeyDown(KeyCode.M)){ team.AddCommand(new MineCommand(team)); } if(Input.GetKeyDown(KeyCode.E)){ team.AddCommand(new C4Command(team)); } if(Input.GetKeyDown(KeyCode.C)){ team.AddCommand(new ClaymoreCommand(team)); } }
public void ShouldRollbackFileMove() { // Given var command = new MoveCommand (OriginFilePath, DestinyFilePath); command.Execute (); // When command.Rollback (); // Then Assert.IsTrue (File.Exists (OriginFilePath)); Assert.IsFalse (File.Exists (DestinyFilePath)); }
void Awake() { watetime = wate; sampleCommand = new MoveCommand(); killcmd = new KillCommand(); PlayerID = GameManager.GetInstance().myInfo.id.ToString(); //PhotonRPCHandler.killtimeEvent += killtimeEvent; killflag = false; death = new bool[8]; for (int i = 0; i < 8; i++) { death[i] = false; } }
public void ShouldMoveFile() { // Given Assert.IsTrue (File.Exists (OriginFilePath)); Assert.IsFalse (File.Exists (DestinyFilePath)); // When var command = new MoveCommand (OriginFilePath, DestinyFilePath); command.Execute (); // Then Assert.IsFalse (File.Exists (OriginFilePath)); Assert.IsTrue (Directory.Exists (Path.GetDirectoryName (DestinyFilePath))); Assert.IsTrue (File.Exists (DestinyFilePath)); }
/// <summary> /// Get proper command based on command input string /// </summary> /// <param name="commandInput"></param> /// <param name="robot"></param> /// <returns></returns> public static ICommand Get(string inputCommand, IRobot robot) { string commandInputName = string.Empty; var args = new string[] { }; StringCommandExtension.ExtractArgsFromCommandString(inputCommand, ref commandInputName, ref args); ICommand command = null; if (!String.IsNullOrEmpty(commandInputName)) { switch (commandInputName.ToEnum<CommandType>()) { case CommandType.Place: //try parse args string into Position Position pos = null; if (TryParseArgsIntoPosition(args, ref pos)) { command = new PlaceCommand(robot, pos.Coordinate.X, pos.Coordinate.Y, pos.Direction); } break; case CommandType.Right: command = new RightCommand(robot); break; case CommandType.Left: command = new LeftCommand(robot); break; case CommandType.Move: command = new MoveCommand(robot); break; case CommandType.Report: command = new ReportCommand(robot); break; } } return command; }
public HarvestCommand(Unit unit, Resource resource) { if (unit.canharvest) { //sanity check (I don't think this is need though) this.unit = unit; this.resource = resource; if(harvesttype == ResourceType.None || harvesttype !=resource.GetResourceType()) { //ensure we are carrying the right resource harvesttype = resource.GetResourceType(); unit.currentload = 0.0f; } harvesting = true; moveCommand = new MoveCommand (unit, resource.transform.position); unit.IssueSubCommand (moveCommand); } else { complete = true; } }
void Update() { // Every tick the enemy shall fly downward and into the direction of // the player if (player != null) { float xDistance = player.transform.position.x - this.transform.position.x; Direction direction = Direction.left; ICommand moveCommand = new MoveCommand(direction); moveCommand.Execute(toControl); // if distance on the x-axis of this enemies and the players // position is smaller than a given range the enemy shall shoot if (Mathf.Abs(xDistance) < shootingRange) { ICommand shootCommand = new ShootCommand(); shootCommand.Execute(toControl); } } }
public override bool PerformAction() { if (target != null) { //not destroyed presumably targetVector = target.transform.position - unit.transform.position; if (targetVector.sqrMagnitude > unit.sqrAttackRange) { //create or update a move command with the current fastest way into firing range to track the target if (moveCommand == null) { moveCommand = new MoveCommand (unit, target.transform.position - targetVector.normalized * 0.95f * Mathf.Sqrt (unit.sqrAttackRange)); //1 would be attack range, 0.95 is slightly less unit.IssueSubCommand (moveCommand); } else { moveCommand.UpdateMoveDestination (target.transform.position - targetVector.normalized * 0.95f * Mathf.Sqrt (unit.sqrAttackRange)); } } if (Mathf.Abs (Vector3.Dot (target.transform.position - unit.transform.position, unit.transform.forward)) > 0.01) { // if it's not in front (since dot product of up and forward would be zero) TurnToTarget (); } } else { complete = true; } return complete; }
void ICommandOwner <MoveCommand, MoveCommandHandler> .Command(MoveCommand command) { commandManager.Handle <MoveCommand, MoveCommandHandler>(this, command); }
/// <summary> /// Animate list moving /// </summary> /// <param name="moveCommand"></param> private void DrawAnimation(MoveCommand moveCommand) { int sign = moveCommand == MoveCommand.Left ? -1 : 1; int bufSideRange = bufferSize / 2; for (int i = -bufSideRange; i <= bufSideRange; i++) { Image Image = (Image)CarouselCanvas.Children[i + bufSideRange]; Storyboard storyboard = new Storyboard(); DoubleAnimation translAnimation = TranslateXAnimation(Image, distanceCenterX * sign, AnimationTime); storyboard.Children.Add(translAnimation); DoubleAnimation scXAnimation; DoubleAnimation scYAnimation; if(i == 0) { scXAnimation = ScaleXAnimation(Image, ScaleKeficient, 1, AnimationTime); scYAnimation = ScaleYAnimation(Image, ScaleKeficient, 1, AnimationTime); storyboard.Children.Add(scXAnimation); storyboard.Children.Add(scYAnimation); } else { if (sign * i == - 1) { scXAnimation = ScaleXAnimation(Image, 1, ScaleKeficient, AnimationTime); scYAnimation = ScaleYAnimation(Image, 1, ScaleKeficient, AnimationTime); storyboard.Children.Add(scXAnimation); storyboard.Children.Add(scYAnimation); } } storyboard.Begin(); } }
/// <summary> /// Processes a MOVE command /// </summary> /// <param name="cmd">Move Command</param> /// <param name="context">SPARQL Update Evaluation Context</param> protected virtual void ProcessMoveCommandInternal(MoveCommand cmd, SparqlUpdateEvaluationContext context) { cmd.Evaluate(context); }
/// <summary> /// Processes a MOVE command /// </summary> /// <param name="cmd">Move Command</param> public void ProcessMoveCommand(MoveCommand cmd) { ProcessCommand(cmd); }
public async Task <Unit> Handle(MoveCommand command, CancellationToken cancellationToken) { var roomId = command.RoomId; var playerId = command.PlayerId; if (roomId <= 0) { await _bus.RaiseEvent(new DomainNotification($"房间不存在!")); return(Unit.Value); } var player = await _playerDomainService.Get(playerId); if (player == null) { await _bus.RaiseEvent(new DomainNotification($"角色不存在!")); return(Unit.Value); } if (player.Status != PlayerStatusEnum.空闲) { await _bus.RaiseEvent(new DomainNotification($"请先停止{player.Status}!")); return(Unit.Value); } var oldRoomId = player.RoomId; if (oldRoomId == roomId) { await _bus.RaiseEvent(new DomainNotification("你已在此地!请刷新或重新进入游戏!")); return(Unit.Value); } var oldRoom = await _roomDomainService.Get(oldRoomId); if (oldRoom != null) { if (!new[] { oldRoom.West, oldRoom.East, oldRoom.North, oldRoom.South }.Contains(roomId)) { await _bus.RaiseEvent(new DomainNotification($"无法移动到该房间!")); return(Unit.Value); } } var newRoom = await _roomDomainService.Get(roomId); if (newRoom == null) { await _bus.RaiseEvent(new DomainNotification("房间不存在!")); return(Unit.Value); } player.RoomId = roomId; await _playerDomainService.Update(player); if (await Commit()) { await _bus.RaiseEvent(new MovedEvent(player, newRoom, oldRoom)); } return(Unit.Value); }
public void ExcuteMovement(MoveCommand moveCommand) { moveCommand.ExcuteMoveCommand(); }
/// <summary> /// Evaluates the general drone input keys together. /// </summary> /// <param name="keyUpdated">The updated <see cref="KeyInfo"/>.</param> /// <returns>The evaluated <see cref="KeyInfo"/> as a <see cref="DroneCommand"/>.</returns> protected virtual DroneCommand EvaluateInputKeys(KeyInfo keyUpdated) { if (this.Connect.KeyState == KeyState.Down) { return(new ConnectCommand()); } else if (this.TakeOff.KeyState == KeyState.Down) { return(new TakeOffCommand()); } else if (this.Land.KeyState == KeyState.Down) { return(new LandCommand()); } else { MoveCommand moveCommand = new MoveCommand(); if (this.MoveForward.KeyState == KeyState.Down) { moveCommand.Longitudinal += MOVE_FORWARD; } if (this.MoveBackward.KeyState == KeyState.Down) { moveCommand.Longitudinal += MOVE_BACKWARD; } if (this.MoveLeft.KeyState == KeyState.Down) { moveCommand.Lateral += MOVE_LEFT; } if (this.MoveRight.KeyState == KeyState.Down) { moveCommand.Lateral += MOVE_RIGHT; } if (this.MoveUp.KeyState == KeyState.Down) { moveCommand.Vertical += MOVE_UP; } if (this.MoveDown.KeyState == KeyState.Down) { moveCommand.Vertical += MOVE_DOWN; } if (this.YawLeft.KeyState == KeyState.Down) { moveCommand.Yaw += YAW_LEFT; } if (this.YawRight.KeyState == KeyState.Down) { moveCommand.Yaw += YAW_RIGHT; } return(moveCommand); } }
public Ball() : base(ServiceProvider.Instance.Resolve <SpriteBatch>(), Constants.EntityIds.BallId) { _moveCommand = new MoveCommand <Ball>(this, 4, new Vector2(1f, 0.15f)); _commandManager = ServiceProvider.Instance.Resolve <ICommandManager>(); }
override public BaseCommand Make(GameObject target) { return(MoveCommand.Make(target, this)); }
public bool IsSatisfiedBy(MoveCommand moveCommand, Game game) { return(game.Clone().PlayWithoutRecord(moveCommand).DoOte(moveCommand.Player.Opponent)); }
/// <summary> /// Ask the engine to do a move /// </summary> /// <param name="move">The move to do</param> /// <returns>True if the move was valid and therefore has been done</returns> public bool DoMove(Move move) { //No reason to move if it's the same square if (move.StartCoordinate == move.TargetCoordinate) { return(false); } Piece piece = Board.PieceAt(move.StartCoordinate); Piece targetPiece = Board.PieceAt(move.TargetCoordinate); //TODO gérer exception if (_ruleGroups.Handle(move, Board)) { ICompensableCommand command; if ((move.PieceType == Type.King) && (((targetPiece?.Type == Type.Rook) && (move.PieceColor == targetPiece.Color)) || (Math.Abs(move.TargetCoordinate.X - move.StartCoordinate.X) == 2))) { command = new CastlingCommand(move, Board); } else if ((move.PieceType == Type.Pawn) && (targetPiece == null) && (move.StartCoordinate.X != move.TargetCoordinate.X)) { command = new EnPassantCommand(move, Board); } else if ((move.PieceType == Type.Pawn) && (move.TargetCoordinate.Y == (move.PieceColor == Color.White ? 0 : 7))) { command = new PromoteCommand(move, Board); } else { command = new MoveCommand(move, Board); } //En passant if (move.PieceColor == Color.White) { if (_enPassantPawnWhite != null) { _enPassantPawnWhite.EnPassant = false; _enPassantPawnWhite = null; } } else { if (_enPassantPawnBlack != null) { _enPassantPawnBlack.EnPassant = false; _enPassantPawnBlack = null; } } if ((move.PieceType == Type.Pawn) && (Math.Abs(move.StartCoordinate.Y - move.TargetCoordinate.Y) == 2)) { if (move.PieceColor == Color.White) { _enPassantPawnWhite = (Pawn)piece; _enPassantPawnWhite.EnPassant = true; } else { _enPassantPawnBlack = (Pawn)piece; _enPassantPawnBlack.EnPassant = true; } } //Number of moves since last capture if (Board.PieceAt(move.TargetCoordinate) == null) { _container.HalfMoveSinceLastCapture++; } else { _container.HalfMoveSinceLastCapture = 0; } _conversation.Execute(command); _moves.Add(command); return(true); } return(false); }
private void search(Vector3 pos, MoveCommand command) { //Debug.Log(stage.panels[(int)pos.x, (int)pos.z] + ":" + pos + ":"); if (stage.panels[(int)pos.x, (int)pos.z] == 0 || stage.panels[(int)pos.x, (int)pos.z] == 2) { stage.CharacterExit((int)this.transform.position.x, (int)this.transform.position.z); //Debug.Log("x = " + (int)this.transform.position.x + "\r\nz = " + (int)this.transform.position.z); transform.position += Vector3.right * command.offsetX; transform.position += Vector3.forward * command.offsetZ; stage.CharacterEnter((int)this.transform.position.x, (int)this.transform.position.z); //Debug.Log("x = " + (int)this.transform.position.x + "\r\nz = " + (int)this.transform.position.z); } }
private void Start() { JumpCommand = JumpCommand ?? new JumpCommand(); MoveCommand = MoveCommand ?? new MoveCommand(); }
public override void _presenter_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { if (pressedMouseLeftButtonDown) { if (_startPoint != null) { current = e.GetPosition(_inkCanvas); switch (MoveOrZoom) { case "Move": double offsetx = current.X - _prepoint.X; double offsety = current.Y - _prepoint.Y; _inkCollector.IsAutoMove = true; //移动Mybutton foreach (MyButton myButton in _inkCollector.SelectButtons) { myButton.InkFrame._inkCanvas.CaptureMouse(); ButtonMoveCommand bmc = new ButtonMoveCommand(myButton, offsetx, offsety, _inkCollector); bmc.execute(); } //移动MyImage foreach (MyImage image in _inkCollector.SelectedImages) { ImageMoveCommand imc = new ImageMoveCommand(image, offsetx, offsety); imc.execute(); image.adjustBound(); foreach (ImageConnector connector in image.ConnectorCollection) { connector.adjustConnector(); } } //移动笔迹 if (_inkCollector.SelectedStrokes.Count > 0) { foreach (MyStroke myStroke in _inkCollector.SelectedStrokes) { MoveCommand mc = new MoveCommand(myStroke, offsetx, offsety); mc.execute(); } } //移动图形 if (SelectedMyGraphics.Count > 0) { MyGraphicsMoveCommand mgsmc = new MyGraphicsMoveCommand(SelectedMyGraphics, offsetx, offsety, _inkCollector); mgsmc.execute(); } //移动文本 foreach (MyRichTextBox myRichTextBox in _inkCollector.SelectedMyRichTextBoxs) { Command tmc = new TextMoveCommand(myRichTextBox, offsetx, offsety); tmc.execute(); } break; case "Zoom": _inkCollector.IsAutoMove = false; StylusPoint curr = new StylusPoint(current.X, current.Y); StylusPoint pre = new StylusPoint(_prepoint.X, _prepoint.Y); foreach (MyButton myButton in _inkCollector.SelectButtons) { double dist1 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getMyButtonCenter(myButton), curr); double dist2 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getMyButtonCenter(myButton), pre); if (dist2 == 0) { dist2 = 1; } double scaling = dist1 / dist2; ButtonZoomCommand bmc = new ButtonZoomCommand(myButton, scaling, _inkCollector, myButton.Angle); bmc.execute(); } foreach (MyImage image in _inkCollector.SelectedImages) { double dist1 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getImageCenter(image), curr); double dist2 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getImageCenter(image), pre); if (dist2 == 0) { dist2 = 1; } double scaling = dist1 / dist2; ImageZoomCommand izc = new ImageZoomCommand(image, scaling); izc.execute(); image.adjustBound(); foreach (ImageConnector connector in image.ConnectorCollection) { connector.adjustConnector(); } } break; } _prepoint = current; } } }
public void ShouldThrowExceptionIfFileDoesntExist() { // When var command = new MoveCommand (@"c:\temp\foo.txt", DestinyFilePath); command.Execute (); }
public override void _presenter_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (pressedMouseLeftButtonDown) { if (_startPoint != null) { current = e.GetPosition(_inkCanvas); switch (MoveOrZoom) { case "Move": double offsetx = current.X - _startPoint.X; double offsety = current.Y - _startPoint.Y; _inkCollector.IsAutoMove = true; foreach (MyButton myButton in _inkCollector.SelectButtons) { myButton.InkFrame._inkCanvas.ReleaseMouseCapture(); myButton.InkFrame._inkCanvas.Cursor = Cursors.Arrow; myButton.TextBoxTime.Background = null; ButtonMoveCommand bmc = new ButtonMoveCommand(myButton, offsetx, offsety, _inkCollector); _inkCollector.CommandStack.Push(bmc); } if (_inkCollector.SelectedImages.Count > 0) { foreach (MyImage image in _inkCollector.SelectedImages) { Command imc = new ImageMoveCommand(image, offsetx, offsety); _inkCollector.CommandStack.Push(imc); image.Bound.Visibility = Visibility.Collapsed; _inkCanvas.Cursor = Cursors.Arrow; image.Image.ReleaseMouseCapture(); foreach (ImageConnector connector in image.ConnectorCollection) { connector.adjustConnector(); } } } if (_inkCollector.SelectedStrokes.Count > 0) { foreach (MyStroke myStroke in _inkCollector.SelectedStrokes) { MoveCommand mc = new MoveCommand(myStroke, offsetx, offsety); _inkCollector.CommandStack.Push(mc); } } //移动图形 if (SelectedMyGraphics.Count > 0) { foreach (MyGraphic myGraphic in SelectedMyGraphics) { MyGraphicMoveCommand mgmc = new MyGraphicMoveCommand(myGraphic, offsetx, offsety, _inkCollector); _inkCollector.CommandStack.Push(mgmc); mgmc.searchRelation(); } //MyGraphicsMoveCommand mgsmc = new MyGraphicsMoveCommand(SelectedMyGraphics, offsetx, offsety, _inkCollector.Sketch.MyGraphics, _inkCollector); //_inkCollector.CommandStack.Push(mgsmc); List <int> ids = GraphicMathTool.getInstance().getGraphicStructure(_inkCollector.Sketch.MyGraphics[0], _inkCollector, new List <int>()); foreach (int id in ids) { _inkCollector._mainPage.message.Content += id.ToString() + ","; } } //移动文本 foreach (MyRichTextBox myRichTextBox in _inkCollector.SelectedMyRichTextBoxs) { Command tmc = new TextMoveCommand(myRichTextBox, offsetx, offsety); myRichTextBox.RichTextBox.BorderBrush = null; _inkCollector.CommandStack.Push(tmc); } MoveOrZoom = ""; break; case "Zoom": _inkCollector.IsAutoMove = false; StylusPoint curr = new StylusPoint(current.X, current.Y); StylusPoint sta = new StylusPoint(_startPoint.X, _startPoint.Y); foreach (MyButton myButton in _inkCollector.SelectButtons) { double dist1 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getMyButtonCenter(myButton), curr); double dist2 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getMyButtonCenter(myButton), sta); if (dist2 == 0) { dist2 = 1; } double scaling = dist1 / dist2; _inkCanvas.Cursor = Cursors.Arrow; myButton.TextBoxTime.Background = null; ButtonZoomCommand bmc = new ButtonZoomCommand(myButton, scaling, _inkCollector, myButton.Angle); _inkCollector.CommandStack.Push(bmc); } foreach (MyImage image in _inkCollector.SelectedImages) { double dist1 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getImageCenter(image), curr); double dist2 = MathTool.getInstance().distanceP2P(MathTool.getInstance().getImageCenter(image), sta); if (dist2 == 0) { dist2 = 1; } double scaling = dist1 / dist2; _inkCanvas.Cursor = Cursors.Arrow; image.Bound.Visibility = Visibility.Collapsed; ImageZoomCommand izc = new ImageZoomCommand(image, scaling); _inkCollector.CommandStack.Push(izc); foreach (ImageConnector connector in image.ConnectorCollection) { connector.adjustConnector(); } } MoveOrZoom = ""; break; } _inkCollector.SelectButtons.Clear(); _inkCollector.SelectedImages.Clear(); _inkCollector.SelectedStrokes.Clear(); _inkCollector.SelectedMyRichTextBoxs.Clear(); SelectedMyGraphics.Clear(); } _inkCanvas.ReleaseMouseCapture(); _inkCollector.IsAutoMove = false; pressedMouseLeftButtonDown = false; } }
public ICommand GetDefaultBumpAction(MoveCommand moveCommand) { return(new SkipTurnCommand(Host)); }
public List<Square> Update(MoveCommand command, PlayerState player) { player.X = command.X; player.Y = command.Y; return new List<Square>(); }
public void Describe_ShouldBeNotEmpty() { IProgramCommand command = new MoveCommand(123); Assert.False(string.IsNullOrWhiteSpace(command.Describe())); }
List <Command> BuildCommandLists(GameObject player, Transform content) { Transform _enemy = player == this.player ? enemy.transform : this.player.transform; List <Command> list = new List <Command>(); foreach (Transform headCmd in content) { List <Command> lst = null; Transform cmdObj = headCmd; Command cmdClass = null; while (true) { switch (cmdObj.name) { // Movement case "Move(Clone)": cmdClass = new MoveCommand(player, Convert.ToInt32(cmdObj.GetArgs()[0])); break; case "TurnR(Clone)": cmdClass = new TurnCommand(player, -Convert.ToSingle(cmdObj.GetArgs()[0])); break; case "TurnL(Clone)": cmdClass = new TurnCommand(player, Convert.ToSingle(cmdObj.GetArgs()[0])); break; // Actions case "Shoot(Clone)": cmdClass = new ShootCommand(player, bulletPrefab); break; case "Look at enemy(Clone)": cmdClass = new TurnCommand(player, _enemy); break; // Events /*case "OnStart(Clone)": * lst = new List<Command>(); * player.GetComponent<Player>().OnStart += () => HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); break;*/ case "OnCollisionWithBullet(Clone)": lst = new List <Command>(); player.GetComponent <Player>().OnCollisionWithBullet += () => HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); break; case "OnCollisionWithPlayer(Clone)": lst = new List <Command>(); player.GetComponent <Player>().OnCollisionWithPlayer += () => HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); break; case "OnSuccessfulHit(Clone)": lst = new List <Command>(); _enemy.GetComponent <Player>().OnCollisionWithBullet += () => HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); break; case "OnTimer(Clone)": lst = new List <Command>(); player.GetComponent <Player>().OnTimer += () => { if (player.GetComponent <Player>().secondsAlive % Convert.ToInt32(headCmd.GetArgs()[1]) == 0) { HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); } }; break; case "OnChangeHP(Clone)": lst = new List <Command>(); player.GetComponent <Player>().OnChangeHP += () => { if (player.GetComponent <Player>().HP == Convert.ToInt32(headCmd.GetArgs()[1])) { HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); } }; break; case "OnCollisionWithBounds(Clone)": lst = new List <Command>(); player.GetComponent <Bounds>().OnCollisionWithBounds += () => HandleEvent(player, new Thread(this, lst, false, Convert.ToInt32(headCmd.GetArgs()[0]), headCmd.name)); break; } if (lst == null) { list.Add(cmdClass); } else if (cmdClass != null) { lst.Add(cmdClass); } Transform next = cmdObj.Next(); if (next == null) { break; } else { cmdObj = next; } } } return(list); }
// TODO handle the defaultGraph case internal static INode ToSpinRdf(this SparqlUpdateCommand query, IGraph g) { INode root = g.CreateBlankNode(); SpinVariableTable varTable = new SpinVariableTable(g); switch (query.CommandType) { case SparqlUpdateCommandType.Add: g.Assert(root, RDF.PropertyType, SP.ClassAdd); AddCommand add = (AddCommand)query; if (add.SourceUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(add.SourceUri)); } if (add.DestinationUri == null) { g.Assert(root, SP.PropertyInto, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyInto, RDFUtil.CreateUriNode(add.DestinationUri)); } break; case SparqlUpdateCommandType.Clear: g.Assert(root, RDF.PropertyType, SP.ClassClear); if (((ClearCommand)query).TargetUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(((ClearCommand)query).TargetUri)); } break; case SparqlUpdateCommandType.Copy: g.Assert(root, RDF.PropertyType, SP.ClassCopy); CopyCommand copy = (CopyCommand)query; if (copy.SourceUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(copy.SourceUri)); } if (copy.DestinationUri == null) { g.Assert(root, SP.PropertyInto, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyInto, RDFUtil.CreateUriNode(copy.DestinationUri)); } break; case SparqlUpdateCommandType.Create: g.Assert(root, RDF.PropertyType, SP.ClassCreate); CreateCommand create = (CreateCommand)query; if (create.TargetUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(create.TargetUri)); } break; case SparqlUpdateCommandType.Delete: g.Assert(root, RDF.PropertyType, SP.ClassModify); DeleteCommand delete = (DeleteCommand)query; if (delete.GraphUri != null) { g.Assert(root, SP.PropertyWith, RDFUtil.CreateUriNode(delete.GraphUri)); } // TODO handle the usings g.Assert(root, SP.PropertyDeletePattern, delete.DeletePattern.ToSpinRdf(g, varTable)); g.Assert(root, SP.PropertyWhere, delete.WherePattern.ToSpinRdf(g, varTable)); break; case SparqlUpdateCommandType.DeleteData: g.Assert(root, RDF.PropertyType, SP.ClassDeleteData); g.Assert(root, SP.PropertyData, ((DeleteDataCommand)query).DataPattern.ToSpinRdf(g, varTable)); break; case SparqlUpdateCommandType.Drop: g.Assert(root, RDF.PropertyType, SP.ClassDrop); DropCommand drop = (DropCommand)query; if (drop.TargetUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(drop.TargetUri)); } g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(((DropCommand)query).TargetUri)); break; case SparqlUpdateCommandType.Insert: g.Assert(root, RDF.PropertyType, SP.ClassModify); InsertCommand insert = (InsertCommand)query; if (insert.GraphUri != null) { g.Assert(root, SP.PropertyWith, RDFUtil.CreateUriNode(insert.GraphUri)); } g.Assert(root, SP.PropertyInsertPattern, insert.InsertPattern.ToSpinRdf(g, varTable)); g.Assert(root, SP.PropertyWhere, insert.WherePattern.ToSpinRdf(g, varTable)); break; case SparqlUpdateCommandType.InsertData: g.Assert(root, RDF.PropertyType, SP.ClassInsertData); g.Assert(root, SP.PropertyData, ((InsertDataCommand)query).DataPattern.ToSpinRdf(g, varTable)); break; case SparqlUpdateCommandType.Load: g.Assert(root, RDF.PropertyType, SP.ClassLoad); LoadCommand load = (LoadCommand)query; if (load.SourceUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(load.SourceUri)); } if (load.TargetUri == null) { g.Assert(root, SP.PropertyInto, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyInto, RDFUtil.CreateUriNode(load.TargetUri)); } break; case SparqlUpdateCommandType.Modify: g.Assert(root, RDF.PropertyType, SP.ClassModify); ModifyCommand modify = (ModifyCommand)query; if (modify.GraphUri != null) { g.Assert(root, SP.PropertyWith, RDFUtil.CreateUriNode(modify.GraphUri)); } if (modify.DeletePattern != null) { g.Assert(root, SP.PropertyDeletePattern, modify.DeletePattern.ToSpinRdf(g, varTable)); } if (modify.InsertPattern != null) { g.Assert(root, SP.PropertyInsertPattern, modify.InsertPattern.ToSpinRdf(g, varTable)); } g.Assert(root, SP.PropertyWhere, modify.WherePattern.ToSpinRdf(g, varTable)); break; case SparqlUpdateCommandType.Move: g.Assert(root, RDF.PropertyType, SP.ClassMove); MoveCommand move = (MoveCommand)query; if (move.SourceUri == null) { g.Assert(root, SP.PropertyGraphIRI, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyGraphIRI, RDFUtil.CreateUriNode(move.SourceUri)); } if (move.DestinationUri == null) { g.Assert(root, SP.PropertyInto, SP.PropertyDefault); } else { g.Assert(root, SP.PropertyInto, RDFUtil.CreateUriNode(move.DestinationUri)); } break; case SparqlUpdateCommandType.Unknown: throw new NotSupportedException("Unkown SPARQL update query encountered " + query.ToString()); break; } return(root); }
// Registering View Items Commands into bindinglist public void AddToCommandList(MoveCommand mc) { MovementCmnds.Add(mc); }
/// <summary> /// Processes a MOVE command /// </summary> /// <param name="cmd">Move Command</param> public void ProcessMoveCommand(MoveCommand cmd) { ProcessMoveCommandInternal(cmd, GetContext()); }
public bool MouseUp(MouseEventArgs e) { if (IsActive) { moving = false; //the undoredo trick, but watch out not to execute it since the MouseMove was the execution! MoveCommand cmd = new MoveCommand(movedShape, Point.Subtract(currentPoint, initialPoint)); UndoManager.UndoStack.Push(cmd); UndoManager.UndoStackInfo.Insert(0,cmd.Text); DeactivateTool(); return true; } return false; }
/// <summary> /// Update carousel buffer(elements). It remove last element and add first by /// move direction. /// </summary> /// <param name="moveCommand"></param> private void UpdateCarousel(MoveCommand moveCommand) { DrawAnimation(moveCommand); int sign = moveCommand == MoveCommand.Left ? -1 : 1; CurrentIndex -= sign; Image Image = CreateControlByUri(ItemsSources[CurrentIndex - sign * (bufferSize / 2)]); if (moveCommand == MoveCommand.Left) { CarouselCanvas.Children.RemoveAt(0); CarouselCanvas.Children.Insert(bufferSize - 1, Image); } else { CarouselCanvas.Children.RemoveAt(bufferSize - 1); CarouselCanvas.Children.Insert(0, Image); } Canvas.SetLeft(Image, carouselCenter.X - Image.Width / 2 - sign * ((int)(bufferSize / 2)) * distanceCenterX); Canvas.SetTop(Image, carouselCenter.Y - Image.Height / 2); }
// Use this for initialization void Start() { t = transform; _walkableTerrain = new string[] { "Terrain", "ActiveEnemy","HitBox" }; _currentState = PlayerState.IDLE; _idleCommand = gameObject.AddComponent<IdleCommand>(); _moveCommand = gameObject.AddComponent<MoveCommand>(); _moveAttackCommand = gameObject.AddComponent<MoveAttackCommand>(); _moveToLevelCommand = gameObject.AddComponent<MoveToAnotherLevelCommand>(); _currentCommand = _idleCommand; _dashingTrail.enabled = false; _weaponTrail.Deactivate(); FlushPreviousCommand(); }
public bool IsSatisfiedBy(MoveCommand moveCommand, Game game) { return((moveCommand is HandKomaMoveCommand) && ((HandKomaMoveCommand)moveCommand).KomaType == KomaHu && game.Clone().PlayWithoutRecord(moveCommand).DoCheckmateWithoutHandMove(moveCommand.Player)); }
public Movement AddCommand(MoveCommand cmd) { commands.Add(cmd); newCommandsAdded = true; return(this); }
public CollisionEvent Move(MoveCommand moveCommand) { return(GameGrid.Move(moveCommand)); }
public async Task <CommandResult> ExecuteAsync(MoveCommand command) { return(await ExecuteCommand(command, EventTypes.MoveCommandExecuted)); }
public ShogiBoardViewModel(GameService gameService, IMessenger messenger, Func <GameSet> gameSetGetter) { Messenger = messenger; this.gameService = gameService; OperationMode = OperationMode.SelectMoveSource; this.gameService.Subscribe(this); StartCommand = new DelegateCommand( async() => { var gameSet = gameSetGetter(); FirstPlayerHands.Name = gameSet.Players[PlayerType.FirstPlayer].Name; SecondPlayerHands.Name = gameSet.Players[PlayerType.SecondPlayer].Name; OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Start(gameSet, cancelTokenSource.Token); //this.gameService.Start(new NegaAlphaAI(9), new NegaAlphaAI(9), GameType.AnimalShogi, this); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode != OperationMode.AIThinking); }); RestartCommand = new DelegateCommand( async() => { OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Restart(cancelTokenSource.Token); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode != OperationMode.AIThinking); }); MoveCommand = new DelegateCommand <object>( async(param) => { if (param == null) { return; } if (OperationMode == OperationMode.SelectMoveSource) { var selectedMoveSource = param as ISelectable; selectedMoveSource.IsSelected = true; OperationMode = OperationMode.SelectMoveDestination; UpdateCanMove(selectedMoveSource); } else if (OperationMode == OperationMode.SelectMoveDestination) { var cell = param as CellViewModel; if (cell != null && cell.CanMove) { MoveCommand move = null; if (cell.MoveCommands.Count() == 1) { move = cell.MoveCommands[0]; } else { var doTransform = Messenger.MessageYesNo("成りますか?"); move = cell.MoveCommands.FirstOrDefault(x => x.DoTransform == doTransform); } //game.Play(move); OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => this.gameService.Play(move, cancelTokenSource.Token)); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); } else { // [動けない位置の場合はキャンセルしすべて更新] OperationMode = OperationMode.SelectMoveSource; Update(); } } }, (param) => { if (param == null) { return(false); } if (OperationMode == OperationMode.SelectMoveSource) { var cell = param as CellViewModel; if (cell != null) { if (cell.Koma == null) { return(false); } return(this.gameService.GetGame().State.TurnPlayer == cell.Koma.Player.ToDomain()); } var hand = param as HandKomaViewModel; if (hand != null) { return(this.gameService.GetGame().State.TurnPlayer == hand.Player.ToDomain()); } } else if (OperationMode == OperationMode.SelectMoveDestination) { return(true); } // [OperationMode.GameEnd] // [OperationMode.AIThinking] // [OperationMode.Stopping] return(false); } ); StopCommand = new DelegateCommand( () => { cancelTokenSource?.Cancel(); // [MEMO:OperationModeを変更すると、この時点でタスクが裏で動いているのに、他の操作ができるようになってしまうが] // [ アプリケーションサービス層でロックしているので一応問題ない(タスクがキャンセルされるまで少し固まる可能性はあるが)] OperationMode = OperationMode.Stopping; }, () => { return(OperationMode == OperationMode.AIThinking || OperationMode == OperationMode.SelectMoveSource || OperationMode == OperationMode.GameEnd); }); ResumeCommand = new DelegateCommand( async() => { OperationMode = OperationMode.AIThinking; cancelTokenSource = new CancellationTokenSource(); await Task.Run(() => { this.gameService.Resume(cancelTokenSource.Token); }); cancelTokenSource = null; // [MEMO:タスクが完了されるまでここは実行されない(AIThinkingのまま)] UpdateOperationModeOnTaskFinished(); }, () => { return(OperationMode == OperationMode.Stopping); }); UndoCommand = new DelegateCommand( () => { this.gameService.Undo(Game.UndoType.Undo); Update(); UndoCommand?.RaiseCanExecuteChanged(); RedoCommand?.RaiseCanExecuteChanged(); }, () => { return(OperationMode == OperationMode.Stopping && this.gameService.GetGame().CanUndo(Game.UndoType.Undo)); }); RedoCommand = new DelegateCommand( () => { this.gameService.Undo(Game.UndoType.Redo); Update(); UndoCommand?.RaiseCanExecuteChanged(); RedoCommand?.RaiseCanExecuteChanged(); }, () => { return(OperationMode == OperationMode.Stopping && this.gameService.GetGame().CanUndo(Game.UndoType.Redo)); }); var ai = new NegaAlphaAI(6); var human = new Human(); FirstPlayerHands = new PlayerViewModel() { Player = Player.FirstPlayer, Name = human.Name }; SecondPlayerHands = new PlayerViewModel() { Player = Player.SecondPlayer, Name = ai.Name }; ForegroundPlayer = Player.FirstPlayer; // [MEMO:タスクで開始していない(コンストラクタなのできない)ので、必ず初手はHumanになるようにする] cancelTokenSource = new CancellationTokenSource(); this.gameService.Start(new GameSet(human, ai, GameType.AnimalShogi), cancelTokenSource.Token); cancelTokenSource = null; }
/// <summary> /// Processes a MOVE command /// </summary> /// <param name="cmd">Move Command</param> public void ProcessMoveCommand(MoveCommand cmd) { this.ProcessMoveCommandInternal(cmd, this.GetContext()); }
private void UpdateGameMovesHistory(GameModel game, MoveCommand moveCommand) { game.MovesHistory.Add(moveCommand); }
public void Move(ArrayList movedItemsList, PointF delta) { var cmd = new MoveCommand(movedItemsList, delta); _undoRedo.AddCommand(cmd); }
public override void TurnOnGUI() { float buttonHeight = 50; float buttonWidth = 150; Rect buttonRect = new Rect(0, Screen.height - buttonHeight * 7, buttonWidth, buttonHeight); ICharacterActionCommand cmd; //move button if (GUI.Button(buttonRect, "Move")) { if (!_isMoving) { GameManager.instance.removeTileHighlights(); _isMoving = true; _isAttacking = false; _hasPerformedAtLeastOneMove = true; _isDefending = false; _isRotating = false; cmd = new MoveCommand(null, null); _cmdManager.CommandStack.Push(cmd); ((MoveCommand)cmd).Execute(); GameManager.instance.highlightTilesAt(gridPosition, Color.blue, movementPerActionPoint, false); } else { _isMoving = false; _isAttacking = false; _hasPerformedAtLeastOneMove = false; _isDefending = false; _isRotating = false; //GameManager.instance.removeTileHighlights(); } } //attack/heal button buttonRect = new Rect(0, Screen.height - buttonHeight * 6, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "Attack")) { if (!_isAttacking) { //GameManager.instance.removeTileHighlights(); _isMoving = false; _isAttacking = true; _hasPerformedAtLeastOneMove = true; _isDefending = false; _isRotating = false; cmd = new AttackCommand(null); _cmdManager.CommandStack.Push(cmd); ((AttackCommand)cmd).Execute(); //GameManager.instance.highlightTilesAt(gridPosition, Color.red, attackRange); } else { _isMoving = true; _isAttacking = false; _hasPerformedAtLeastOneMove = true; _isDefending = false; _isRotating = false; //GameManager.instance.removeTileHighlights(); } } //defend button buttonRect = new Rect(0, Screen.height - buttonHeight * 5, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "Defend")) { if (!_isDefending) { //GameManager.instance.removeTileHighlights(); _isMoving = false; _isAttacking = false; _hasPerformedAtLeastOneMove = true; _isDefending = true; _isRotating = false; cmd = new DefendCommand(null); _cmdManager.CommandStack.Push(cmd); ((DefendCommand)cmd).Execute(this); //GameManager.instance.highlightTilesAt(gridPosition, Color.red, attackRange); } else { _isMoving = false; _isAttacking = false; _isDefending = false; _isRotating = false; //GameManager.instance.removeTileHighlights(); } } //rotate button buttonRect = new Rect(0, Screen.height - buttonHeight * 4, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "Rotate")) { if (!_isRotating) { //GameManager.instance.removeTileHighlights(); _isMoving = false; _isAttacking = true; _hasPerformedAtLeastOneMove = false; _isDefending = false; _isRotating = true; cmd = new RotateCommand(null); _cmdManager.CommandStack.Push(cmd); ((RotateCommand)cmd).Execute(); //GameManager.instance.highlightTilesAt(gridPosition, Color.red, attackRange); } else { _isMoving = true; _isAttacking = false; _hasPerformedAtLeastOneMove = true; _isDefending = false; _isRotating = false; //GameManager.instance.removeTileHighlights(); } } //undo button buttonRect = new Rect(0, Screen.height - buttonHeight * 3, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "Undo")) { if (_hasPerformedAtLeastOneMove) { _cmdManager.Undo(this, _cmdManager.LastCharacterAttacked); if (_cmdManager.CommandStack.Count == 0) _hasPerformedAtLeastOneMove = false; } } //skip button buttonRect = new Rect(0, Screen.height - buttonHeight * 2, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "Skip")) { GameManager.instance.GoToNextCharacter(); } //end turn button buttonRect = new Rect(0, Screen.height - buttonHeight * 1, buttonWidth, buttonHeight); if (GUI.Button(buttonRect, "End Turn")) { GameManager.instance.GoToNextCharacter(); } base.TurnOnGUI(); }
/* * 1. Двигаемся вперед пока не наткнемся на препятствие * 2. Сканируем, поворачиваем на направление с максимальной дистанцией * 2.1 Если повсюду препятствия, поворачиваемся на случайный угол(25-180). Переход к пункту 2. * 3. Двигаемся по новому направлению. Переход к п.1. */ public BasicMetaCommandResult ProcessResponce(BasicResponce rsp) { switch (_status) { case Status.Start: Console.WriteLine(_status.ToString()); var startCmd = new RangeScanCommand(MinScanDegree, MaxScanDegree, 200); _status = Status.WaitingForScanResults; return(new BasicMetaCommandResult(MetaCommandAction.Command, startCmd)); case Status.StartScanning: var answer = rsp as AnswerResponce; if (answer != null && answer.Code == Commands.Move) { Console.WriteLine(_status.ToString()); var cmd = new RangeScanCommand(MinScanDegree, MaxScanDegree, 200); _status = Status.WaitingForScanResults; return(new BasicMetaCommandResult(MetaCommandAction.Command, cmd)); } break; case Status.WaitingForScanResults: var responce = rsp as RangeScanResponce; if (responce != null) { Console.WriteLine(_status.ToString()); var degree = FindNewDirection(responce); Console.WriteLine(" Selected degree: " + degree); var rnd = new Random(); if (degree == null) { _turnDirection = (TurnDirection)rnd.Next((int)TurnDirection.Left, (int)TurnDirection.Right + 1); _turnDegree = (byte)rnd.Next(90, 180); _status = Status.StartTurning; break; } if (degree == 0xFF) { _status = Status.StartMoving; break; } if (degree > RangeScanCommand.CenterDegree) { _turnDirection = TurnDirection.Right; _turnDegree = (byte)(degree - RangeScanCommand.CenterDegree); } else { _turnDirection = TurnDirection.Left; _turnDegree = (byte)(RangeScanCommand.CenterDegree - degree); } _status = Status.StartTurning; } break; case Status.StartMoving: Console.WriteLine(_status.ToString()); _status = Status.Moving; var moveCmd = new MoveCommand(MoveDirection.Forward, Speed, 500); return(new BasicMetaCommandResult(MetaCommandAction.Command, moveCmd)); case Status.Moving: if (rsp == null) { var statusCmd = new StatusCommand(RangeScanCommand.CenterDegree, 500); return(new BasicMetaCommandResult(MetaCommandAction.Command, statusCmd)); } Console.WriteLine(_status.ToString()); var status = rsp as StatusResponce; if (status == null) { break; } if (status.DistanceToObstacle < MinDistance) { _status = Status.StartScanning; var stopCmd = new MoveCommand(MoveDirection.Stopped, Speed, 500); return(new BasicMetaCommandResult(MetaCommandAction.Command, stopCmd)); } break; case Status.StartTurning: Console.WriteLine(_status.ToString()); _status = Status.StartScanning; var turnCmd = new TurnCommand(_turnDirection, _turnDegree, 255, true, 500); return(new BasicMetaCommandResult(MetaCommandAction.Command, turnCmd)); case Status.None: break; default: Console.WriteLine("ERROR! Unknown status!"); break; } return(new BasicMetaCommandResult(MetaCommandAction.Idle)); }
public void RotateCommandTest() { SimpleRover rover = new SimpleRover(); SimpleTelemetry st; MoveCommand rotateLeft = new MoveCommand() { Data = "L" }; MoveCommand rotateRight = new MoveCommand() { Data = "R" }; //rotate 1 right, to the east rover.ExecuteCommand(rotateRight); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.East, st.Orientation); //rotate 1 left, to the south rover.ExecuteCommand(rotateRight); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.South, st.Orientation); //rotate 1 left, to the west rover.ExecuteCommand(rotateRight); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.West, st.Orientation); //rotate 1 left, to the north rover.ExecuteCommand(rotateRight); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.North, st.Orientation); //...and final 1 left to the east rover.ExecuteCommand(rotateRight); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.East, st.Orientation); //now, let's go other way // atm we are at: 0,0,r (east) // after 1 right we should be looking north rover.ExecuteCommand(rotateLeft); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.North, st.Orientation); //rotate 1 right, to the west rover.ExecuteCommand(rotateLeft); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.West, st.Orientation); //rotate 1 right, to the south rover.ExecuteCommand(rotateLeft); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.South, st.Orientation); //rotate 1 right, to the east rover.ExecuteCommand(rotateLeft); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.East, st.Orientation); //rotate 1 right, to the north rover.ExecuteCommand(rotateLeft); st = rover.GetTelemetry(); Assert.AreEqual(0, st.Y); Assert.AreEqual(0, st.X); Assert.AreEqual(SimpleOrientation.North, st.Orientation); }
private void SendMoveCommand(Vector3 velocity, Movable movable) { ICommand command = new MoveCommand(movable, velocity); commandProcessor.ProcessCommand(command); }