public bool Wait(TimeSpan timeout) { SpinWait s = new SpinWait(); bool waitResult = true; while (m_state == 0) { if (s.Spin() >= s_spinCount) { if (m_eventObj == null) { ManualResetEvent newEvent = new ManualResetEvent(m_state == 1); if (Interlocked.CompareExchange<EventWaitHandle>( ref m_eventObj, newEvent, null) == null) { // If someone set the flag before seeing the new // event obj, we must ensure it’s been set. if (m_state == 1) m_eventObj.Set(); } else { // Lost the race w/ another thread. Just use // its event. newEvent.Close(); } } waitResult = m_eventObj.WaitOne(timeout); } } return waitResult; }
/// <summary> /// Initializes a new instance of the <see cref="GlimpseRequest" /> class. /// </summary> /// <param name="requestId">The request id.</param> /// <param name="requestMetadata">The request metadata.</param> /// <param name="tabData">The plugin data.</param> /// <param name="displayData">The display data</param> /// <param name="duration">The duration.</param> public GlimpseRequest(Guid requestId, IRequestMetadata requestMetadata, IDictionary<string, TabResult> tabData, IDictionary<string, TabResult> displayData, TimeSpan duration) : this() { RequestId = requestId; TabData = tabData; DisplayData = displayData; Duration = duration; RequestHttpMethod = requestMetadata.RequestHttpMethod; RequestIsAjax = requestMetadata.RequestIsAjax; RequestUri = requestMetadata.RequestUri; ResponseStatusCode = requestMetadata.ResponseStatusCode; ResponseContentType = requestMetadata.ResponseContentType; ClientId = requestMetadata.GetCookie(Constants.ClientIdCookieName) ?? requestMetadata.ClientId; UserAgent = requestMetadata.GetHttpHeader(Constants.UserAgentHeaderName); Guid parentRequestId; #if NET35 if (RequestIsAjax && Glimpse.Core.Backport.Net35Backport.TryParseGuid(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId)) { ParentRequestId = parentRequestId; } #else if (RequestIsAjax && Guid.TryParse(requestMetadata.GetHttpHeader(Constants.HttpRequestHeader), out parentRequestId)) { ParentRequestId = parentRequestId; } #endif }
/// <summary> /// Constructor /// </summary> /// <param name="idleTTL">the idle time to live value</param> public IdleExpiration(TimeSpan idleTTL) { this.SetBit(IS_VARIANT); _idleTimeToLive = (int)idleTTL.TotalSeconds; _lastTimeStamp = AppUtil.DiffSeconds(DateTime.Now); _hintType = ExpirationHintType.IdleExpiration; }
public Game(UserControl userControl, Canvas drawingCanvas, Canvas debugCanvas, TextBlock txtDebug) { //Initialize IsActive = true; IsFixedTimeStep = true; TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16); Components = new List<DrawableGameComponent>(); World = new World(new Vector2(0, 0)); _gameTime = new GameTime(); _gameTime.GameStartTime = DateTime.Now; _gameTime.FrameStartTime = DateTime.Now; _gameTime.ElapsedGameTime = TimeSpan.Zero; _gameTime.TotalGameTime = TimeSpan.Zero; //Setup Canvas DrawingCanvas = drawingCanvas; DebugCanvas = debugCanvas; TxtDebug = txtDebug; UserControl = userControl; //Setup GameLoop _gameLoop = new Storyboard(); _gameLoop.Completed += GameLoop; _gameLoop.Duration = TargetElapsedTime; DrawingCanvas.Resources.Add("gameloop", _gameLoop); }
/// <summary> /// Creates an instance of the SplunkViaHttp context /// </summary> public SplunkContext(SplunkClient.Scheme scheme, string host, int port, string index, string username, string password, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true) : base(scheme, host, port, timeout, handler, disposeHandler) { Index = index; Username = username; Password = password; }
public async Task<bool> Exists(string fileName, TimeSpan expiration) { try { var exists = true; var file = await _baseFolder.TryGetItemAsync(fileName.CleanCharacters()); if (file != null) { var createdAt = file.DateCreated; var timeDiff = (DateTimeOffset.Now - createdAt); if (timeDiff > expiration) exists = false; return exists; } else return false; } catch (FileNotFoundException) { return false; } }
public XNAAsyncDispatcher(TimeSpan dispatchInterval) { FrameworkDispatcher.Update(); this._frameworkDispatcherTimer = new DispatcherTimer(); this._frameworkDispatcherTimer.Tick += new EventHandler(frameworkDispatcherTimer_Tick); this._frameworkDispatcherTimer.Interval = dispatchInterval; }
public static ITcpConnection CreateConnectingTcpConnection(Guid connectionId, IPEndPoint remoteEndPoint, TcpClientConnector connector, TimeSpan connectionTimeout, Action<ITcpConnection> onConnectionEstablished, Action<ITcpConnection, SocketError> onConnectionFailed, bool verbose) { var connection = new TcpConnectionLockless(connectionId, remoteEndPoint, verbose); // ReSharper disable ImplicitlyCapturedClosure connector.InitConnect(remoteEndPoint, (_, socket) => { if (connection.InitSocket(socket)) { if (onConnectionEstablished != null) onConnectionEstablished(connection); connection.StartReceive(); connection.TrySend(); } }, (_, socketError) => { if (onConnectionFailed != null) onConnectionFailed(connection, socketError); }, connection, connectionTimeout); // ReSharper restore ImplicitlyCapturedClosure return connection; }
static Configuration() { AnnounceDir = ConfigurationSettings.AppSettings["AnnounceDir"].ToString(); IconDir = ConfigurationSettings.AppSettings["IconDir"].ToString(); AudioDir = ""; AnnouncementMaxDuration = new TimeSpan(0, 20, 0); }
/// <summary> /// Initializes the service. /// </summary> /// <param name="pollingInterval">The polling interval. If <c>default(TimeSpan)</c>, no polling will be enabled.</param> /// <returns>Task.</returns> /// <remarks>Note that this method is optional but will start the service. If this method is not called, the service will be initialized /// in the <see cref="ValidateLicense" /> method.</remarks> public virtual void Initialize(TimeSpan pollingInterval = default(TimeSpan)) { CreateLicenseListeningSockets(); if (_pollingTimer.Enabled) { Log.Debug("Stopping network polling"); _pollingTimer.Stop(); _pollingTimer.Elapsed -= OnPollingTimerElapsed; } if (pollingInterval != default(TimeSpan)) { if (pollingInterval < SearchTimeout) { Log.Warning("Polling interval is smaller than SearchTimeout, defaulting to SearchTimeout + 5 seconds"); pollingInterval = SearchTimeout.Add(TimeSpan.FromSeconds(5)); } Log.Debug("Starting network polling with an interval of '{0}'", pollingInterval); _pollingTimer.Interval = pollingInterval.TotalMilliseconds; _pollingTimer.Elapsed += OnPollingTimerElapsed; _pollingTimer.Start(); } }
public override void Update(TimeSpan elapsed) { if (Reflected) Move(); Reflected = false; base.Update(elapsed); }
/// <summary> /// 非同步刷新最新資訊 /// </summary> /// <returns></returns> public async Task RefreshAsync() { HttpClient client = new HttpClient(); HtmlDocument HTMLDoc = new HtmlDocument(); HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource)); var script = HTMLDoc.DocumentNode.Descendants("script") .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray(); var tempAry = script.First() .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select((x, i) => new { index = i, item = x }) .GroupBy(x => Math.Floor(x.index / 4.0)); this.LastPassed = null; this.Delay = new TimeSpan(); foreach (var item in tempAry) { string[] temp = item.Select(x=>x.item).ToArray(); if(temp[3] == "TRSearchResult.push('x')") { this.LastPassed = await Station.GetStationByNameAsync( innerString(temp[0],"'","'") ); } } var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0); this.Delay= time; }
protected override void Update(TimeSpan gameTime) { if (this.CurrentState == States.Menu) { Input input = WaveServices.Input; if ((input.TouchPanelState.IsConnected && input.TouchPanelState.Count > 0) || (input.KeyboardState.IsConnected && (input.KeyboardState.Space == ButtonState.Pressed || input.KeyboardState.A == ButtonState.Pressed || input.KeyboardState.S == ButtonState.Pressed || input.KeyboardState.D == ButtonState.Pressed || input.KeyboardState.W == ButtonState.Pressed || input.KeyboardState.Up == ButtonState.Pressed || input.KeyboardState.Down == ButtonState.Pressed || input.KeyboardState.Left == ButtonState.Pressed || input.KeyboardState.Right == ButtonState.Pressed))) { this.CurrentState = States.GamePlay; } } else if (this.CurrentState == States.GamePlay) { if (this.player.Life <= 0) { this.CurrentState = States.GameOver; } } }
protected override void Update(TimeSpan gameTime) { input = WaveServices.Input; if (input.KeyboardState.IsConnected) { keyboardState = input.KeyboardState; if (keyboardState.W == ButtonState.Pressed) { MoveCamera(ref forward); } if (keyboardState.S == ButtonState.Pressed) { MoveCamera(ref back); } if (keyboardState.A == ButtonState.Pressed) { MoveCamera(ref left); } if (keyboardState.D == ButtonState.Pressed) { MoveCamera(ref right); } } var rotationMatrix = (Matrix.CreateRotationX(MathHelper.ToRadians(45.0f)) * Matrix.CreateRotationY(MathHelper.ToRadians(30.0f))); Vector3 transformedReference = Vector3.Transform(Vector3.Down, rotationMatrix); Vector3 cameraLookat = Camera.Position + transformedReference; var width = WaveServices.Platform.ScreenWidth / 24; var height = WaveServices.Platform.ScreenHeight / 24; //camera.Projection = Matrix.CreateOrthographic(width, height, camera.NearPlane, camera.FarPlane); Camera.LookAt = cameraLookat; }
public SubscriptionClient(IServiceBus bus, SubscriptionRouter router, Uri subscriptionServiceUri, TimeSpan startTimeout) { _bus = bus; _router = router; _subscriptionServiceUri = subscriptionServiceUri; _startTimeout = startTimeout; _network = router.Network; if (_log.IsDebugEnabled) _log.DebugFormat("Starting SubscriptionClient using {0}", subscriptionServiceUri); VerifyClientAndServiceNotOnSameEndpoint(bus); _ready.Reset(); var consumerInstance = new SubscriptionMessageConsumer(_router, _network); _unsubscribeAction = _bus.ControlBus.SubscribeInstance(consumerInstance); _unsubscribeAction += _bus.ControlBus.SubscribeContextHandler<SubscriptionRefresh>(Consume); _subscriptionEndpoint = _bus.GetEndpoint(subscriptionServiceUri); _producer = new SubscriptionServiceMessageProducer(router, _subscriptionEndpoint); WaitForSubscriptionServiceResponse(); }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or the timeout /// expires, whichever comes first.</para> /// <para>If no timeout is given, take it from the innermost enclosing `within` /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor"..</para> /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/> /// </para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> /// <param name="max">The maximum duration. If undefined, uses the remaining time /// (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor".</param> /// <param name="message">The message used if the timeout expires.</param> public void AwaitCondition(Func<bool> conditionIsFulfilled, TimeSpan? max, string message) { var maxDur = RemainingOrDilated(max); var interval = new TimeSpan(maxDur.Ticks / 10); var logger = _testState.TestKitSettings.LogTestKitCalls ? _testState.Log : null; InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, (format, args) => AssertionsFail(format, args, message), logger); }
internal async Task<SerialDevice> GetSerialDeviceAsync(string identifier, int baudRate, TimeSpan readTimeout, TimeSpan writeTimeout) { var deviceInformationCollection = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector()); var selectedPort = deviceInformationCollection.FirstOrDefault(d => d.Id.Contains(identifier) || d.Name.Equals(identifier)); if (selectedPort == null) { return null; } var serialDevice = await SerialDevice.FromIdAsync(selectedPort.Id); if (serialDevice == null) { return null; } serialDevice.ReadTimeout = readTimeout; serialDevice.WriteTimeout = writeTimeout; serialDevice.BaudRate = (uint)baudRate; serialDevice.Parity = SerialParity.None; serialDevice.StopBits = SerialStopBitCount.One; serialDevice.DataBits = 8; serialDevice.Handshake = SerialHandshake.None; Debug.WriteLine($"Found - {identifier}"); return serialDevice; }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or until a timeout</para> /// <para>The timeout is taken from the innermost enclosing `within` /// block (if inside a `within` block) or the value specified in config value "akka.test.single-expect-default". /// The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor"..</para> /// <para>A call to <paramref name="conditionIsFulfilled"/> is done immediately, then the threads sleep /// for about a tenth of the timeout value, before it checks the condition again. This is repeated until /// timeout or the condition evaluates to <c>true</c>. To specify another interval, use the overload /// <see cref="AwaitCondition(System.Func{bool},System.Nullable{System.TimeSpan},System.Nullable{System.TimeSpan},string)"/> /// </para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> public void AwaitCondition(Func<bool> conditionIsFulfilled) { var maxDur = RemainingOrDefault; var interval = new TimeSpan(maxDur.Ticks / 10); var logger = _testState.TestKitSettings.LogTestKitCalls ? _testState.Log : null; InternalAwaitCondition(conditionIsFulfilled, maxDur, interval, (format, args) => _assertions.Fail(format, args), logger); }
public override void Update() { time -= GameGlobals.gameTime.ElapsedGameTime; if (time < TimeSpan.Zero) ScreenManager.CurrentScreen = destination; }
public CommandMessage(string cmdText, TimeSpan duration, string type, string connectionGUID) { CommandText = cmdText; Duration = duration; Type = type; ConnectionGUID = connectionGUID; }
protected void Arrange() { var random = new Random(); _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture); _operationTimeout = TimeSpan.FromSeconds(30); _encoding = Encoding.UTF8; _disconnectedRegister = new List<EventArgs>(); _errorOccurredRegister = new List<ExceptionEventArgs>(); _channelDataEventArgs = new ChannelDataEventArgs( (uint)random.Next(0, int.MaxValue), new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) }); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _channelMock = new Mock<IChannelSession>(MockBehavior.Strict); _sequence = new MockSequence(); _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); _channelMock.InSequence(_sequence).Setup(p => p.Open()); _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, _subsystemName, _operationTimeout, _encoding); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); }
/// <summary> /// A simpler alternative to the irritatingly useless FileSystemWatcher /// </summary> /// <param name="file">The file to monitor</param> /// <param name="refreshPeriod">The refresh period.</param> /// <param name="scheduler">The scheduler.</param> /// <returns></returns> public static IObservable<FileNotification> WatchFile(this FileInfo file, TimeSpan? refreshPeriod = null, IScheduler scheduler = null) { return Observable.Create<FileNotification>(observer => { var refresh = refreshPeriod ?? TimeSpan.FromMilliseconds(250); scheduler = scheduler ?? Scheduler.Default; FileNotification notification = null; return scheduler.ScheduleRecurringAction(refresh, () => { try { notification = notification == null ? new FileNotification(file) : new FileNotification(notification); observer.OnNext(notification); } catch (Exception ex) { notification = new FileNotification(file, ex); observer.OnNext(notification); } }); }).DistinctUntilChanged(); }
public void Enter(TimeSpan timeout) { if (!this.TryEnter(timeout)) { throw Fx.Exception.AsError(CreateEnterTimedOutException(timeout)); } }
public void Update() { if (_deploysRemaining > 0 && _time.Minutes % 15 == 0 && _time.Seconds == 0) { _deploysRemaining--; //_trains.Add(new Bullet(_stations["Glenhuntly"].GetPlatform(1))); //_trains.Add(new Bullet(_stations["Windsor"].GetPlatform(1))); //_trains.Add(new Bullet(_stations["Hawthorn"].GetPlatform(1))); //_trains.Add(new Bullet(_stations["Jolimont"].GetPlatform(1))); for (int i = 0; i < 75; i++) { Station station = _links[MathUtils.Rand(0, _links.Count - 1)].InStation; Platform platform = station.GetPlatform(MathUtils.Rand(1, station.PlatformCount)); if (!platform.IsOccupied) { Train train = Train.Generate(platform); platform.Occupy(train); _trains.Add(train); } } } _time = _time.Add(new TimeSpan(0, 0, 1)); foreach (Train train in _trains) train.Update(); }
public static void LinearSmoothMove(Point newPosition, TimeSpan duration) { Point start = Cursor.Position; var rnd = new Random(); // Find the vector between start and newPosition double deltaX = newPosition.X - start.X; double deltaY = newPosition.Y - start.Y; // start a timer var stopwatch = new Stopwatch(); stopwatch.Start(); double timeFraction = 0.0; do { var v = rnd.Next(0, 1000); Trace.WriteLine(stopwatch.Elapsed.Ticks + ", " + v + ", " + (double)(stopwatch.Elapsed.Ticks + v) / duration.Ticks); timeFraction = (double)(stopwatch.Elapsed.Ticks + v * 5) / duration.Ticks; if (timeFraction > 1.0) timeFraction = 1.0; var addX = rnd.Next(0, 10); var addY = rnd.Next(0, 10); var curPoint = new Point(start.X + (int)(timeFraction * deltaX) + addX, start.Y + (int)(timeFraction * deltaY) + addY); Cursor.Position = curPoint; Thread.Sleep(20); } while (timeFraction < 1.0); Cursor.Position = newPosition; }
internal APNGFrame(GraphicsDevice graphicsDevice, Frame frame) { if (frame.fcTLChunk != null) { X = (int) frame.fcTLChunk.XOffset; Y = (int) frame.fcTLChunk.YOffset; Width = (int) frame.fcTLChunk.Width; Height = (int) frame.fcTLChunk.Height; BlendOp = frame.fcTLChunk.BlendOp; DisposeOp = frame.fcTLChunk.DisposeOp; DelayTime = new TimeSpan( TimeSpan.TicksPerSecond*frame.fcTLChunk.DelayNum/frame.fcTLChunk.DelayDen); } else { X = 0; Y = 0; Width = frame.IHDRChunk.Width; Height = frame.IHDRChunk.Height; BlendOp = BlendOps.APNGBlendOpSource; DisposeOp = DisposeOps.APNGDisposeOpNone; DelayTime = TimeSpan.Zero; } // frame.GetStream() is not seekable, so we build a new MemoryStream. FrameTexture = Texture2D.FromStream( graphicsDevice, new MemoryStream(frame.GetStream().ToArray())); MultiplyAlpha(FrameTexture); }
/// <summary> /// Generate a new <see cref="Guid"/> using the comb algorithm. /// </summary> private Guid GenerateComb() { byte[] guidArray = Guid.NewGuid().ToByteArray(); DateTime baseDate = new DateTime(1900, 1, 1); DateTime now = DateTime.Now; // Get the days and milliseconds which will be used to build the byte string TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks); TimeSpan msecs = now.TimeOfDay; // Convert to a byte array // Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333 byte[] daysArray = BitConverter.GetBytes(days.Days); byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.333333)); // Reverse the bytes to match SQL Servers ordering Array.Reverse(daysArray); Array.Reverse(msecsArray); // Copy the bytes into the guid Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2); Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4); return new Guid(guidArray); }
/// <summary> /// Calculates the indicator's components /// </summary> public override void Calculate(SlotTypes slotType) { // Calculation double[] adClosePrice = new double[Bars]; for (int iBar = 1; iBar < Bars; iBar++) if (Time[iBar - 1].Day != Time[iBar].Day) adClosePrice[iBar - 1] = Close[iBar - 1]; // Check the last bar TimeSpan tsBarClosing = Time[Bars - 1].TimeOfDay.Add(new TimeSpan(0, (int)Period, 0)); TimeSpan tsDayClosing = new TimeSpan(24, 0, 0); if (tsBarClosing == tsDayClosing) adClosePrice[Bars - 1] = Close[Bars - 1]; // Saving the components Component = new IndicatorComp[1]; Component[0] = new IndicatorComp(); Component[0].CompName = "Closing price of the day"; Component[0].DataType = IndComponentType.ClosePrice; Component[0].ChartType = IndChartType.NoChart; Component[0].FirstBar = 2; Component[0].Value = adClosePrice; return; }
/// <summary> /// Reads from the stream. /// </summary> /// <param name="timeout">The timeout.</param> /// <returns>Any text read from the stream.</returns> public string Read(TimeSpan timeout) #endif { if (!this.byteStream.Connected || this.internalCancellation.Token.IsCancellationRequested) { return string.Empty; } StringBuilder sb = new StringBuilder(); this.byteStream.ReceiveTimeout = (int)timeout.TotalMilliseconds; DateTime endInitialTimeout = DateTime.Now.Add(timeout); DateTime rollingTimeout = ExtendRollingTimeout(timeout); do { if (this.ParseResponse(sb)) { rollingTimeout = ExtendRollingTimeout(timeout); } } while (!this.internalCancellation.Token.IsCancellationRequested && (this.IsResponsePending || IsWaitForInitialResponse(endInitialTimeout, sb) || #if ASYNC await #endif IsWaitForIncrementalResponse(rollingTimeout))); if (DateTime.Now >= rollingTimeout) { System.Diagnostics.Debug.Print("RollingTimeout exceeded {0}", DateTime.Now.ToString("ss:fff")); } return sb.ToString(); }
/// <summary> Creates a ShutdownParams object with given parameters. /// <param name="customReason"/> and <param name="initiatedBy"/> may be null. </summary> public ShutdownParams(ShutdownReason reason, TimeSpan delay, bool restart, [CanBeNull] string customReason, [CanBeNull] Player initiatedBy) : this(reason, delay, restart) { customReasonString = customReason; InitiatedBy = initiatedBy; }
private bool CanShoot() { System.DateTime now = System.DateTime.Now; System.TimeSpan ts = now - lastShootTime; return(ts.TotalMilliseconds > TIME_BETWEEN_SHOTS && bulletManager.BulletsLeft() >= BULLETS_PER_SHOT); }
// Use this for initialization void Start() { currentTime = 0; trialTime = 0; t = System.TimeSpan.FromSeconds(currentTime); }
//void Start() //{ // transform.eulerAngles = new Vector3(0, -90, 0); // Vector3 angles = transform.eulerAngles; // x = angles.y; // y = angles.x; // if (GetComponent<Rigidbody>()) // { // GetComponent<Rigidbody>().freezeRotation = true; // } // oldTime = System.DateTime.Now; //} // Update is called once per frame void Update() { nowTime = System.DateTime.Now; System.TimeSpan ts1 = new System.TimeSpan(oldTime.Ticks); System.TimeSpan ts2 = new System.TimeSpan(nowTime.Ticks); System.TimeSpan ts = ts2.Subtract(ts1).Duration(); if (ts.Seconds > 8 && !Input.anyKey) { // flag_Roable = true; 3 oldTime = System.DateTime.Now; } if (Input.anyKey) { //// 单指 // if (Input.touchCount == 1) // { // if (Input.GetTouch(0).phase == TouchPhase.Moved) // { // //x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; // //y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; // x = Input.GetAxis("Mouse X") * xSpeed; // y = Input.GetAxis("Mouse Y") * ySpeed; // transform.Rotate(Vector3.up * -x * Time.deltaTime, Space.World); // transform.Rotate(Vector3.right * y * Time.deltaTime, Space.World); // } // } ////双指旋转 //if (Input.touchCount == 2) //{ // if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) // { // //x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; // //y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; // x = Input.GetAxis("Mouse X") * xSpeed; // y = Input.GetAxis("Mouse Y") * ySpeed; // transform.Rotate(Vector3.up * -x * Time.deltaTime, Space.World); // transform.Rotate(Vector3.right * y * Time.deltaTime, Space.World); // } //} //if (Input.touchCount==2 ) //{ // Touch touch = Input.GetTouch(0); // Vector2 deltaPos = touch.deltaPosition; // transform.Rotate(Vector3.down * deltaPos.x, Space.World); // transform.Rotate(Vector3.right * deltaPos.y, Space.World); //} //双指缩放 if (Input.touchCount > 1) { if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) { Vector2 tempPosition1 = Input.GetTouch(0).position; Vector2 tempPosition2 = Input.GetTouch(1).position; if (isEnlarge(oldPosition1, oldPosition2, tempPosition1, tempPosition2)) { float oldScale = transform.localScale.x; float newScale = oldScale * 1.025f; transform.localScale = new Vector3(newScale, newScale, newScale); } else { float oldScale = transform.localScale.x; float newScale = oldScale / 1.025f; transform.localScale = new Vector3(newScale, newScale, newScale); } //备份上一次触摸点的位置,用于对比 oldPosition1 = tempPosition1; oldPosition2 = tempPosition2; } } } }
/// <summary> /// Check if the player gets a daily play reward, so check if the last time he got one was yesterday. /// </summary> public bool CheckDailyPlayReward(SaveLoadManager saveLoadManager) { System.TimeSpan timeDiff = System.DateTime.Now - saveLoadManager.GetLastRewardTime(); return(timeDiff.TotalHours >= 24); }
public static long GetTime() { System.TimeSpan ts = new System.TimeSpan(System.DateTime.UtcNow.Ticks - new System.DateTime(2000, 1, 1, 0, 0, 0).Ticks); return((long)ts.TotalMilliseconds); }
void DateChecker(string dateOfWeak, int m) // WITH SORT { for (int l = 1; l <= 8; l++) { bool brake = false; for (int i = 0; i < DataManager.Instance.data.Count; i++) { if (DataManager.Instance.data[i].data.Contains(dateOfWeak)) { if (DataManager.Instance.data[i].onTheAccount == l) { CreateCellAndHisFilling(i); brake = true; break; } } else { string[] data = DataManager.Instance.data[i].data.Split(','); for (int e = 0; e < data.Length; e++) // чистка от не нужных символов { data[e] = data[e].Replace("[", ""); data[e] = data[e].Replace("]", ""); data[e] = data[e].Replace(" ", ""); } for (int u = 0; u < data.Length; u++) { if (!data[u].Contains("-")) { continue; } string start = ""; string end = ""; string today = dateText[m].text; int index = data[u].IndexOf("-"); for (int p = index - 5; p < index; p++) // start { start += data[u][p]; } for (int j = index + 1; j < index + 6; j++) // end { end += data[u][j]; } createDayAndMounth(start); System.DateTime day1Start = new System.DateTime(System.DateTime.Today.Year, int.Parse(mounth), int.Parse(day)); createDayAndMounth(end); System.DateTime day2End = new System.DateTime(System.DateTime.Today.Year, int.Parse(mounth), int.Parse(day)); createDayAndMounth(today); System.DateTime Today = new System.DateTime(System.DateTime.Today.Year, int.Parse(mounth), int.Parse(day)); if (!(Today > day1Start) || !(Today < day2End)) // если текущий день не попадает в диапозон то .. { continue; } System.TimeSpan interval = new System.TimeSpan(7, 0, 0, 0); System.TimeSpan interval2 = new System.TimeSpan(0, 0, 0, 0); if (data[u].Contains("к.н")) { for (int h = 0; h < 30; h++) { interval2 += interval; if (Today != day1Start + interval2) { continue; } if (DataManager.Instance.data[i].onTheAccount == l) { CreateCellAndHisFilling(i); brake = true; break; } } interval2 = System.TimeSpan.Zero; } else if (data[u].Contains("ч.н")) { interval += new System.TimeSpan(7, 0, 0, 0); for (int h = 0; h < 20; h++) { interval2 += interval; if (Today != day1Start + interval2) { continue; } if (DataManager.Instance.data[i].onTheAccount == l) { CreateCellAndHisFilling(i); brake = true; break; } } interval2 = System.TimeSpan.Zero; } } } if (brake) { break; } } if (!brake) { CreateCellAndHisFilling(-1); } } }
IEnumerator GetUserData() { //if (string.IsNullOrEmpty(WebServices.CookieString)) { UnityWebRequest www = WebServices.Authenticated_Get("me"); yield return(www.SendWebRequest()); if (www.isHttpError || www.isNetworkError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); currUser.username = JsonUtility.FromJson <User>(www.downloadHandler.text).username; currUser.scores = JsonUtility.FromJson <User>(www.downloadHandler.text).scores; Debug.Log("currUser : "******"userScores : " + userScores); currUser.updates = JsonUtility.FromJson <User>(www.downloadHandler.text).updates; updateScores = currUser.updates; currUser.items = JsonUtility.FromJson <User>(www.downloadHandler.text).items; currUser.locations = JsonUtility.FromJson <User>(www.downloadHandler.text).locations; currUser.autoCount = JsonUtility.FromJson <User>(www.downloadHandler.text).autoCount; currUser.autoTime = JsonUtility.FromJson <User>(www.downloadHandler.text).autoTime; currUser.recentLogin = JsonUtility.FromJson <User>(www.downloadHandler.text).recentLogin; currUser.recentLogout = JsonUtility.FromJson <User>(www.downloadHandler.text).recentLogout; if (countCat < currUser.items.Length) { itemSearchLogin(currUser.items, currUser.locations); } if (!string.IsNullOrEmpty(currUser.recentLogin) && !string.IsNullOrEmpty(currUser.recentLogout) && !isLogin) { System.DateTime login = System.DateTime.Parse(currUser.recentLogin); System.DateTime logout = System.DateTime.Parse(currUser.recentLogout); System.TimeSpan passed = login.Subtract(logout); double totalSeconds = passed.TotalSeconds; tempScores = 0; for (int i = 0; i < currUser.autoCount.Length; ++i) { if (currUser.autoCount[i] > 0) { tempScores += (int)(totalSeconds / currUser.autoTime[i]); } } double totalMinutes = passed.TotalMinutes; double totalHours = passed.TotalHours; if (totalMinutes > 1 || totalHours > 1) { totalTime = totalHours > 1.0 ? (int)totalHours : (int)totalMinutes; string str = totalHours > 1.0 ? "hours" : "minutes"; timeManagerBox.gameObject.SetActive(true); timeManagerText.gameObject.SetActive(true); timeManagerText.text = "You logged in " + totalTime.ToString() + " " + str;// + //"\n" + "You earns " + tempScores.ToString() + " points by Auto Clicker Cat!!"; timeManagerBox.GetComponent <Image>().color = new Color32(255, 255, 255, 150); timeManagerText.GetComponent <Text>().color = new Color32(0, 0, 0, 255); //userScores += (int)(totalTime); } isLogin = true; } } //} }
/// <summary> /// Time overloaded constructor /// </summary> public Timer(System.TimeSpan time) { currentTime = time; }
// For rezising images: // https://resizeimage.net/ // TODO for tomorrow: create prefabs to instantiate and follow along video at 18:00 at https://www.youtube.com/watch?v=ae6mW74FZSU // Start is called before the first frame update void Start() { System.DateTime before = System.DateTime.Now; image = images[imageToRender]; Color[] pix = image.GetPixels(); int worldX = image.width; int worldZ = image.height; Vector3[] spawnPositions = new Vector3[pix.Length]; Vector3 startingSpawnPosition = new Vector3(-Mathf.Round(worldX / 2), 0, -Mathf.Round(worldZ / 2)); Vector3 currentSpawnPosition = startingSpawnPosition; int counter = 0; for (int z = 0; z < worldZ; z++) { for (int x = 0; x < worldX; x++) { spawnPositions[counter] = currentSpawnPosition; counter++; currentSpawnPosition.x++; } currentSpawnPosition.x = startingSpawnPosition.x; currentSpawnPosition.z++; } counter = 0; //int whitePix = 0; //int notWhitePix = 0; // NOTE: removing the last 0.0f in Color in the following line will make Unity break??? Color white = new Color(0.0f, 0.0f, 0.0f, 0.0f); //Color black = new Color(0.0f, 0.0f, 0.0f, 0.0f); foreach (Vector3 pos in spawnPositions) { Color c = pix[counter]; // First check for certain colors that would signify a certain object //if (c.r == 0.0f && c.g == 0.0f && c.b == 0.0f) if (c.b > 252f / 255f) { Debug.Log("Making fridge where color is " + c.ToString() + " at pos " + pos.ToString()); Instantiate(fridge, pos, Quaternion.identity); } else if (c.b > 200f / 255f && c.a > .5) { //Debug.Log("c.b > 200f/255f"); //Instantiate(blueObject, pos, Quaternion.identity); } else if (c.a > .500 && c.b < 100f / 255f) // != white) { //Debug.Log("Not white! Color is " + c.ToString() + " at pos " + pos.ToString()); Instantiate(wallObject, pos, Quaternion.identity); //notWhitePix++; } else { //Debug.Log("White"); //whitePix++; // Not instantiating groundObject for performance purposes //Instantiate(groundObject, pos, Quaternion.identity); } counter++; } System.TimeSpan duration = System.DateTime.Now.Subtract(before); Debug.Log("Generation of map took " + duration.Milliseconds + " milliseconds"); //Debug.Log("Found " + whitePix + " white pixels"); //Debug.Log("Found " + notWhitePix + " non-white pixels"); //foreach (Color c in pix) //{ //} //Color white = new Color(0.0f, 0.0f, 0.0f, 0.0f); //for (int i = 0; i < pix.Length; i++) //{ // //Debug.Log("i == " + i); // if (pix[i] == Color.white) // { // Debug.Log("Pixel is white!"); // } // else // { // if (pix[i] != white) // { // Debug.Log("!!pix[i] == " + pix[i]); // } // } //} //Debug.Log("pix.Length == " + pix.Length); }
private bool CanShoot() { System.DateTime now = System.DateTime.Now; System.TimeSpan ts = now - lastShootTime; return(ts.TotalMilliseconds > TIME_BETWEEN_SHOTS && rocketManager.RocketsLeft() > 0); }
private void UpdateTimeAliveText() { // https://forum.unity.com/threads/convert-float-to-time-minutes-and-seconds.676414/ System.TimeSpan ts = System.TimeSpan.FromSeconds(timeAlive); timeAliveText.text = "Time Alive - " + string.Format("{0:00}:{1:00}", ts.TotalMinutes, ts.Seconds); }
public static string FormatTime(System.TimeSpan t) { return(t.Hours + ":" + t.Minutes.ToString("D2") + ":" + t.Seconds.ToString("D2") + "." + t.Milliseconds.ToString("D3")); }
private void UpdateText(float time) { System.TimeSpan ts = System.TimeSpan.FromSeconds(time); timeText.SetText(string.Format("{0:00}:{1:00}.{2:000}", ts.Minutes, ts.Seconds, ts.Milliseconds)); }
void Start() { System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(EndGameStats.remainingTime); chronoText.text = timeSpan.ToString(@"mm\:ss"); }
double ConvertToUnixTimestamp(System.DateTime date) { System.DateTime st = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); System.TimeSpan diff = date - st; return(System.Math.Floor(diff.TotalSeconds)); }
string GiveBestTime(float bestTime) { System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(bestTime); return(string.Format("{0:D2}:{1:D2}:{2:D2}", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10)); }
public void UpdateWeak() { int n = 0; switch (dt.Date.DayOfWeek) { case System.DayOfWeek.Friday: n = 4; break; case System.DayOfWeek.Monday: n = 0; break; case System.DayOfWeek.Saturday: n = 5; break; case System.DayOfWeek.Thursday: n = 3; break; case System.DayOfWeek.Tuesday: n = 1; break; case System.DayOfWeek.Wednesday: n = 2; break; default: break; } setDate(n, dt); if (dt == System.DateTime.Today) { dateText[n].color = Color.red; } else { dateText[n].color = Color.black; } //in left for (int i = 0; i < dateText.Length - (dateText.Length - n - 1); i++) { System.TimeSpan interval = new System.TimeSpan(i, 0, 0, 0); System.DateTime d = dt.Date.Subtract(interval); setDate((dateText.Length - (dateText.Length - n)) - i, d); } //in right int j = 1; for (int i = n + 1; i < dateText.Length; i++) { System.TimeSpan interval = new System.TimeSpan(j, 0, 0, 0); System.DateTime d = dt.Date.Add(interval); j++; setDate(i, d); } for (int i = 0; i < 6; i++) { DateChecker(dateText[i].text, i); } CellIn.SetActive(false); }
public static DBCraftingItem GetCurrentCookingRecipe(int completeQueueSize, System.TimeSpan passedTime, List <DBCraftingItem> allDish, out System.TimeSpan currentPassed, out bool isUnhold) { DBCraftingItem current = null; isUnhold = false; currentPassed = System.TimeSpan.Zero; int cnt = 0; foreach (var item in allDish) { if (cnt >= completeQueueSize) { //There is more product.. but its holding right now! current = item; isUnhold = true; return(current); } if (item.reqTime < passedTime) { //This is made. passedTime -= item.reqTime; cnt++; continue; } //Done.. current = item; break; } if (current == null) { return(null); } currentPassed = passedTime; return(current); }
// Start is called before the first frame update void Start() { System.DateTime sample = System.DateTime.Now; //coordinates = new List<Vector2Int>(); coordinatesHash = new Dictionary <int, Vector2Int>(); areaSize = new List <int>(); string pattern = @"(?<posX>\d+),\s(?<posY>\d+)"; foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(input.text, pattern)) { posX = int.Parse(m.Groups["posX"].Value); posY = int.Parse(m.Groups["posY"].Value); //coordinates.Add(new Vector2Int(posX, posY)); coordinatesHash.Add((int)thisArea, new Vector2Int(posX, posY)); areaSize.Add(1); thisArea++; if (posX > maxX) { maxX = posX; } if (posY > maxY) { maxY = posY; } //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); //cube.transform.position = new Vector3(posX, 0, posY); //cube.GetComponent<Renderer>().material.color = new Color(1, 0, 0); } /* * grid = new int?[maxX+1, maxY+1]; * * for (int i = 0; i < coordinates.Count; i++) * { * posX = coordinates[i].x; * posY = coordinates[i].y; * grid[posX, posY] = i; * } */ for (int x = 0; x <= maxX; x++) { for (int y = 0; y <= maxY; y++) { //if (grid[x, y] == null) if (!coordinatesHash.ContainsValue(new Vector2Int(x, y))) { float smallestDistance = Mathf.Infinity; for (int i = 0; i < areaSize.Count; i++) { float distanceH = Mathf.Abs(x - coordinatesHash[i].x) + Mathf.Abs(y - coordinatesHash[i].y); if (distanceH < smallestDistance) { smallestDistance = distanceH; thisArea = i; } else if (distanceH == smallestDistance) { thisArea = null; } } if (!(x == 0 || x == maxX || y == 0 || y == maxY) && (thisArea != null) && (areaSize[(int)thisArea] != 0)) { areaSize[(int)thisArea]++; //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); //cube.transform.position = new Vector3(x, 0, y); //cube.GetComponent<Renderer>().material.color = new Color(1 / ((float)grid[x, y] / 5), 1 / ((float)grid[x, y] / 5), 1 / ((float)grid[x, y]/5)); } else if ((x == 0 || x == maxX || y == 0 || y == maxY) && (thisArea != null)) { areaSize[(int)thisArea] = 0; //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); //cube.transform.position = new Vector3(x, 0, y); //cube.GetComponent<Renderer>().material.color = new Color(0,0,0); } } } } biggestAreaSize = areaSize[0]; for (int i = 1; i < areaSize.Count; i++) { if (areaSize[i] > biggestAreaSize) { biggestAreaSize = areaSize[i]; //biggestArea = i; } } Debug.Log("Size biggest area: " + biggestAreaSize); //Debug.Log("Biggest area: " + biggestArea); System.TimeSpan elapsed = (System.DateTime.Now - sample); Debug.Log(string.Format("This took {0} milliseconds", elapsed.TotalMilliseconds)); }
public static DBCraftingItem GetCurrentCookingRecipe(int completeQueueSize, System.TimeSpan passedTime, List <DBCraftingItem> allDish, out bool isUnhold) { var temp = System.TimeSpan.Zero; return(GetCurrentCookingRecipe(completeQueueSize, passedTime, allDish, out temp, out isUnhold)); }
private void create_splits_from_xml(string xml_path) { speedrun.RunModel run = new speedrun.RunModel(); XmlDocument doc = new XmlDocument(); doc.Load(xml_path); /////////////////// // Run meta-data run.run.game_meta.name = doc.DocumentElement.SelectSingleNode("/Run/GameName").InnerText; run.run.game_meta.catergory = doc.DocumentElement.SelectSingleNode("/Run/CategoryName").InnerText; System.TimeSpan ts = System.TimeSpan.Parse(doc.DocumentElement.SelectSingleNode("/Run/Offset").InnerText); //run.run.game_meta.start_offset = string.Format("{0}.{0}", ts.Seconds, ts.Milliseconds); run.run.game_meta.start_offset = ts.Seconds + "." + ts.Milliseconds; run.run.game_meta.attempts_count = System.Int32.Parse(doc.DocumentElement.SelectSingleNode("/Run/AttemptCount").InnerText); //////////////// // Split meta-data XmlNode segment_nodelist = doc.DocumentElement.SelectSingleNode("/Run/Segments"); foreach (XmlNode node in segment_nodelist) { speedrun.SplitMeta m = new speedrun.SplitMeta(); m.name = node.SelectSingleNode("Name").InnerText; m.thumb_path = node.SelectSingleNode("Icon").InnerText; // need to take the info which is formated in hh:mm:ss.fffffff in livesplit // and make it a timestamp-friendly time..(ms I think I use..) string pb_time = node.SelectSingleNode("SplitTimes/SplitTime/RealTime").InnerText; System.TimeSpan pb_dt = System.TimeSpan.Parse(pb_time); m.pb = (long)pb_dt.TotalMilliseconds; // need to find the pb-index when parsing history! string glod_time = node.SelectSingleNode("BestSegmentTime/RealTime").InnerText; System.TimeSpan glod_dt = System.TimeSpan.Parse(glod_time); m.gold = (long)glod_dt.TotalMilliseconds; ///////////////////////////////// // parse the history for the run! XmlNode history = node.SelectSingleNode("SegmentHistory"); foreach (XmlNode entry in history) { speedrun.Split split = new speedrun.Split(); split.attempt_index = System.Int32.Parse(entry.Attributes.GetNamedItem("id").InnerText); System.TimeSpan entry_ts = System.TimeSpan.Parse(entry.SelectSingleNode("RealTime").InnerText); split.split_time = (long)entry_ts.TotalMilliseconds; split.split_duration = (long)entry_ts.TotalMilliseconds; // duration is tricky it is what livesplit actually store.. // I am not sure we'll have to try it out and figure out as we go.. do we just skip duration, or do we try to calculate it? m.history.Add(split); } run.run.split_meta.Add(m); } /////////// // Attempts XmlNode attempts = doc.DocumentElement.SelectSingleNode("/Run/AttemptHistory"); foreach (XmlNode attempt_node in attempts) { speedrun.RunAttempt attempt = new speedrun.RunAttempt(); attempt.attempt_index = System.Int32.Parse(attempt_node.Attributes.GetNamedItem("id").InnerText); attempt.start_datetime = attempt_node.Attributes.GetNamedItem("started").InnerText; attempt.end_datetime = attempt_node.Attributes.GetNamedItem("ended").InnerText; attempt.finished = attempt_node.HasChildNodes; run.run.attempts.Add(attempt); } string json_path = System.IO.Path.GetFileName(xml_path); json_path = json_path.Replace(".lss", ".json"); string id = PlayerPrefs.GetString("active_game"); string path = Application.persistentDataPath + "/" + id + "/splits/" + json_path; run.save(path); on_import_done(json_path); //run.run.split_meta }
void Start() { Physics2D.IgnoreLayerCollision(10, 11); nextLevelData = new AssetProxy(typeof(NextLevelData)).LoadAsset("Objects/NextData.asset"); gamData = new AssetProxy(typeof(GameData)).LoadAsset("Objects/Data.asset"); Debug.Log(nextLevelData); nextLevelData.GenerateNextLevelData(); Vector2Int ms = nextLevelData.GetMapSize(); int MapSizeX = ms.x; int MapSizeY = ms.y; System.DateTime start = System.DateTime.Now; edgeCollider = GetComponent <EdgeCollider2D>(); edgeCollider.points = new Vector2[] { new Vector2(-MapSizeX / 2, -MapSizeY / 2), new Vector2(-MapSizeX / 2, MapSizeY / 2), new Vector2(MapSizeX / 2, MapSizeY / 2), new Vector2(MapSizeX / 2, -MapSizeY / 2), new Vector2(-MapSizeX / 2, -MapSizeY / 2) }; GameMap map = new GameMap(MapSizeX, MapSizeY); map.ground = GetComponentsInChildren <Tilemap>()[0]; map.decorations = GetComponentsInChildren <Tilemap>()[1]; map.structures = GetComponentsInChildren <Tilemap>()[2]; TilesetCreator tilesetCreator; Locations location = nextLevelData.GetLocation(); switch (location) { case Locations.Forest: tilesetCreator = new ForestTilesetCreator(); break; case Locations.Desert: tilesetCreator = new DesertTilesetCreator(); break; case Locations.Village: tilesetCreator = new VillageTilesetCreator(); break; default: tilesetCreator = new ForestTilesetCreator(); break; } Tileset ts = tilesetCreator.CreateTileset(); MapBuilder builder; MapType type = nextLevelData.GetMapType(); switch (type) { case MapType.Dungeon: builder = new DungeonMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts); break; case MapType.Ruins: builder = new RuinsMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts); break; case MapType.Village: tilesetCreator = new VillageTilesetCreator(); ts = tilesetCreator.CreateTileset(); builder = new VillageMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts); break; default: builder = new DungeonMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map, ts); break; } //MapBuilder builder = new VillageMapBuilder(new Rect(-MapSizeX / 2, -MapSizeY / 2, MapSizeX, MapSizeY), map); MapGenerator mapGen = new MapGenerator(builder); mapGen.Generate(); builder.GetMap(); Spawner spawner = new Spawner(); spawner.Spawn(map, ts); BuffSpawner buffSpawner = new BuffSpawner(); buffSpawner.Spawn(map, ts); System.TimeSpan timeItTook = System.DateTime.Now - start; Debug.Log(string.Format("Map generated, {0}", timeItTook)); }
public void Gen_board() { System.DateTime aa = System.DateTime.Now; //Debug.Log("Almost Found 1"); Uzup_tab(tab, true); //Debug.Log("Almost Found 2"); Skok_petla(tab, 0, 0); check: Uzup_tab(tab, false); Skok_petla(tab, 3, 3); if (!done) { goto check; } Skok_petla(tab, 6, 6); if (!done) { goto check; } Skok_petla(tab, 0, 6); if (!done) { goto check; } Skok_petla(tab, 6, 0); if (!done) { goto check; } Skok_petla(tab, 0, 3); if (!done) { goto check; } Skok_petla(tab, 3, 0); if (!done) { goto check; } Skok_petla(tab, 3, 6); if (!done) { goto check; } Skok_petla(tab, 6, 3); if (!done) { goto check; } Wykresl_do_rozw(tab, int.Parse(ifield.text)); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (tab[i, j] == 0) { fields[j + i * 9].GetComponentInChildren <Text>().text = ""; fields[j + i * 9].GetComponentInChildren <Text>().color = Color.white; } else { fields[j + i * 9].GetComponentInChildren <Text>().text = tab[i, j] + ""; fields[j + i * 9].GetComponentInChildren <Text>().color = Color.white; } } } System.DateTime ab = System.DateTime.Now; System.TimeSpan duration = ab.Subtract(aa); Debug.Log("Duration in milliseconds: " + duration.Milliseconds); /*execute = false; * loader.GetComponent<Image>().enabled = false;*/ }
// Update is called once per frame public void UpdateTime(float deltatime) { timer += deltatime; System.TimeSpan t = System.TimeSpan.FromSeconds(timer); timerText.text = string.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds); }
string TimeToString(float time) { System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(time); return((timeSpan.Minutes < 10 ? "0" + timeSpan.Minutes : timeSpan.Minutes.ToString()) + ":" + (timeSpan.Seconds < 10 ? "0" + timeSpan.Seconds : "" + timeSpan.Seconds)); }
private string FormatTime(float seconds) { System.TimeSpan ts = System.TimeSpan.FromSeconds(seconds); return(string.Format("{0}:{1}:{2}", ((int)ts.TotalHours), ts.Minutes, ts.Seconds)); }
public GameTimer(System.TimeSpan accumulatedTime) { this.accumulatedTime = accumulatedTime; timerStart = System.DateTime.UtcNow; }
void OnEnable() { EquimentList = GameManager.Instance.GetEquimentShopData(); if (EquimentList == null) { EquimentList = new List <CGameEquiment>(); } if (PlayerPrefs.HasKey("NowTime")) { strTime = PlayerPrefs.GetString("NowTime"); StartDate = System.Convert.ToDateTime(strTime); } EndData = System.DateTime.Now; timeCal = EndData - StartDate; int nStartTime = StartDate.Hour * 360 + StartDate.Minute * 60 + StartDate.Second; int nEndTime = EndData.Hour * 360 + EndData.Minute * 60 + EndData.Second; int nCheck = Mathf.Abs(nEndTime - nStartTime); //1시간이 지났거나 하루차이가 있을 경우 if (timeCal.Days != 0 || nCheck >= 1) { PlayerPrefs.SetString("NowTime", EndData.ToString()); EquimentList.Clear(); for (int nIndex = 0; nIndex < 3; nIndex++) { CGameEquiment cGameEquiment = GetEquiment(); ShopList[nIndex].GetEquiment(inventory, showPanel, cGameEquiment); EquimentList.Add(cGameEquiment); } } else { if (EquimentList != null) { foreach (CGameEquiment equit in EquimentList) { ShopList[nShopCount++].GetEquiment(inventory, showPanel, equit); } } //완전 처음 일 경우 else { for (int nIndex = 0; nIndex < 3; nIndex++) { CGameEquiment cGameEquiment = GetEquiment(); ShopList[nIndex].GetEquiment(inventory, showPanel, cGameEquiment); EquimentList.Add(cGameEquiment); } } } GameManager.Instance.SaveShopList(EquimentList); }
// Update is called once per frame void Update() { t.text = Playar.GetComponent <PlayerBehaviour>().score.ToString(); //show score string s = ""; int i; for (i = 0; i < Playar.GetComponent <PlayerBehaviour>().health; i++) //show health { s += "█"; } s += "\0"; h.text = s; if (Input.GetKey(KeyCode.Escape) && isPaused) { if (quitting == false) { quittimer = System.DateTime.Now; quitting = true; } System.TimeSpan hohoho = System.DateTime.Now - quittimer; exr.text = "quitin in " + ((5 - (float)(hohoho.Seconds + hohoho.Milliseconds / 1000.0f)) > 0 ? (5 - (float)(hohoho.Seconds + hohoho.Milliseconds / 1000.0f)).ToString("0.000") : "now!!!1"); if (hohoho.Seconds == 4 && quitting) { r.text = "bye :("; } if (hohoho.Seconds == 5 && quitting) { //if (Application.isEditor) #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #endif Application.Quit(); } } if (Input.GetKeyUp(KeyCode.Escape) && isPaused) { r.text = "(paused)"; exr.text = "press entr to contenue \n hold esc to quit"; quitting = false; } if (Input.GetKeyDown(KeyCode.Escape) && !isPaused) { Time.timeScale = 0.0f; isPaused = true; backupdir = dir; dir = 0; Playar.GetComponent <PlayerBehaviour>().moveL = Playar.GetComponent <PlayerBehaviour>().moveR = Playar.GetComponent <PlayerBehaviour>().shoot = false; r.text = "(paused)"; exr.text = "press entr to contenue \n hold esc to quit"; quitting = false; } if (Input.GetKeyDown(KeyCode.Return) && isPaused) { Time.timeScale = 1.0f; isPaused = false; dir = backupdir; Playar.GetComponent <PlayerBehaviour>().moveL = Playar.GetComponent <PlayerBehaviour>().moveR = Playar.GetComponent <PlayerBehaviour>().shoot = true; r.text = exr.text = ""; quitting = false; } if (!isPaused) { frames++; } else { frames--; } if (frames / (75 * Time.deltaTime) >= extra && r.text.Equals("")) //should it spawn that ufo { frames = 0; extra = rand.Next(1000 / (int)((75 * Time.deltaTime) + 1), 2000 / (int)((75 * Time.deltaTime) + 1)); Vector3 ve = transform.position; ve.x += (float)9.7; GameObject eventos = Instantiate(EventEnemy, ve, Quaternion.identity) as GameObject; //eventos.GetComponent<EnemyBehaviour>().container = this.gameObject; eventos.transform.parent = transform;//ene.Add(eventos); } if (Playar.GetComponent <PlayerBehaviour>().health <= 0) //does player have health { dir = 0; r.text = "Killed :("; exr.text = "Ya score: " + t.text + "\n press EnterR to restart"; t.text = ""; canEventSpawn = false; Playar.GetComponent <PlayerBehaviour>().moveL = Playar.GetComponent <PlayerBehaviour>().moveR = Playar.GetComponent <PlayerBehaviour>().shoot = false; if (Input.GetKeyDown(KeyCode.Return)) { no.text = "Stage 0"; stage = 0; dir = 1; foreach (Transform child in transform)//var v in ene) { Destroy(child.gameObject); } Playar.GetComponent <PlayerBehaviour>().score = 0; Playar.GetComponent <PlayerBehaviour>().health = 7; Playar.transform.position = playerposition; StartStage(); r.text = exr.text = ""; } } if (GameObject.FindGameObjectsWithTag("Tagged").Length.Equals(0)) //is there no enemies/bullets/pickups { r.text = "Completeded"; frames--; exr.text = "Press ENTERe to continueue"; canEventSpawn = false; Playar.GetComponent <PlayerBehaviour>().shoot = false; if (Input.GetKeyDown(KeyCode.Return)) { if (stage + 1 < levels.Length) { stage++; } else { GenerateEnemies(); } var bl = GameObject.FindGameObjectsWithTag("Boolet"); foreach (var v in bl) { Destroy(v); } StartStage(); r.text = exr.text = ""; } } if (transform.childCount < enemyrow * enemycol * scrUp / scrDwn && !scr) { scrUp--; scr = true; Scramble(); commencingScramble = true; } else { scr = false; } if (commencingScramble && !isPaused) { if (!AreTheyThereYet()) { foreach (Transform child in transform) { if (!child.gameObject.name.Contains("Event")) { child.position = Vector3.MoveTowards(child.position, new Vector3(child.GetComponent <EnemyBehaviour>().scatterX, child.GetComponent <EnemyBehaviour>().scatterY), 0.15f * (75 * Time.deltaTime)); } } } else { foreach (Transform child in transform) { child.GetComponent <EnemyBehaviour>().killable = true; if (!child.gameObject.name.Contains("Event")) { Destroy(child.GetChild(0).gameObject); } } commencingScramble = false; } } if (Playar.GetComponent <PlayerBehaviour>().weapontype == 0) { if (wep != 0) { tim.text = ""; wep = 0; showcase.GetComponent <ShowcaseBehaviour>().sr.sprite = showcase.GetComponent <ShowcaseBehaviour>().weaponSprites[0]; } } else { float timem = Playar.GetComponent <PlayerBehaviour>().limit - (Time.time - Playar.GetComponent <PlayerBehaviour>().time); tim.text = (timem > 0 ? timem : 0).ToString("0.000"); if (wep != Playar.GetComponent <PlayerBehaviour>().weapontype) { showcase.GetComponent <ShowcaseBehaviour>().sr.sprite = showcase.GetComponent <ShowcaseBehaviour>().weaponSprites[Playar.GetComponent <PlayerBehaviour>().weapontype]; wep = Playar.GetComponent <PlayerBehaviour>().weapontype; } } }
public static ChartInfo convertSleepHeaderToChartInfo(ChartInfo chartInfo, string filePath) { var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader reader = new StreamReader(stream); string[] profileInfo = reader.ReadLine().Split(','); //CsvFileの1行目 (Row 0) reader.ReadLine(); //Skip Row 1 string[] sleepRecordStartTimeLine = reader.ReadLine().Split(','); //CsvFileの3行目 (Row 2) string sleepTime = ""; if (chartInfo.endSleepTime != null && sleepRecordStartTimeLine.Length >= 3) { string date = sleepRecordStartTimeLine[0]; string time = sleepRecordStartTimeLine[2]; string[] dateArr = date.Split('/'); string[] timeArr = time.Split(':'); int year = int.Parse(dateArr[0]); int month = int.Parse(dateArr[1]); int day = int.Parse(dateArr[2]); int hour = int.Parse(timeArr[0]); int min = int.Parse(timeArr[1]); int sec = int.Parse(timeArr[2]); chartInfo.startSleepTime = new System.DateTime(year, month, day, hour, min, sec); int sleepTimeSec = Graph.Time.GetDateDifferencePerSecond(chartInfo.startSleepTime, chartInfo.endSleepTime); System.TimeSpan ts = new System.TimeSpan(hours: 0, minutes: 0, seconds: sleepTimeSec); int hourWithDay = 24 * ts.Days + ts.Hours; // 24時間超えた場合の時間を考慮 sleepTime = string.Format("{0:00}:{1:00}", hourWithDay, ts.Minutes); } System.DateTime fileDateTime = Kaimin.Common.Utility.TransFilePathToDate(filePath); chartInfo.fileName = fileDateTime.ToString(); chartInfo.sleepTime = sleepTime; string tmpTime = fileDateTime.ToString("HH:mm:ss"); if (string.Compare(tmpTime, "00:00:00") >= 0 && string.Compare(tmpTime, "09:00:00") <= 0) { //データ開始時刻がAM00:00~09:00までのデータに前日の日付として表示 chartInfo.date = fileDateTime.AddDays(-1).ToString("M/d"); } else { chartInfo.date = fileDateTime.ToString("M/d"); } if (sleepRecordStartTimeLine.Length > 9) //New format { chartInfo.sleepMode = int.Parse(sleepRecordStartTimeLine[8]); chartInfo.vibrationStrength = int.Parse(sleepRecordStartTimeLine[9]); } else { //Default chartInfo.sleepMode = (int)SleepMode.Suppress; chartInfo.vibrationStrength = (int)VibrationStrength.Medium; } return(chartInfo); }