protected Adapter(Robot robot, ILog logger, string adapterId) { Robot = robot; Logger = logger; Id = adapterId; Rooms = new Collection<string>(); }
public void Register(Robot robot) { robot.Respond(@"help\s*(.*)?$", msg => { IEnumerable<string> help = robot.HelpCommands; var filter = msg.Match[1]; if (!string.IsNullOrWhiteSpace(filter)) { help = help.Where(h => h.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) > -1).ToArray(); if (!help.Any()) { msg.Send(string.Format("No available commands match {0}", filter)); } } var alias = robot.Alias ?? robot.Name; help = help.Select(h => NameReplacementRegex.Replace(h, alias)); msg.Send(string.Join(Environment.NewLine, help.OrderBy(h => h))); msg.Message.Done = true; }); }
public void FillRepo(Robot[] allRobots) { robotsInfo.Clear(); robotsTypeCount.Clear(); foreach (Robot r in allRobots) { RobotInfo info = new RobotInfo(); info.Id = r.id; info.IsFree = true; info.Type = r.type; info.Robot = r; unsafe { info.InitialPosition = new Vector(r.position[0], r.position[1], r.position[2]); info.InitialRotation = new Vector(r.rotation[0], r.rotation[1], r.rotation[2]); } robotsInfo.Add(r.id, info); int value; if (robotsTypeCount.TryGetValue(info.Type, out value)) { robotsTypeCount[info.Type] = value + 1; } else { robotsTypeCount.Add(info.Type, 1); } } }
public void doMove(Robot player, string theMove) { if (theMove == "block") player.Block (); else if (theMove == "unblock") player.UnBlock (); else if (theMove == "leftPunch") player.LeftPunch (); else if (theMove == "rightPunch") player.RightPunch (); else if (theMove == "leftKick") player.LeftKick (); else if (theMove == "rightKick") player.RightKick (); else if (theMove == "RocketLeftArm") player.RocketLeftArm (); else if (theMove == "RocketRightArm") player.RocketRightArm (); else if (theMove == "RocketLeftLeg") player.RocketLeftLeg (); else if (theMove == "RocketRightLeg") player.RocketRightLeg (); else if (theMove == "pickUp") player.Pickup (); }
public override void Initialize(Robot robot) { base.Initialize(robot); _token = robot.GetConfigVariable("MMBOT_SLACK_TOKEN"); _commandTokens = (robot.GetConfigVariable("MMBOT_SLACK_COMMANDTOKENS") ?? string.Empty) .Split(',') .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => s.Trim()) .ToArray(); _logRooms = (robot.GetConfigVariable("MMBOT_SLACK_LOGROOMS") ?? string.Empty) .Split(',') .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => s.Trim()) .ToArray(); if (string.IsNullOrWhiteSpace(_token)) { var helpSb = new StringBuilder(); helpSb.AppendLine("The Slack adapter is not configured correctly and hence will not be enabled."); helpSb.AppendLine("To configure the Slack adapter, please set the following configuration properties:"); helpSb.AppendLine(" MMBOT_SLACK_TOKEN: This is the service token you are given when you add your Bot to your Team Services."); helpSb.AppendLine(" MMBOT_SLACK_COMMANDTOKENS: Optional. The comma delimited list of expected command tokens from the Slack commands hook. If none supplied then any token will be accepted."); helpSb.AppendLine(" MMBOT_SLACK_LOGROOMS: Optional. The comma delimited list of rooms to send log messages to."); helpSb.AppendLine("More info on these values and how to create the mmbot.ini file can be found at https://github.com/mmbot/mmbot/wiki/Configuring-mmbot"); Logger.Warn(helpSb.ToString()); _isConfigured = false; return; } _isConfigured = true; Logger.Info("The Slack adapter is connected"); }
public void TestRobotCreation() { Robot robot = new Robot(new Vector2(10, 11)); Assert.AreEqual(10, robot.Position.X); Assert.AreEqual(11, robot.Position.Y); }
public void Register(Robot robot) { robot.Respond(@"spot me winning", msg => { msg.Send("http://open.spotify.com/track/77NNZQSqzLNqh2A9JhLRkg"); msg.Message.Done = true; }); robot.Respond(@"spot me (.*)$", async msg => { var q = msg.Match[1]; var res = await msg.Http("http://ws.spotify.com/search/1/track.json") .Query(new {q}) .GetJson(); foreach(var t in res.tracks) { try { if (t.album.availability.territories.ToString() == "worldwide" || t.album.availability.territories.ToString().IndexOf("NZ") > -1) { msg.Send(string.Format("http://open.spotify.com/track/{0}", t.href.ToString().Replace("spotify:track:", string.Empty))); msg.Message.Done = true; return; } } catch (Exception) { } } }); }
public void TestReport() { ArrayList line = new ArrayList(); line.Add(new Machine("mixer", "left")); Machine extruder = new Machine("extruder", "center"); extruder.Put("paste"); line.Add(extruder); Machine oven = new Machine("oven", "right"); oven.Put("chips"); line.Add(oven); Robot robot = new Robot(); robot.MoveTo(extruder); robot.Pick(); StringWriter writer = new StringWriter(); RobotReport.Report(writer, line, robot); String expected = "FACTORY REPORT\n" + "Machine mixer\nMachine extruder\n" + "Machine oven bin=chips\n\n" + "Robot location=extruder bin=paste\n" + "========\n"; Assert.That(writer.ToString(), Is.EqualTo(expected)); }
static void Main(string[] args) { // Read the count of the commands that will follow. int commandCount = int.Parse(Console.ReadLine()); // Get the start position of the robot. Vector2 startPosition = Vector2.PositionFromString(Console.ReadLine()); // Create the robot and the tracker. Robot robot = new Robot(startPosition); PositionTracker tracker = new PositionTracker(robot); // Loop until we have read all commands. for (int i = 0; i < commandCount; i++) { // Read the line and create a movement vector. var line = Console.ReadLine(); Vector2 movement = Vector2.MoveDirectionFromString(line); // Move the robot. robot.Move(movement); } // Calculate and display the unique positions visited by the robot. Console.WriteLine($"=> Cleaned: {tracker.CalculatePositionsVisited()}"); }
public void Register(Robot robot) { robot.Respond(@"(youtube|yt)( me)? (.*)", async msg => { var query = msg.Match[3]; var res = await msg.Http("http://gdata.youtube.com/feeds/api/videos") .Query(new Dictionary<string, string> { {"orderBy", "relevance"}, {"max-results", "15"}, {"alt", "json"}, {"q", query} }) .GetJson(); var videos = res.feed.entry; if (videos == null) { await msg.Send(string.Format("No video results for \"{0}\"", query)); return; } dynamic video = msg.Random(videos); foreach (var link in video.link) { if ((string) link.rel == "alternate" || (string) link.type == "text/html") { await msg.Send((string) link.href); } } }); }
public void Register(Robot robot) { robot.Respond(@"(calc|calculate|calculator|convert|math|maths)( me)? (.*)", async msg => { dynamic res = await msg .Http("https://www.google.com/ig/calculator") .Query(new { hl = "en", q = msg.Match[3] }) .Headers(new Dictionary<string, string> { {"Accept-Language", "en-us,en;q=0.5"}, {"Accept-Charset", "utf-8"}, {"User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"} }) .GetJson(); try { await msg.Send((string)res.rhs ?? "Could not compute"); return; } catch (Exception) { } await msg.Send("Could not compute"); }); }
public override void ExecuteAction(Robot.hexapod hexy) { var deg = -30; hexy.LeftFront.hip(-deg); hexy.RightMiddle.hip(1); hexy.LeftBack.hip(deg); hexy.RightFront.hip(deg); hexy.LeftMiddle.hip(1); hexy.RightBack.hip(-deg); Thread.Sleep(500); foreach (var leg in hexy.Legs) { leg.knee(-30); } Thread.Sleep(500); for (var angle = 0; angle <= 45; angle += 3) { foreach (var leg in hexy.Legs) { leg.knee(angle); leg.ankle(-90 + angle); } Thread.Sleep(100); } hexy.Move("Reset"); }
internal Response(Robot robot, ResponseCode code, Byte seqNum, Byte[] data) { Robot = robot; RspCode = code; SeqNum = seqNum; Data = data; }
public void Register(Robot robot) { robot.Respond(@"(cat|cats)( gif)( \d+)?$", async msg => { int number = 1; try { number = Int32.Parse(msg.Match[3]); } catch (Exception) { } if (number == 0) { number = 1; } await CatMeGifCore(msg, number); }); robot.Respond(@"(cat|cats)( me)?( \d+)?$", async msg => { int number = 1; try { number = Int32.Parse(msg.Match[3]); } catch (Exception) { } if (number == 0) { number = 1; } await CatMeCore(msg, number); }); }
public void RobotTest() { var commands = new[] { "Move 2", "Turn right", "Move 4", "Turn left", "Move -5", "Turn right", "Move 10", "Turn left", "Move -2", "Turn left", "Turn left", "Move 5", "Move -2", "Turn right", "Move 1", "Move 0" }; const int expectedX = 13; const int expectedY = -8; var grid = new Grid(); var robot = new Robot(grid); commands.ToList().ForEach(robot.Command); var actualX = robot.PositionX; var actualY = robot.PositionY; Assert.AreEqual(expectedX, actualX); Assert.AreEqual(expectedY, actualY); }
public void TestPositionTrackerCreation() { Robot robot = new Robot(new Vector2(10, 10)); PositionTracker tracker = new PositionTracker(robot); Assert.AreEqual(1, tracker.CalculatePositionsVisited()); }
// Use this for initialization void Start () { observedRobot = FindObjectOfType<RobotScript>().ScriptRobot; hearts = new GameObject[observedRobot.MaxHealth]; RectTransform rt = (RectTransform) heartPrefab.transform; float heartWidth = rt.rect.width; float heartHeight = rt.rect.height; int i = 0; for (; i<observedRobot.MaxHealth; ++i) { Vector2 position = new Vector2(heartWidth/2 + heartMargin + (heartWidth + heartMargin)*i , Screen.height - heartHeight/2 - heartMargin); hearts[i] = Instantiate(heartPrefab, position, Quaternion.identity) as GameObject; hearts[i].transform.parent = UICanvas.transform; } RectTransform rtCoin = (RectTransform)coinUIPrefab.transform; float coinUIHeight = rt.rect.height; Vector2 coinUIPosition = new Vector2((heartWidth + heartMargin*2)*(i+1), Screen.height - coinUIHeight/2 - heartMargin); coinUI = Instantiate(coinUIPrefab, coinUIPosition, Quaternion.identity) as GameObject; coinUI.transform.parent = UICanvas.transform; coinAmountText = coinUI.GetComponentInChildren<Text>(); coinAmountText.text = observedRobot.Coins.ToString(); Vector2 sliderPosition = new Vector2(Screen.width - sliderRightMargin, Screen.height - sliderTopMargin); timeSlider = Instantiate(timeSliderPrefab, sliderPosition, Quaternion.identity) as GameObject; timeSlider.transform.parent = UICanvas.transform; }
public Simulator(IReporter reporter, ILogger logger) { _reporter = reporter; _logger = logger; robot = new Robot(); instruction = new Instruction(); }
public void ExecuteCommands() { var gridCoord = CommandsParser.CommandToCoordinate(_gridCommand); if (gridCoord == null) { Console.WriteLine("Command {0} is invalid", _gridCommand); return; } var grid = new Grid(gridCoord.X, gridCoord.Y); foreach (var robotCmd in _robotCommands) { var coord = CommandsParser.CommandToCoordinate(robotCmd.Orientation); var orientation = CommandsParser.RobotCommandToOrientation(robotCmd.Orientation); if (CommandsParser.IsRobotCommandValid(coord, orientation)) { var robot = new Robot(coord.X, coord.Y, orientation, GetInstructionsParser(), grid); Console.WriteLine(robot.ExecuteInstructions(robotCmd.Instruction)); } else { Console.WriteLine("Command {0} is invalid", robotCmd.Orientation); } } }
public void TestRobot() { Robot testRobot = new Robot(); Position position = null; Assert.IsFalse(testRobot.initialized); testRobot.initialize(2, 2, Orientation.NORTH); Assert.IsTrue(testRobot.initialized); testRobot.TurnLeft(); position = testRobot.GetCurrentPosition(); Assert.AreEqual(2, position.x); Assert.AreEqual(2, position.y); Assert.AreEqual(Orientation.WEST, position.orientation); testRobot.Place(3, 3, Orientation.SOUTH); Assert.AreEqual(3, position.x); Assert.AreEqual(3, position.y); Assert.AreEqual(Orientation.SOUTH, position.orientation); testRobot.TurnRight(); Assert.AreEqual(3, position.x); Assert.AreEqual(3, position.y); Assert.AreEqual(Orientation.WEST, position.orientation); }
public static GameObject MakeLaser(int damage, Vector3 pos, Vector2 dir, RaycastHit hit, Color robotLaserColor, Robot roobit, Color lcolor) { GameObject laser = new GameObject("Laser"); LineRenderer line = laser.AddComponent<LineRenderer>(); line.SetVertexCount(2); line.SetColors(Color.blue, Color.blue); line.SetWidth(0.1f, 0.1f); line.SetPosition(0, pos); line.material.color = lcolor; GameObject obj = hit.transform.gameObject; Vector2 hitPos = pos; if(obj.GetComponent<Player>() != null) hitPos = obj.GetComponent<Player>().gridCoords; else if(obj.GetComponent<Robot>() != null) hitPos = obj.GetComponent<Robot>().gridCoords; else if(obj.GetComponent<DestructibleWall>() != null) hitPos = obj.GetComponent<DestructibleWall>().gridCoords; else if(obj.GetComponent<ExplosiveCrate>() != null) hitPos = obj.GetComponent<ExplosiveCrate>().gridCoords; line.SetPosition(1, hitPos); Laser script = laser.AddComponent<Laser>(); script.dir = dir; script.damageDealt = damage; Destroy(laser, 0.1f); script.Hit(obj); script.laser = laser; script.roobit = roobit; script.target = obj; return laser; }
public void robot_line_charges_robots_upon_attachment() { var recharger = new Mock<IRobotRecharger>(); var robot = new Robot(recharger.Object); new RobotAssemblyLine().Attach(robot); recharger.Verify(x => x.Recharge(robot)); }
public void CreateProgramRobot(Robot robot, Program program) => data.ProgramRobots.Add(new ProgramRobot { Program = program, Robot = robot, CurrentVersion = program.ActualVersion });
public override void Hit(Robot robot) { Debug.Log("StraightLight hit " + robot.name); Assert.IsNotNull<Robot>(robot); Assert.IsTrue(robot.teamColor != teamColor); robot.RecieveDamage(damage); }
public override void ExecuteAction(Robot.hexapod hexy) { var deg = -30; // pickup and put all the feet centered on the floor hexy.LeftFront.replantFoot(-deg, 0.3f); hexy.RightMiddle.replantFoot(1, 0.3f); hexy.LeftBack.replantFoot(deg, 0.3f); Thread.Sleep(1000); Console.WriteLine(hexy.LeftFront.GetStatus()); Console.WriteLine(hexy.RightMiddle.GetStatus()); Console.WriteLine(hexy.LeftBack.GetStatus()); hexy.RightFront.replantFoot(deg, 0.3f); hexy.LeftMiddle.replantFoot(1, 0.3f); hexy.RightBack.replantFoot(-deg, 0.3f); Thread.Sleep(1000); // set all the hip angle to what they should be while standing hexy.LeftFront.hip(-deg); hexy.RightMiddle.hip(1); hexy.LeftBack.hip(deg); hexy.RightFront.hip(deg); hexy.LeftMiddle.hip(1); hexy.RightBack.hip(-deg); }
public override void Shoot(Robot _robot) { if ( _robot.UsePower(_robot.GetWeaponPowerCost(weaponParameter.PowerCost)) ) MagicShoot(_robot); else NormalShoot(_robot); }
//Update timer and return if end effect public bool Update(Robot _robot) { duration += Time.deltaTime; if (duration > parameter.PTime) return true; return false; }
public void PickUp(Robot robot) { coin.PickUp(robot); FindObjectOfType<UIManagerScript>().OnCoinAmountChanged(); SoundEffectsHelper.Instance.MakeCoinPickedUpSound(transform.position); Destroy(this.gameObject); }
public void robot_recharger_automatically_recharges_robot_when_needed_to_perform_work() { var recharger = new Mock<IRobotRecharger>(); var robot = new Robot(recharger.Object); robot.Work(); recharger.Verify(x => x.Recharge(robot)); }
public SharpDistanceTracker(Robot robo, int pin) { robot = robo; robot.sensors.Add(this); sharp = GetPort(pin); sharp.SetLinearScale(0, 255); }
private async Task ValidateRobotCreation(Robot inputRobot) { var sameIdRobots = await _repository.GetAllRobots( new RobotFilter { Ids = new List <Guid>() { inputRobot.Id } }); if (sameIdRobots.Any()) { throw new CrewApiException { ExceptionMessage = $"Robot with same id {inputRobot.Id} already exists in the repository !", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; var sameIdTeamsOfExplorers = await _teamOfExplorersRepository.GetAllTeamsOfExplorers( new TeamOfExplorersFilter { Ids = new List <Guid> { inputRobot.TeamOfExplorersId } }); if (sameIdTeamsOfExplorers.Count != 1) { throw new CrewApiException { ExceptionMessage = $"Robot's TeamOfExplorers id {inputRobot.TeamOfExplorersId} does not correspond to any team !", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; var sameTeamIdExplorers = await _explorerRepository.GetAllExplorers( new ExplorerFilter { TeamId = inputRobot.TeamOfExplorersId }); var sameTeamIdShuttles = await _shuttleRepository.GetAllShuttles( new ShuttleFilter { Ids = new List <Guid> { sameIdTeamsOfExplorers.First().ShuttleId } }); if (sameTeamIdShuttles.Any()) { if (sameTeamIdExplorers > sameTeamIdShuttles.First().MaxCrewCapacity) { throw new CrewApiException { ExceptionMessage = $"Adding Robot with id {inputRobot.TeamOfExplorersId} exceeds shuttle's {sameTeamIdShuttles.First().Id} max crew capacity !", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } } ; var nameAlikeRobots = await _repository.GetAllRobots( new RobotFilter { ToSearch = inputRobot.Name, PerfectMatch = true }); if (nameAlikeRobots.Any()) { throw new CrewApiException { ExceptionMessage = $"Robot name {inputRobot.Name} is not unique !", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; var correspondingTeam = await _teamOfExplorersRepository.GetAllTeamsOfExplorers( new TeamOfExplorersFilter { Ids = new List <Guid> { inputRobot.TeamOfExplorersId } }); if (correspondingTeam.Any()) { var correspondingShuttle = await _shuttleRepository.GetAllShuttles( new ShuttleFilter { Ids = new List <Guid> { correspondingTeam.First().ShuttleId } }); if (correspondingShuttle.Any()) { var client = _clientFactory.CreateClient(); var planetId = Guid.Parse(await(await client.GetAsync( $"http://localhost:5001/exports?shuttleId={correspondingShuttle.First().Id}")).Content .ReadAsStringAsync()); using var httpResponse = await client.PutAsync( $"http://localhost:5001/exports/update" + $"?shuttleId={correspondingShuttle.First().Id}&planetId={planetId}&numberOfRobotsDelta={1}", null); httpResponse.EnsureSuccessStatusCode(); } } } } }
/// <summary> /// Returns the RAPID declaration code line of the this action. /// </summary> /// <param name="robot"> The Robot were the code is generated for. </param> /// <returns> An empty string. </returns> public override string ToRAPIDDeclaration(Robot robot) { return(string.Empty); }
public BridgeBehavior(Robot robot, MachinaBridgeWindow parent) { this._robot = robot; this._parent = parent; }
protected override async Task UnregisterFromRobotEventsAsync(Robot robot) { controller.OnCameraFrameProcessingResult -= Controller_OnCameraFrameProcessingResult; }
protected override async Task RegisterWithRobotEventsAsync(Robot robot) { controller.OnCameraFrameProcessingResult += Controller_OnCameraFrameProcessingResult; }
public void Visit(Robot robot) { Debug.Log("Robot waking up."); }
public static void MoveOut(Robot robot, int width, int height) { MoveToDestination(robot, width, height); }
public Task <GrpcAgentResult <Robot> > UpdateAsync(Robot value, Guid id, GrpcRequestOptions?requestOptions = null) => RobotServiceAgent.UpdateAsync(Check.NotNull(value, nameof(value)), id, requestOptions);
internal Inventory(Robot robot) { items = new List <Item>(); Robot = robot; }
public void CleanRoom(Robot robot) { HashSet <string> v = new HashSet <string>(); BacktrackRobotCleaner(v, robot, 0, 0, 0); }
public Rescue(Robot robot) : base() { this.robot = robot; }
public async Task <bool> UpdateRobot(Robot inputRobot) { _robotValidator.Validate(inputRobot); var sameIdRobots = await _repository.GetAllRobots( new RobotFilter { Ids = new List <Guid> { inputRobot.Id } }); if (!sameIdRobots.Any()) { throw new CrewApiException { ExceptionMessage = $"Cannot update non-existant robot {inputRobot.Id}.", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; if (inputRobot.Name != sameIdRobots.First().Name) { var sameNameRobots = await _repository.GetAllRobots( new RobotFilter { ToSearch = inputRobot.Name, PerfectMatch = true }); if (sameNameRobots.Any(h => h.Id != inputRobot.Id)) { throw new CrewApiException { ExceptionMessage = $"Cannot update Robot name {inputRobot.Name} to one that already exists.", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; } if (inputRobot.TeamOfExplorersId != sameIdRobots.First().TeamOfExplorersId) { var sameIdTeamOfExplorers = await _teamOfExplorersRepository.GetAllTeamsOfExplorers( new TeamOfExplorersFilter { Ids = new List <Guid> { inputRobot.TeamOfExplorersId } }); if (!sameIdTeamOfExplorers.Any()) { throw new CrewApiException { ExceptionMessage = $"Team with id {inputRobot.TeamOfExplorersId} does not exist.", Severity = ExceptionSeverity.Error, Type = ExceptionType.ServiceException } } ; } var robot = sameIdRobots.First(); robot.UpdateByReflection(inputRobot); return(await _repository.UpdateRobot(robot)); }
public static double LotToVolume(this Robot robot, double LotSize) { return(robot.Symbol.NormalizeVolumeInUnits(robot.Symbol.LotSize * LotSize)); }
internal void DownloadDrivers() { Logger.Info("Downloading Machina Drivers for " + _robotBrand + " robot on " + txtbox_IP.Text + ":" + txtbox_Port.Text); // Create a fake robot not to interfere with the main one Robot driverBot = Robot.Create(_robotName, _robotBrand); driverBot.ControlMode(ControlType.Online); var parameters = new Dictionary <string, string>() { { "HOSTNAME", txtbox_IP.Text }, { "PORT", txtbox_Port.Text } }; var files = driverBot.GetDeviceDriverModules(parameters); // Clear temp folder string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "machina_modules"); //https://stackoverflow.com/a/1288747/1934487 System.IO.DirectoryInfo di = new DirectoryInfo(path); if (di.Exists) { Logger.Debug("Clearing " + path); foreach (FileInfo file in di.GetFiles()) { Logger.Debug("Deleting " + file.FullName); file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { Logger.Debug("Deleting " + dir.FullName); dir.Delete(true); } } else { di.Create(); Logger.Debug("Created " + path); } // Save temp files foreach (var pair in files) { string filename = pair.Key; string content = pair.Value; string filepath = System.IO.Path.Combine(path, filename); try { System.IO.File.WriteAllText(filepath, content, Encoding.ASCII); } catch { Logger.Error("Could not save " + filename + " to " + filepath); Logger.Error("Could not download drivers"); return; } Logger.Debug("Saved module to " + filepath); } // Zip the file string zipPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "machina_modules.zip"); System.IO.FileInfo fi = new FileInfo(zipPath); if (fi.Exists) { fi.Delete(); Logger.Debug("Deleted previous " + zipPath); } ZipFile.CreateFromDirectory(path, zipPath); Logger.Debug("Zipped files to " + zipPath); // Prompt file save dialog: https://www.wpf-tutorial.com/dialogs/the-savefiledialog/ SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Zip file (*.zip)|*.zip"; saveFileDialog.DefaultExt = "zip"; saveFileDialog.AddExtension = true; saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); saveFileDialog.FileName = "machina_modules.zip"; if (saveFileDialog.ShowDialog() == true) { fi = new FileInfo(saveFileDialog.FileName); if (fi.Exists) { fi.Delete(); Logger.Debug("Deleted previous " + saveFileDialog.FileName); } File.Copy(zipPath, saveFileDialog.FileName); Logger.Debug("Copied " + zipPath + " to " + saveFileDialog.FileName); Logger.Info("Drivers saved to " + saveFileDialog.FileName); } }
public static int CalculateInterval(this Robot robot, double price1, double price2) { int gap = (int)((price1 - price2) / robot.Symbol.TickSize); return(gap < 0 ? gap * -1 : gap); //returns to always positive number }
public override void show() { if (!base.isDisposed()) { if (base.areSettingsOpen()) { if (backgroundGraphicString != base.settingPairs.build_hub_background_graphic) { backgroundGraphicString = base.settingPairs.build_hub_background_graphic; BACKGROUND.GetComponent <UnityEngine.UI.Image>().sprite = ImageTools.getSpriteFromString(backgroundGraphicString); } if (platformGraphicString != base.settingPairs.build_hub_platform_graphic) { platformGraphicString = base.settingPairs.build_hub_platform_graphic; PLATFORM.GetComponent <Renderer>().material.mainTexture = new Image(platformGraphicString).getTexture(); } if (colorScheme != base.colorScheme) { colorScheme = ImageTools.getColorFromString(base.settingPairs.color_scheme); SETTINGS_BUTTON.GetComponent <UnityEngine.UI.Image>().color = base.colorScheme; TRAINING_BUTTON.GetComponent <UnityEngine.UI.Image>().color = base.colorScheme; } enableCreditsSpentAnimation = base.settingPairs.credits_spent_animation; enablePreviewRobotAnimation = base.settingPairs.preview_robot_animation; } if (obstacleList.isEnabled()) { obstacleList.update(); } MODES oldMode = mode; updateTabs(); switch (mode) { case MODES.MY_ROBOTS: myRobots.update(base.colorScheme); break; case MODES.WORKSHOP: workshop.updateSettings(base.colorScheme, enableCreditsSpentAnimation); workshop.update(); break; case MODES.STORE: if (oldMode != mode) { store.goToDefaultTab(); } store.updateSettings(base.colorScheme, enableCreditsSpentAnimation); store.update(); break; default: break; } if (currentRobot != null) { if (mode == MODES.WORKSHOP && (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2) || Input.GetKey(KeyCode.Tab) || Input.GetKey(KeyCode.Escape) || Input.GetKey(KeyCode.Return) || Input.GetKey(KeyCode.KeypadEnter))) { updateCurrentRobotInList(); } Part[] robotParts = workshop.getRobotParts().ToArray(); Part[] currentRobotParts = currentRobot.getParts(); bool partsChanged = false; if (robotParts.Length != currentRobotParts.Length) { partsChanged = true; } else { for (int partIndex = 0; partIndex < robotParts.Length; ++partIndex) { if (robotParts[partIndex] != currentRobotParts[partIndex]) { partsChanged = true; break; } } } if (partsChanged) { humanRobotParts = workshop.getHumanParts(); myRobots.updateHumanParts(humanRobotParts); workshop.updateHumanParts(humanRobotParts); store.updateHumanParts(humanRobotParts); for (int robotIndex = 0; robotIndex < myRobotsList.Count; ++robotIndex) { if (currentRobot == myRobotsList[robotIndex]) { currentRobot = workshop.getRobot(); myRobotsList[robotIndex] = currentRobot; myRobots.updateMyRobots(myRobotsList); List <Part> robotPartList = new List <Part>(); robotPartList.AddRange(robotParts); workshop.updateRobotParts(robotPartList); store.updateRobotParts(robotPartList); break; } } } Part partBought = store.getPartBought(); humanRobotParts = workshop.getHumanParts(); if (partBought != null) { humanRobotParts.Add(partBought); workshop.updateHumanParts(humanRobotParts); store.updateHumanParts(humanRobotParts); } credits = (workshop.getUpdatedCredits() < store.getUpdatedCredits()) ? workshop.getUpdatedCredits() : store.getUpdatedCredits(); myRobots.updateCredits(credits); workshop.updateCredits(credits); store.updateCredits(credits); } if (mode == MODES.MY_ROBOTS) { Robot robotBeingPreviewed = myRobots.getRobotBeingPreviewed(); if (robotBeingPreviewed != null) { if (robotBeingPreviewed.getHead().getShape() == Shape.SHAPES.HEMISPHERE && !previewRobot.getHead().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getHead().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getHead().GAME_OBJECT.transform.localPosition.x, previewRobot.getHead().GAME_OBJECT.transform.localPosition.y - .5f, previewRobot.getHead().GAME_OBJECT.transform.localPosition.z); } else if (robotBeingPreviewed.getHead().getShape() != Shape.SHAPES.HEMISPHERE && previewRobot.getHead().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getHead().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getHead().GAME_OBJECT.transform.localPosition.x, previewRobot.getHead().GAME_OBJECT.transform.localPosition.y + .5f, previewRobot.getHead().GAME_OBJECT.transform.localPosition.z); } previewRobot.getHead().changeTextureAndShape(robotBeingPreviewed.getHead().getImage().getTexture(), MESHES[(int)robotBeingPreviewed.getHead().getShape()], robotBeingPreviewed.getHead().getShape()); if (robotBeingPreviewed.getBody().getShape() == Shape.SHAPES.HEMISPHERE && !previewRobot.getBody().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getBody().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getBody().GAME_OBJECT.transform.localPosition.x, previewRobot.getBody().GAME_OBJECT.transform.localPosition.y - .5f, previewRobot.getBody().GAME_OBJECT.transform.localPosition.z); } else if (robotBeingPreviewed.getBody().getShape() != Shape.SHAPES.HEMISPHERE && previewRobot.getBody().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getBody().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getBody().GAME_OBJECT.transform.localPosition.x, previewRobot.getBody().GAME_OBJECT.transform.localPosition.y + .5f, previewRobot.getBody().GAME_OBJECT.transform.localPosition.z); } previewRobot.getBody().changeTextureAndShape(robotBeingPreviewed.getBody().getImage().getTexture(), MESHES[(int)robotBeingPreviewed.getBody().getShape()], robotBeingPreviewed.getBody().getShape()); if (robotBeingPreviewed.getMobility().getShape() == Shape.SHAPES.HEMISPHERE && !previewRobot.getMobility().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getMobility().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getMobility().GAME_OBJECT.transform.localPosition.x, previewRobot.getMobility().GAME_OBJECT.transform.localPosition.y - .5f, previewRobot.getMobility().GAME_OBJECT.transform.localPosition.z); } else if (robotBeingPreviewed.getMobility().getShape() != Shape.SHAPES.HEMISPHERE && previewRobot.getMobility().GAME_OBJECT.GetComponent <MeshFilter>().mesh.name.Contains("Sphere")) { previewRobot.getMobility().GAME_OBJECT.transform.localPosition = new Vector3(previewRobot.getMobility().GAME_OBJECT.transform.localPosition.x, previewRobot.getMobility().GAME_OBJECT.transform.localPosition.y + .5f, previewRobot.getMobility().GAME_OBJECT.transform.localPosition.z); } previewRobot.getMobility().changeTextureAndShape(robotBeingPreviewed.getMobility().getImage().getTexture(), MESHES[(int)robotBeingPreviewed.getMobility().getShape()], robotBeingPreviewed.getMobility().getShape()); } } goToField = workshop.getGoToField(); if (previewRobot != null) { animatePreviewRobot(); } base.show(); } }
// Use this for initialization void Start() { robot = GameObject.Find("Robot").GetComponent <Robot>(); }
public static double ShiftPrice(this Robot robot, double fromPrice, int points) { var priceDiff = robot.Symbol.TickSize * points; return(fromPrice + priceDiff); }
public void CanTurnLeft(string x_coordinate, string y_coordinate, string orientation, string expectedOutput) { robot = new Robot(x_coordinate, y_coordinate, orientation); robot.Turn("L"); Assert.That(robot.Position, Is.EqualTo(expectedOutput)); }
public void ProcessCommand(Mars mars, Robot robot) { robot.CurrentPosition.Orientation = OrientateLeft(robot.CurrentPosition.Orientation); }
public MoveDownCommand(Robot robot) : base(robot) { }
public void ExecuteOn(Robot robot, out int penalty) { robot.MoveForward(out penalty); }
public void InitializeRobot() { rover = new Robot(); }
public void HasPossitionAndOrientation() { robot = new Robot("1", "1", "N"); Assert.That(robot.Position, Is.EqualTo("1 1 N")); }
public RobotAdapter(string id, int capacity) { this.robot = new Robot(id, capacity); }
public void Setup() { this.robot = new Robot("Test", 50); this.robotManager = new RobotManager(1); this.robotManager.Add(this.robot); }
public override int Execute(Robot robo) { return(Next()); }
public static void SortMap(int maxDistance) { openedMapsLoc = null; Game.PrintMessage("Bagl s mapkami >"); UOItem containerFrom = new UOItem(UIManager.TargetObject()); if (containerFrom.Serial.IsValid && containerFrom.Exist) { foreach (UOItem item in containerFrom.Items) { if (item.Graphic == mapka.Graphic) { item.Move(1, World.Player.Backpack); Game.Wait(); } } } foreach (UOItem item in World.Player.Backpack.Items) { if (item.Graphic == mapka.Graphic) { item.Use(); Game.Wait(); } } Game.PrintMessage("OpenedMapsLoc: " + OpenedMapsLoc.Count); Dictionary <string, List <uint> > groups = new Dictionary <string, List <uint> >(); foreach (KeyValuePair <string, List <uint> > kvp in OpenedMapsLoc) { string[] pos = kvp.Key.Split(','); UOPositionBase mapPos = new UOPositionBase(ushort.Parse(pos[0]), ushort.Parse(pos[1]), 0); bool found = false; foreach (KeyValuePair <string, List <uint> > groupkvp in groups) { string[] gruppos = groupkvp.Key.Split(','); UOPositionBase groupmapPos = new UOPositionBase(ushort.Parse(gruppos[0]), ushort.Parse(gruppos[1]), 0); if (Robot.GetRelativeVectorLength(groupmapPos, mapPos) < maxDistance) { groups[groupkvp.Key].AddRange(kvp.Value); found = true; break; } } if (!found) { if (groups.ContainsKey(mapPos.ToString())) { groups[mapPos.ToString()].AddRange(kvp.Value); } else { groups.Add(mapPos.ToString(), kvp.Value); } } } //pytlik obyc 5 rad 20; //4 sloupce po 20 ushort currentCol = 10; ushort currentRow = 1; foreach (KeyValuePair <string, List <uint> > kvp in groups) { ushort colItemPos = currentCol; foreach (uint serial in kvp.Value) { UOItem item = new UOItem(serial); item.Move(1, containerFrom, colItemPos, currentRow); colItemPos++; Game.Wait(); } currentCol = (ushort)(currentCol + 20); if (currentCol > 120) { currentCol = 10; currentRow = (ushort)(currentRow + 16); } } }