Beispiel #1
0
 public virtual void Render(Cloud cloud, Graphics g)
 {
     foreach (var block in cloud)
     {
         DrawWord(block.Data, g, block.LeftTop);
     }
 }
        public ProviderResponse<Cloud> Connect(Cloud cloud)
        {
            ProviderResponse<Cloud> response = new ProviderResponse<Cloud>();
            Cloud local = cloud.DeepCopy();
            IVcapClient client = new VcapClient(local);

            try
            {
                VcapClientResult result = client.Login();
                if (!result.Success)
                    throw new Exception(result.Message);
                local.AccessToken = client.CurrentToken;
                var applications = client.GetApplications();
                var provisionedServices = client.GetProvisionedServices();
                var availableServices = client.GetSystemServices();
                local.Applications.Synchronize(new SafeObservableCollection<Application>(applications), new ApplicationEqualityComparer());
                local.Services.Synchronize(new SafeObservableCollection<ProvisionedService>(provisionedServices), new ProvisionedServiceEqualityComparer());
                local.AvailableServices.Synchronize(new SafeObservableCollection<SystemService>(availableServices), new SystemServiceEqualityComparer());
                foreach (Application app in local.Applications)
                {
                    var instances = GetInstances(local, app);
                    if (instances.Response != null)
                        app.InstanceCollection.Synchronize(new SafeObservableCollection<Instance>(instances.Response), new InstanceEqualityComparer());
                }
                response.Response = local;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return response;
        }
 protected override void InitializeData()
 {
     Messenger.Default.Send(new NotificationMessageAction<Cloud>(Messages.SetChangePasswordData, c => {
         this.EMail = c.Email;
         this.cloud = c;
     }));
 }
Beispiel #4
0
    public void ShouldAddFriend(Cloud cloud)
    {
        // Use two test accounts
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects friend status change event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Community.OnFriendStatusChange += (FriendStatusChangeEvent e) => {
                Assert(e.FriendId == gamer2.GamerId, "Should come from P2");
                Assert(e.NewStatus == FriendRelationshipStatus.Add, "Should have added me");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // Add gamer1 as a friend of gamer2
            gamer2.Community.AddFriend(gamer1.GamerId)
            .ExpectSuccess(addResult => {
                // Then list the friends of gamer1, gamer2 should be in it
                return gamer1.Community.ListFriends();
            })
            .ExpectSuccess(friends => {
                Assert(friends.Count == 1, "Expects one friend");
                Assert(friends[0].GamerId == gamer2.GamerId, "Wrong friend ID");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
Beispiel #5
0
    public void ShouldAssociateGodfather(Cloud cloud)
    {
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            // Expects godchild event
            Promise restOfTheTestCompleted = new Promise();
            gamer1.StartEventLoop();
            gamer1.Godfather.OnGotGodchild += (GotGodchildEvent e) => {
                Assert(e.Gamer.GamerId == gamer2.GamerId, "Should come from player2");
                Assert((object)e.Reward == (object)Bundle.Empty, "No reward should be associated");
                restOfTheTestCompleted.Done(CompleteTest);
            };

            // P1 generates a code and associates P2 with it
            gamer1.Godfather.GenerateCode()
            // Use code
            .ExpectSuccess(genCode => gamer2.Godfather.UseCode(genCode))
            .ExpectSuccess(dummy => gamer2.Godfather.GetGodfather())
            .ExpectSuccess(result => {
                Assert(result.GamerId == gamer1.GamerId, "P1 should be godfather");
                Assert(result.AsBundle().Root.Has("godfather"), "Underlying structure should be accessible");
                return gamer1.Godfather.GetGodchildren();
            })
            .ExpectSuccess(result => {
                Assert(result.Count == 1, "Should have only one godchildren");
                Assert(result[0].GamerId == gamer2.GamerId, "P2 should be godchildren");
                restOfTheTestCompleted.Resolve();
            });
        });
    }
Beispiel #6
0
    public void ShouldBeUsableToSearchForMatches(Cloud cloud)
    {
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            string queryStr = "public:true AND owner_id:" + gamer1.GamerId;
            Match[] matches = new Match[2];

            gamer1.Matches.Create(maxPlayers: 2)
            .Then(match1 => {
                Bundle matchProp = Bundle.CreateObject("public", true, "owner_id", gamer1.GamerId);
                matches[0] = match1;
                // Index the match
                return cloud.Index("matches").IndexObject(match1.MatchId, matchProp, Bundle.Empty);
            })
            .Then(indexResult => {
                // Create another match
                return gamer1.Matches.Create(maxPlayers: 2);
            })
            .Then(match2 => {
                // Index it
                matches[1] = match2;
                return cloud.Index("matches").IndexObject(match2.MatchId, Bundle.CreateObject("public", false), Bundle.Empty);
            })
            .Then(indexResult2 => {
                // Check that we can find match1 by looking for public matches
                return cloud.Index("matches").Search(queryStr);
            })
            .Then(found => {
                Assert(found.Hits.Count == 1, "Should find one match");
                Assert(found.Hits[0].ObjectId == matches[0].MatchId, "Should find one match");
            })
            .CompleteTestIfSuccessful();
        });
    }
Beispiel #7
0
 public void ShouldListScoreOfFriends(Cloud cloud)
 {
     // Create 2 users
     Login2NewUsers(cloud, (gamer1, gamer2) => {
         // Post 1 score each
         string board = RandomBoardName();
         gamer1.Scores.Post(1000, board, ScoreOrder.HighToLow, "TestGamer1", false)
         .ExpectSuccess(dummy => gamer2.Scores.Post(1500, board, ScoreOrder.HighToLow, "TestGamer2", false))
         // We need to wait a bit else the results may be misleading
         .ExpectSuccess(dummy => Wait<object>(1000))
         // Ok so now the two friends are not friends, so the scores returned should not include the other
         .ExpectSuccess(dummy => gamer1.Scores.ListFriendScores(board))
         .ExpectSuccess(scores => {
             Assert(scores.Count == 1, "Should have one score only");
             Assert(scores[0].GamerInfo.GamerId == gamer1.GamerId, "Should contain my score");
             // So let's become friends!
             return gamer2.Community.AddFriend(gamer1.GamerId);
         })
         // And try again fetching scores
         .ExpectSuccess(dummy => Wait<object>(1000))
         .ExpectSuccess(friendResult => gamer1.Scores.ListFriendScores(board))
         .ExpectSuccess(scoresWhenFriend => {
             Assert(scoresWhenFriend.Count == 2, "Should have two scores only");
             Assert(scoresWhenFriend[1].Rank == 2, "Second score should have rank 2");
             CompleteTest();
         });
     });
 }
Beispiel #8
0
 public void ShouldCreateMatchWithMinimumArgs(Cloud cloud)
 {
     Login(cloud, gamer => {
         gamer.Matches.Create(maxPlayers: 2)
         .CompleteTestIfSuccessful();
     });
 }
Beispiel #9
0
 public void ShouldCreateMatch(Cloud cloud)
 {
     string matchDesc = "Test match";
     Login(cloud, gamer => {
         gamer.Matches.Create(
             description: matchDesc,
             maxPlayers: 2,
             customProperties: Bundle.CreateObject("test", "value"),
             shoe: Bundle.CreateArray(1, 2, 3))
         .ExpectSuccess(match => {
             Assert(match.Creator.GamerId == gamer.GamerId, "Match creator not set properly");
             Assert(match.CustomProperties["test"] == "value", "Missing custom property");
             Assert(match.Description == matchDesc, "Invalid match description");
             Assert(match.Moves.Count == 0, "Should not have any move at first");
             Assert(match.GlobalState.AsDictionary().Count == 0, "Global state should be empty initially");
             Assert(match.LastEventId != null, "Last event should not be null");
             Assert(match.MatchId != null, "Match ID shouldn't be null");
             Assert(match.MaxPlayers == 2, "Should have two players");
             Assert(match.Players.Count == 1, "Should contain only one player");
             Assert(match.Players[0].GamerId == gamer.GamerId, "Should contain me as player");
             Assert(match.Seed != 0, "A 31-bit seed should be provided");
             Assert(match.Shoe.AsArray().Count == 0, "The shoe shouldn't be available until the match is finished");
             Assert(match.Status == MatchStatus.Running, "The match status is invalid");
             CompleteTest();
         });
     });
 }
Beispiel #10
0
 public void ShouldHavePaginationInTxHistory(Cloud cloud)
 {
     LoginNewUser(cloud, gamer => {
         // Run 3 transactions serially
         gamer.Transactions.Post(Bundle.CreateObject("gold", 1))
         .ExpectSuccess(dummy => gamer.Transactions.Post(Bundle.CreateObject("gold", 2, "silver", 10)))
         .ExpectSuccess(dummy => gamer.Transactions.Post(Bundle.CreateObject("gold", 3)))
         // All transactions have been executed. Default to page 1.
         .ExpectSuccess(dummy => gamer.Transactions.History(limit: 2))
         .ExpectSuccess(tx => {
             // Even though there are three, only two results should be returned
             Assert(tx.Count == 2, "Expected two entries in history");
             // Then fetch the next page
             Assert(!tx.HasPrevious, "Should not have previous page");
             Assert(tx.HasNext, "Should have next page");
             return tx.FetchNext();
         })
         .ExpectSuccess(tx => {
             Assert(tx.Offset == 2, "Expected offset: 2");
             Assert(tx.Count == 1, "Expected one value at page 2");
             Assert(tx.HasPrevious, "Should have previous page");
             Assert(!tx.HasNext, "Should not have next page");
             return tx.FetchPrevious();
         })
         .ExpectSuccess(tx => {
             Assert(tx.Count == 2, "Expected two entries in history");
             Assert(!tx.HasPrevious, "Should not have previous page");
             Assert(tx.HasNext, "Should have next page");
             CompleteTest();
         });
     });
 }
	// Use this for initialization
	void Start () {
		var cotc = FindObjectOfType<CotcGameObject> ();
		if (cotc == null) {
			throw new SystemException ("No Clan of the Cloud SDK object found on the scene");
		}

		// Log unhandled exceptions (.Done block without .Catch -- not called if there is any .Then)
		Promise.UnhandledException += (object sender, ExceptionEventArgs e) => {
			Debug.LogError("Unhandled exception: " + e.Exception.ToString());
		};
//		Promise.Debug_OutputAllExceptions = true;
//		PlayerPrefs.DeleteAll();

		// Initiate getting the main Cloud object
		cotc.GetCloud().Done(cloud => {
			Cloud = cloud;
			// Retry failed HTTP requests once after 1 sec, then 5, finally abort.
			Cloud.HttpRequestFailedHandler = (HttpRequestFailedEventArgs e) => {
				int count = (int?) e.UserData ?? 0;
				if (count == 0)      e.RetryIn(1000);
				else if (count == 1) e.RetryIn(5000);
				else                 e.Abort();
				e.UserData = ++count;
			};
			Debug.Log("Setup done");
//			PostSampleScoresForTesting();
			InitCloud();
		});

		Debug.Assert(ConfirmationDialog != null);
	}
Beispiel #12
0
 public void ShouldRunGameBatch(Cloud cloud)
 {
     cloud.Game.Batches.Run("test", Bundle.CreateObject("value", 3))
     .ExpectSuccess(batchResult => {
         Assert(batchResult["value"] == 6, "Result invalid (expected 3 x 2 = 6)");
         CompleteTest();
     });
 }
 protected override void InitializeData()
 {
     Messenger.Default.Send(new NotificationMessageAction<Cloud>(Messages.SetCreateServiceData,
         (cloud) =>
         {
             this.cloud = cloud;
             this.SystemServices.Synchronize(cloud.AvailableServices, new SystemServiceEqualityComparer());
         }));
 }
 protected override void InitializeData()
 {
     Messenger.Default.Send(new NotificationMessageAction<Cloud>(Messages.SetRegisterAccountData,
         (cloud) =>
         {
             this.cloud = cloud;
             this.EMail = cloud.Email;
             this.NewPassword = cloud.Password;
         }));
 }
Beispiel #15
0
 public void ShouldRunGamerBatch(Cloud cloud)
 {
     Login(cloud, gamer => {
         gamer.Batches.Run("testGamer", Bundle.CreateObject("prefix", "Hello "))
         .ExpectSuccess(batchResult => {
             Assert(batchResult["message"] == "Hello [email protected]", "Returned value invalid (" + batchResult["message"] + ", check hook on server");
             CompleteTest();
         });
     });
 }
Beispiel #16
0
 public void TestInitialize()
 {
     factories = Substitute.For<Factories>();
     providerFactory = Substitute.For<CloudProviderFactory>();
     provider = Substitute.For<CloudProvider>();
     providerFactory.Create().Returns(provider);
     exportAndImport = Substitute.For<ExportAndImport>();
     settings = new Settings { CloudToken = "foo" };
     factories.Settings.Returns(settings);
     sut = new CloudImpl(providerFactory, factories, exportAndImport);
 }
 public AddCloudViewModel()
     : base(Messages.AddCloudDialogResult)
 {
     Cloud = new Cloud();
     dispatcher = Dispatcher.CurrentDispatcher;
     ValidateAccountCommand = new RelayCommand(ValidateAccount, CanValidate);
     RegisterAccountCommand = new RelayCommand(RegisterAccount, CanRegister);
     ManageCloudUrlsCommand = new RelayCommand(ManageCloudUrls);
     cloudUrls = provider.CloudUrls;
     SelectedCloudUrl = cloudUrls.SingleOrDefault((i) => i.IsDefault);
 }
Beispiel #18
0
 public void ShouldNotReadInexistingKey(Cloud cloud)
 {
     cloud.LoginAnonymously().ExpectSuccess(gamer => {
         gamer.GamerVfs.GetKey("nonexistingkey")
         .ExpectFailure(getRes => {
             Assert(getRes.HttpStatusCode == 404, "Wrong error code (404)");
             Assert(getRes.ServerData["name"] == "KeyNotFound", "Wrong error message");
             CompleteTest();
         });
     });
 }
Beispiel #19
0
 public void ShouldChangePassword(Cloud cloud)
 {
     cloud.Login(
         network: LoginNetwork.Email,
         networkId: RandomEmailAddress(),
         networkSecret: "Password123")
     .Then(gamer => gamer.Account.ChangePassword("Password124"))
     .Then(pswResult => {
         Assert(pswResult, "Change password failed");
     })
     .CompleteTestIfSuccessful();
 }
Beispiel #20
0
 public void ShouldReturnProperOutline(Cloud cloud)
 {
     Login(cloud, gamer => {
         gamer.Profile.Outline()
         .ExpectSuccess(outline => {
             Assert(outline.Network == gamer.Network, "Expected same network");
             Assert(outline.NetworkId == gamer.NetworkId, "Expected same network ID");
             Assert(outline["games"].Type == Bundle.DataType.Array, "Expected games array");
             CompleteTest();
         });
     });
 }
		/// <summary>
		/// Logs in to CotC through facebook. This will bring an user interface allowing to sign in
		/// to facebook.
		/// </summary>
		/// <returns>task returning when the login has finished. The resulting Gamer object can then
		/// be used for many purposes related to the signed in account.</returns>
		/// <param name="cloud">needed to perform various tasks. Ensure that the SDK is initialized properly and fetch a
		/// cloud object.</param>
		public Promise<Gamer> LoginWithFacebook(Cloud cloud) {
			var task = new Promise<Gamer>();

			LoginToFacebook(new List<string>() { "public_profile","email","user_friends" }).Then(aToken => {
				string userId = aToken.UserId, token = aToken.TokenString;
				Common.Log("Logged in through facebook");
				cloud.Login(LoginNetwork.Facebook, userId, token)
					.ForwardTo(task);
			}).Catch(ex => {
				task.Reject(ex);
			});
			return task;
		}
Beispiel #22
0
 public void ShouldFetchTransactionHistory(Cloud cloud)
 {
     LoginNewUser(cloud, gamer => {
         gamer.Transactions.Post(Bundle.CreateObject("gold", 10), "Transaction run by integration test.")
         .ExpectSuccess(dummy => gamer.Transactions.History())
         .ExpectSuccess(histResult => {
             Assert(histResult.Count == 1, "Expected one history entry");
             Assert(histResult[0].Description == "Transaction run by integration test.", "Wrong description");
             Assert(histResult[0].TxData["gold"] == 10, "Wrong tx data");
             CompleteTest();
         });
     });
 }
 public ExportAndImportViewModel(Factories factories, CloudProviderFactory cloudProviderFactory,
     Vibration vibration, Cloud cloud, MessageDialog messageDialog, CloudMessages cloudMessages,
     BackgroundWorkerFactory workerFactory)
 {
     this.factories = factories;
     exportAndImport = new ExportAndImportImpl(factories);
     this.cloudProviderFactory = cloudProviderFactory;
     this.vibration = vibration;
     this.cloud = cloud;
     this.messageDialog = messageDialog;
     this.cloudMessages = cloudMessages;
     this.workerFactory = workerFactory;
 }
Beispiel #24
0
 public void ShouldFetchGameKey(Cloud cloud)
 {
     cloud.Game.GameVfs.GetKey("testkey")
     .ExpectSuccess(getResult => {
         Assert(getResult.Type != Bundle.DataType.String, "Not expecting string result");
         Assert(getResult["test"] == 2, "Expected test: 2 key");
         return cloud.Game.GameVfs.GetKey("stringkey");
     })
     .ExpectSuccess(v1Result => {
         Assert(v1Result["str"] == "val", "Expected JSON-decodable string");
         CompleteTest();
     });
 }
Beispiel #25
0
 public void ShouldWriteKeys(Cloud cloud)
 {
     Login(cloud, gamer => {
         gamer.GamerVfs.SetKey("testkey", "hello world")
         .ExpectSuccess(setRes => {
             gamer.GamerVfs.GetKey("testkey")
             .ExpectSuccess(getRes => {
                 Assert(getRes == "hello world", "Wrong key value");
                 CompleteTest();
             });
         });
     });
 }
Beispiel #26
0
 public void ShouldNotAssociateGodfatherWithHimself(Cloud cloud)
 {
     LoginNewUser(cloud, gamer => {
         // Should fail to godfather himself
         gamer.Godfather.GenerateCode()
         .ExpectSuccess(genCode => {
             gamer.Godfather.UseCode(genCode)
             .ExpectFailure(usedCode => {
                 Assert(usedCode.HttpStatusCode == 400, "Expected HTTP 400");
                 Assert(usedCode.ServerData["name"] == "cantBeSelfGodchild", "Expected cantBeSelfGodchild");
                 CompleteTest();
             });
         });
     });
 }
Beispiel #27
0
 public void ShouldWriteBinaryKey(Cloud cloud)
 {
     Login(cloud, gamer => {
         byte[] data = { 1, 2, 3, 4 };
         gamer.GamerVfs.SetKeyBinary("testkey", data)
         .ExpectSuccess(setRes => {
             gamer.GamerVfs.GetKeyBinary("testkey")
             .ExpectSuccess(getRes => {
                 Assert(getRes.Length == 4, "Wrong key length");
                 Assert(getRes[2] == 3, "Wrong key value");
                 CompleteTest();
             });
         });
     });
 }
 public ProviderResponse<bool> ChangePassword(Cloud cloud, string newPassword)
 {
     var response = new ProviderResponse<bool>();
     try
     {
         IVcapClient client = new VcapClient(cloud);
         client.ChangePassword(newPassword);
         response.Response = true;
     }
     catch (Exception ex)
     {
         response.Message = ex.Message;
     }
     return response;
 }
	void Awake()
	{
		Context = new Cloud();
		
		for (var i = 0; i < 5; ++i)
		{
			Context.Units.Add(new Unit
			{
				Target = (GameObject)GameObject.Instantiate(UnitPrefab),
				Name = "Unit " + i,
			});
		}
		
		View.SetContext(Context);
	}
Beispiel #30
0
 public void ShouldListNetworkUsers(Cloud cloud)
 {
     Login(cloud, gamer => {
         Bundle data = Bundle.FromJson("{\"data\":[{\"name\":\"Test 1\",\"id\":\"10153057921478192\"},{\"name\":\"Test 2\",\"id\":\"10153366656847346\"},{\"name\":\"Test 3\",\"id\":\"339262546278220\"}],\"paging\":{\"next\":\"https://graph.facebook.com/v2.1/10152381145462633/friends?access_token=CAAENyTNQMpQBADfCgZCpmiZAcRifeQVmfoeVNScZCi5DQxlianZABohlOFivboYIuOb1Qqv4ATAMswCNpJWtmWUrkZAdsDUUxtQMrm0qo3QOjztl2niJ0vmmKrKccXhZAwFK5GkNe4Q58ZBPouzS5IFVsFUzDjhiAVjlzmlCgdb2Fcf9n6651wsWrEMZCKxk98QDcs0OJYEeDQZDZD&limit=5000&offset=5000&__after_id=enc_AdCP2GaZAGG8lfGebTkZAwTP6l7CbRHm15XU9mT6RRx9xa5C7PBZB35xaZAVf1IoFQTd9ZAILfmqphj3KZBrrQ3vaIuYRO\"},\"summary\":{\"total_count\":760}}");
         List<SocialNetworkFriend> friends = new List<SocialNetworkFriend>();
         foreach (Bundle f in data["data"].AsArray()) {
             friends.Add(new SocialNetworkFriend(f));
         }
         gamer.Community.ListNetworkFriends(LoginNetwork.Facebook, friends, true)
         .ExpectSuccess(response => {
             Assert(response.ByNetwork[LoginNetwork.Facebook].Count == 3, "Should have registered 3 facebook users");
             CompleteTest();
         });
     });
 }
 public CleanTrashCommand(Cloud cloud, string path, IList <string> parames) : base(cloud, path, parames)
 {
 }
Beispiel #32
0
        static LevelLoader()
        {
            // Mario loader
            loaders.Add("mario", (game, x, y) =>
            {
                game.Mario = new Entities.Mario.Mario(game, x, y);
            });

            LevelLoader_Block1();
            LevelLoader_Block2();

            // Enemy loaders
            loaders.Add("goomba", (game, x, y) =>
            {
                game.WorldLoader.Enemies.Add(new Goomba(game, x, y));
            });
            loaders.Add("koopa", (game, x, y) =>
            {
                game.WorldLoader.Enemies.Add(new Koopa(game, x, y));
            });
            loaders.Add("boss", (game, x, y) =>
            {
                game.WorldLoader.Enemies.Add(new Bowser(game, x - 1, y - 1));
            });

            loaders.Add("lakitu", (game, x, y) =>
            {
                game.WorldLoader.Enemies.Add(new Lakitu(game, x, y));
            });

            // Pipe loader
            loaders.Add("pipeTop", (game, x, y) =>
            {
                Pipe pipe = new Pipe("Top", game)
                {
                    Position = new Vector2(x, y)
                };
                game.WorldLoader.Pipes.Add(pipe);
                game.Map.SetBlock(x, y, pipe);
                game.Map.SetHiddenBlock(x, y + 1, pipe);
                game.Map.SetHiddenBlock(x + 1, y, pipe);
                game.Map.SetHiddenBlock(x + 1, y + 1, pipe);
            });

            loaders.Add("UGpipeTop", (game, x, y) =>
            {
                Pipe pipe     = new Pipe("UGTop", game);
                pipe.Position = new Vector2(x, y);
                game.WorldLoader.Pipes.Add(pipe);
                game.Map.SetBlock(x, y, pipe);
                game.Map.SetHiddenBlock(x, y + 1, pipe);
                game.Map.SetHiddenBlock(x + 1, y, pipe);
                game.Map.SetHiddenBlock(x + 1, y + 1, pipe);
            });

            loaders.Add("pipeBody", (game, x, y) =>
            {
                Pipe pipeBody     = new Pipe("Body", game);
                pipeBody.Position = new Vector2(x, y);
                game.WorldLoader.Pipes.Add(pipeBody);
                game.Map.SetBlock(x, y, pipeBody);
                game.Map.SetHiddenBlock(x + 1, y, pipeBody);
            });

            loaders.Add("SWPipeEntrance", (game, x, y) =>
            {
                Pipe pipeBody     = new Pipe("SWEntrance", game);
                pipeBody.Position = new Vector2(x, y);
                game.WorldLoader.Pipes.Add(pipeBody);
                game.Map.SetBlock(x, y, pipeBody);
                game.Map.SetHiddenBlock(x + 1, y, pipeBody);
                game.Map.SetHiddenBlock(x, y + 1, pipeBody);
                game.Map.SetHiddenBlock(x + 1, y + 1, pipeBody);
            });

            loaders.Add("SWPipeBody", (game, x, y) =>
            {
                Pipe pipeBody     = new Pipe("SWBody", game);
                pipeBody.Position = new Vector2(x, y);
                game.WorldLoader.Pipes.Add(pipeBody);
                game.Map.SetBlock(x, y, pipeBody);
                game.Map.SetBlock(x, y + 1, pipeBody);
            });

            //Item loaders
            loaders.Add("coin", (game, x, y) =>
            {
                IItem coin    = new Coin(game, new Vector2(x, y - 1));
                coin.Position = new Vector2(x, y);
                game.WorldLoader.Items.Add(coin);
            });

            loaders.Add("flagPole", (game, x, y) =>
            {
                IItem flagPole    = new FlagPole(game);
                flagPole.Position = new Vector2(x, y);
                flagPole.Bounds   = new Rectangle(x, y, 1, 12 - y);
                game.WorldLoader.Items.Add(flagPole);
            });

            // Background loaders
            loaders.Add("bush", (game, x, y) =>
            {
                IBackground bush = new Bush();
                bush.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(bush);
            });

            loaders.Add("bushMid", (game, x, y) =>
            {
                IBackground bushmid = new BushMid();
                bushmid.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(bushmid);
            });

            loaders.Add("bushLong", (game, x, y) =>
            {
                IBackground bushlong = new BushLong();
                bushlong.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(bushlong);
            });

            loaders.Add("hill", (game, x, y) =>
            {
                IBackground hill = new Hill();
                hill.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(hill);
            });

            loaders.Add("cloud", (game, x, y) =>
            {
                IBackground cloud = new Cloud();
                cloud.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(cloud);
            });

            loaders.Add("cloudMid", (game, x, y) =>
            {
                IBackground cloudMid = new CloudMid();
                cloudMid.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(cloudMid);
            });

            loaders.Add("cloudLong", (game, x, y) =>
            {
                IBackground cloudlong = new CloudLong();
                cloudlong.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(cloudlong);
            });

            loaders.Add("castle", (game, x, y) =>
            {
                IBackground castle = new ToadCastle();
                castle.Position    = new Vector2(x, y);
                game.WorldLoader.Background.Add(castle);
            });

            loaders.Add("flag", (game, x, y) =>
            {
                Flag flag = new Flag(new Vector2(x, y));
                game.WorldLoader.Background.Add(flag);
            });

            loaders.Add("lavaTop", (game, x, y) =>
            {
                IBackground lavatop = new LavaTop {
                    Position = new Vector2(x, y)
                };
                game.WorldLoader.Background.Add(lavatop);
            });

            loaders.Add("LavaBot", (game, x, y) => {
                IBackground lavatop = new LavaBot {
                    Position = new Vector2(x, y)
                };
                game.WorldLoader.Background.Add(lavatop);
            });

            loaders.Add("BridgeChain", (game, x, y) => {
                IBackground bc = new BridgeChain {
                    Position = new Vector2(x, y)
                };
                game.WorldLoader.Background.Add(bc);
            });

            loaders.Add("Hammer", (game, x, y) => {
                game.WorldLoader.Items.Add(new Hammer(game, new Vector2(x, y)));
            });
        }
Beispiel #33
0
        public static bool LoadCustomEntity(EntityData entityData, Level level)
        {
            LevelData levelData = level.Session.LevelData;
            Vector2   offset    = new Vector2(levelData.Bounds.Left, levelData.Bounds.Top);

            if (Everest.Events.Level.LoadEntity(level, levelData, offset, entityData))
            {
                return(true);
            }

            if (EntityLoaders.TryGetValue(entityData.Name, out EntityLoader loader))
            {
                Entity loaded = loader(level, levelData, offset, entityData);
                if (loaded != null)
                {
                    level.Add(loaded);
                    return(true);
                }
            }

            if (entityData.Name == "everest/spaceController")
            {
                level.Add(new SpaceController());
                return(true);
            }

            // The following entities have hardcoded "attributes."
            // Everest allows custom maps to set them.

            if (entityData.Name == "spinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustStaticSpinner(entityData, offset));
                    return(true);
                }

                CrystalColor color = CrystalColor.Blue;
                if (level.Session.Area.ID == 5)
                {
                    color = CrystalColor.Red;
                }
                else if (level.Session.Area.ID == 6)
                {
                    color = CrystalColor.Purple;
                }
                else if (level.Session.Area.ID == 10)
                {
                    color = CrystalColor.Rainbow;
                }
                else if ("core".Equals(entityData.Attr("color"), StringComparison.InvariantCultureIgnoreCase))
                {
                    color = (CrystalColor)(-1);
                }
                else if (!Enum.TryParse(entityData.Attr("color"), true, out color))
                {
                    color = CrystalColor.Blue;
                }

                level.Add(new CrystalStaticSpinner(entityData, offset, color));
                return(true);
            }

            if (entityData.Name == "trackSpinner")
            {
                if (level.Session.Area.ID == 10 ||
                    entityData.Bool("star"))
                {
                    level.Add(new StarTrackSpinner(entityData, offset));
                    return(true);
                }
                else if (level.Session.Area.ID == 3 ||
                         (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                         entityData.Bool("dust"))
                {
                    level.Add(new DustTrackSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeTrackSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "rotateSpinner")
            {
                if (level.Session.Area.ID == 10 ||
                    entityData.Bool("star"))
                {
                    level.Add(new StarRotateSpinner(entityData, offset));
                    return(true);
                }
                else if (level.Session.Area.ID == 3 ||
                         (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                         entityData.Bool("dust"))
                {
                    level.Add(new DustRotateSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeRotateSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "checkpoint" &&
                entityData.Position == Vector2.Zero &&
                !entityData.Bool("allowOrigin"))
            {
                // Workaround for mod levels with old versions of Ahorn containing a checkpoint at (0, 0):
                // Create the checkpoint and avoid the start position update in orig_Load.
                level.Add(new Checkpoint(entityData, offset));
                return(true);
            }

            if (entityData.Name == "cloud")
            {
                patch_Cloud cloud = new Cloud(entityData, offset) as patch_Cloud;
                if (entityData.Has("small"))
                {
                    cloud.Small = entityData.Bool("small");
                }
                level.Add(cloud);
                return(true);
            }

            if (entityData.Name == "cobweb")
            {
                patch_Cobweb cobweb = new Cobweb(entityData, offset) as patch_Cobweb;
                if (entityData.Has("color"))
                {
                    cobweb.OverrideColors = entityData.Attr("color")?.Split(',').Select(s => Calc.HexToColor(s)).ToArray();
                }
                level.Add(cobweb);
                return(true);
            }

            if (entityData.Name == "movingPlatform")
            {
                patch_MovingPlatform platform = new MovingPlatform(entityData, offset) as patch_MovingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "sinkingPlatform")
            {
                patch_SinkingPlatform platform = new SinkingPlatform(entityData, offset) as patch_SinkingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "crumbleBlock")
            {
                patch_CrumblePlatform platform = new CrumblePlatform(entityData, offset) as patch_CrumblePlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "wire")
            {
                Wire wire = new Wire(entityData, offset);
                if (entityData.Has("color"))
                {
                    wire.Color = entityData.HexColor("color");
                }
                level.Add(wire);
                return(true);
            }

            if (!_LoadStrings.Contains(entityData.Name))
            {
                Logger.Log(LogLevel.Warn, "LoadLevel", $"Failed loading entity {entityData.Name}");
            }

            return(false);
        }
 public RemoveBadLinksCommand(Cloud cloud, string path, IList <string> parames) : base(cloud, path, parames)
 {
 }
Beispiel #35
0
    // =============================================== Simulation

    // Runs a single frame of the erosion simulation
    private void ErosionSimulation()
    {
        Vector2 gpc;
        int     iterations = weatherlessDropletIterations;

        if (simulateWeather)
        {
            iterations = clouds.Count;
        }
        // Create a water Droplet for every cloud
        for (int cloudIndex = 0; cloudIndex < iterations; cloudIndex++)
        {
            if (simulateWeather)
            {
                Cloud cloud = clouds[cloudIndex];
                // Create water droplet at random place below cloud
                float lonOffset = UnityEngine.Random.value * cloud.radius * 2f - cloud.radius;
                float latOffset = UnityEngine.Random.value * cloud.radius * 2f - cloud.radius;
                gpc = cloud.globalCoords + new Vector2(lonOffset, latOffset);
                gpc = GPCClampToBounds(gpc);
            }
            else
            {
                gpc = new Vector2(UnityEngine.Random.value * 360 - 180, UnityEngine.Random.value * 180 - 90);
            }
            Vector3 dir      = Vector3.zero;
            float   speed    = initialSpeed;
            float   water    = initialWaterVolume;
            float   sediment = 0;

            int vertexIndex;
            int newVertexIndex;

            int     face_start = GPCToFaceIndex(gpc);
            Vector3 pos        = GetWorldSpaceFromGPC(gpc, face_start);

            // Simulate Droplet's Life
            for (int lifetime = 0; lifetime < maxDropletLifetime; lifetime++)
            {
                vertexIndex = GetClosestVertex(pos, face_start);

                // Calculate droplet's height and direction of flow
                float     height    = pos.magnitude;
                Direction direction = GetFlowDirection(face_start);

                // Update the droplet's direction and position (move position 1 unit regardless of speed)
                dir = (dir * inertia + direction.worldDirection * (1 - inertia));
                dir = dir.normalized;
                direction.worldDirection = dir;
                newVertexIndex           = GetNextVertex(direction.GPCDirection(), vertexIndex);
                gpc = positionToGPC(pos + (dir * (vertices[newVertexIndex] - vertices[vertexIndex]).magnitude));

                // Stop Simulating droplet if it's not moving
                if (dir.x == 0 && dir.y == 0)
                {
                    break;
                }

                // Find droplets new height and calculate the delta height
                int currFaceStart = face_start;
                face_start = GetFace(gpc, newVertexIndex);
                if (face_start == -1)
                {
                    face_start = GPCToFaceIndex(gpc);
                }

                pos = GetWorldSpaceFromGPC(gpc, face_start);
                float newHeight   = pos.magnitude;
                float deltaHeight = newHeight - height;

                // Calculate the droplet's sediment capacity (higher when moving fast down a slope and contains lots of water)
                float sedimentCapacity = Mathf.Max(-deltaHeight * speed * water * sedimentCapacityFactor, minSedimentCapacity);

                // We don't want to do any erosion or depositing if we havn't changed faces
                // If carrying more sediment than capacity, or if flowing uphill:
                if ((sediment > sedimentCapacity || deltaHeight > 0) && currFaceStart != face_start)
                {
                    // If moving uphill (deltaHeight > 0) try fill up to the current height, otherwise deposit a fraction of the excess sediment
                    float amountToDeposit = (deltaHeight > 0) ? Mathf.Min(deltaHeight, sediment) : (sediment - sedimentCapacity) * depositSpeed;
                    sediment -= amountToDeposit;

                    // Add Sediment to this vertex (not to radius to fill small pits)
                    vertices[vertexIndex] += vertices[vertexIndex].normalized * amountToDeposit;
                }
                else if (currFaceStart != face_start)
                {
                    // Erode a fraction of the droplet's current carry capacity.
                    // Clamp the erosion to the change in height so that it doesn't dig a hole in the terrain behind the droplet
                    float amountToErode = Mathf.Min((sedimentCapacity - sediment) * erodeSpeed, -deltaHeight);

                    // Use erosion brush to erode from all nodes inside the droplet's erosion radius
                    for (int brushPointIndex = 0; brushPointIndex < erosionBrushIndices[vertexIndex].Length; brushPointIndex++)
                    {
                        int   nodeIndex          = erosionBrushIndices[vertexIndex][brushPointIndex];
                        float weighedErodeAmount = amountToErode * erosionBrushWeights[vertexIndex][brushPointIndex];
                        float deltaSediment      = (vertices[nodeIndex].magnitude < weighedErodeAmount) ? vertices[nodeIndex].magnitude : weighedErodeAmount;
                        vertices[nodeIndex] -= vertices[nodeIndex].normalized * deltaSediment;
                        FixNormals(nodeIndex);
                        sediment += deltaSediment;
                    }
                }

                // Update droplet's speed and water content
                speed  = Mathf.Sqrt(speed * speed + deltaHeight * gravity);
                water *= (1 - evaporateSpeed);
            }
        }
    }
        private void MoveTimer_Tick(object sender, object e)
        {
            cheat = togleCheat.IsOn;
            canvasWidth();
            canvasHeight();
            date = cheat ? new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, timePicker.Time.Hours, timePicker.Time.Minutes, 0, 0) : DateTime.Now; //new DateTime(2018, 04, 26, 17, 11, 0, 0);
            b    = getCurrentColor(date);
            currentBackGroundColor = Color.FromArgb(255, (byte)(b / 2), (byte)(b / 2), b);
            mainClcl = Colors.WhiteSmoke;
            secClcl  = Colors.Gray;

            getFrequency();
            if (!cheat && cheatTaggled)
            {
                clouds = new List <Cloud>();
                width  = 1700;
                float x = width / frequency;
                for (float i = 0; i < frequency; i++)
                {
                    var cl = new Cloud(x / 2 + i * x, cloudHeight * k + random(-1 * (cloudHeight * k) / 2, (cloudHeight * k) / 1.5f),
                                       (int)random(4, 12), cloudHeight, 0);
                    clouds.Add(cl);
                }
                cheatTaggled = !cheatTaggled;
            }

            float maxWidth = (float)this.maxWidth();

            dk3 = -3;

            var lastId = clouds.Count - 1;

            if (clouds[0].maxX < -25)
            {
                clouds[0].makeCloud(width + 100, cloudHeight * k + random(-1 * (cloudHeight * k) / 3, (cloudHeight * k) / 1.5f),
                                    (int)random(4, 12), lastId);
                clouds = Ofset(clouds);
            }

            foreach (Cloud cl in clouds)
            {
                cl.move(dk3);
            }


            float animSpeed  = 0.15f;
            float animSpeed2 = 0.3f;

            if (forward && dk < 5)
            {
                dk += animSpeed;
            }
            else if (forward)
            {
                forward = !forward;
                dk     -= animSpeed;
            }
            else if (!forward && dk >= 0)
            {
                dk -= animSpeed;
            }
            else
            {
                forward = !forward;
            }

            if (dk2 < (20 / animSpeed2 - 20 % animSpeed2) * animSpeed2)
            {
                dk2 += animSpeed2;
            }
            else
            {
                dk2 = 0;
            }
        }
        private Stream OpenReadStream(Cloud cloud, long?start, long?end)
        {
            Stream stream = cloud.GetFileDownloadStream(_fileInfo, start, end).Result;

            return(stream);
        }
Beispiel #38
0
    internal void Render()
    {
        if (bounds == null)
        {
            bounds = GetBounds();
        }

        float now = Time.realtimeSinceStartup;

        for (int i = 0; i < clouds.Length; i++)
        {
            Cloud cloud = clouds[i];
            if (cloud != null)
            {
                //cloud is visible
                if (cloud.obj == null)
                {
                    //create gameobject and set texture
                    cloud.obj = CreateGameObject(i);
                    cloud.mr  = cloud.obj.GetComponent <MeshRenderer>();
                    cloud.mr.material.mainTexture = textures[cloud.texture];
                    cloud.position.x = UnityEngine.Random.Range(bounds[0] - BOUNDS_PADDING, bounds[1] + BOUNDS_PADDING);
                    cloud.position.z = UnityEngine.Random.Range(bounds[2] - BOUNDS_PADDING, bounds[3] + BOUNDS_PADDING);
                    cloud.spawnTime  = 0;
                    cloudsVisible++;
                }

                //update cloud position
                float modifier = Mathf.Pow(Mathf.Sin(cloud.seed + now / 4f), 2) * 0.5f;
                cloud.position.x            += cloud.direction.x * Time.deltaTime * (1 - modifier);
                cloud.obj.transform.position = cloud.position;


                float alpha;
                //fade out
                if (cloud.fadeOut)
                {
                    alpha = Mathf.Clamp01(Mathf.Abs(cloud.fadeOutAt - now) / FADEOUT_DURATION);

                    if (now > cloud.fadeOutAt)
                    {
                        cloud.fadeOut = false;
                        cloudsVisible++;
                        cloud.spawnTime  = now;
                        cloud.position.x = UnityEngine.Random.Range(bounds[0] - BOUNDS_PADDING, bounds[1] + BOUNDS_PADDING / 2);
                        cloud.position.z = UnityEngine.Random.Range(bounds[2] - BOUNDS_PADDING / 2, bounds[3] + BOUNDS_PADDING / 2);
                    }
                }
                else
                {
                    if (!IsInsideBounds(cloud.position))
                    {
                        cloud.fadeOut   = true;
                        cloud.fadeOutAt = now;
                        cloudsVisible--;
                    }

                    //fade in
                    alpha = Mathf.Clamp01((now - cloud.spawnTime) / FADEIN_DURATION);
                }

                cloud.color.a = alpha;
                cloud.mr.material.SetColor("_TintColor", cloud.color);
            }
        }
    }
Beispiel #39
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 4)
                {
#if DEBUG
                    Console.WriteLine("invalid arguments");
                    Console.ReadLine();
#endif
                    return;
                }

                string pipeName         = args[0];
                string connectionTarget = args[1];
                string portNoStr        = args[2];
                string param3           = args[3];
#if DEBUG
                Console.WriteLine($"{nameof(pipeName)}={pipeName},{nameof(connectionTarget)}={connectionTarget},{nameof(portNoStr)}={portNoStr},{nameof(param3)}={param3}");
#endif

                int      portNo   = int.Parse(portNoStr);
                PeerName peerName = null;
                Cloud    cloud    = null;

                switch (connectionTarget.ToLower())
                {
                case "global":
                    cloud    = Cloud.Global;
                    peerName = PeerName.CreateFromPeerHostName(param3);
                    break;

                case "local":
                    cloud    = Cloud.AllLinkLocal;
                    peerName = new PeerName(param3, PeerNameType.Secured);
                    break;

                default:
                    throw new ArgumentException("invalid argument", "param 1");
                }

                using (var namedPipePipeToPeer = new NamedPipeClientStream(".", pipeName + "PipeToPeer"))
                {
                    namedPipePipeToPeer.Connect();
#if DEBUG
                    Console.WriteLine("connect named pipe 'PipeToPeer'");
#endif
                    using (var namedPipePeerToPipe = new NamedPipeClientStream(".", pipeName + "PeerToPipe"))
                    {
                        namedPipePeerToPipe.Connect();
#if DEBUG
                        Console.WriteLine("connect named pipe 'PeerToPipe'");
#endif
                        var peerNameResolver = new PeerNameResolver();

                        while (namedPipePipeToPeer.IsConnected && namedPipePeerToPipe.IsConnected)
                        {
                            int result = namedPipePipeToPeer.ReadByte();
                            if (result < 0)
                            {
                                break;
                            }
#if DEBUG
                            Console.WriteLine("read");
#endif
                            // 読み込み実行
                            if (result == 0xFF)
                            {
#if DEBUG
                                Console.WriteLine("resolve start");
#endif
                                foreach (var record in peerNameResolver.Resolve(peerName, cloud))
                                {
                                    namedPipePeerToPipe.Write(record.Data, 0, record.Data.Length);
                                    namedPipePeerToPipe.Flush();
                                    namedPipePeerToPipe.WaitForPipeDrain();
#if DEBUG
                                    var buffer = record.Data;
                                    var length = record.Data.Length;
                                    Console.WriteLine($"{nameof(buffer)}[{length}]={BitConverter.ToString(buffer, 0, length).Replace("-", string.Empty)}");
#endif
                                }

                                namedPipePeerToPipe.WriteByte(0xFF);//終端
                                namedPipePeerToPipe.Flush();
                                namedPipePeerToPipe.WaitForPipeDrain();

#if DEBUG
                                Console.WriteLine("resolve end");
#endif
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(ex);
                Console.ReadLine();
#endif
            }
#if DEBUG
            Console.WriteLine("end");
#endif
        }
        public async Task <StoreItemResult> MoveItemAsync(string sourceName, IStoreCollection destinationCollection, string destinationName, bool overwrite, IHttpContext httpContext)
        {
            // Return error
            if (!IsWritable)
            {
                return(new StoreItemResult(DavStatusCode.PreconditionFailed));
            }

            // Determine the object that is being moved
            var item = await GetItemAsync(sourceName, httpContext);

            if (item == null)
            {
                return(new StoreItemResult(DavStatusCode.NotFound));
            }


            var destinationStoreCollection = destinationCollection as MailruStoreCollection;

            if (destinationStoreCollection != null)
            {
                if (!destinationStoreCollection.IsWritable)
                {
                    return(new StoreItemResult(DavStatusCode.PreconditionFailed));
                }

                var itemexist = destinationStoreCollection.FindSubItem(destinationName);

                DavStatusCode result;

                if (itemexist != null)
                {
                    if (!overwrite)
                    {
                        return(new StoreItemResult(DavStatusCode.Forbidden));
                    }

                    await Cloud.Instance(httpContext).Remove(itemexist);

                    result = DavStatusCode.NoContent;
                }
                else
                {
                    result = DavStatusCode.Created;
                }


                if (destinationStoreCollection.FullPath == FullPath)
                {
                    await Cloud.Instance(httpContext).Rename(item, destinationName);
                }
                else
                {
                    await Cloud.Instance(httpContext).Move(item, destinationStoreCollection.FullPath);
                }

                return(new StoreItemResult(result, new MailruStoreItem(LockingManager, null, IsWritable)));
            }
            else
            {
                // Attempt to copy the item to the destination collection
                var result = await item.CopyAsync(destinationCollection, destinationName, overwrite, httpContext);

                if (result.Result == DavStatusCode.Created || result.Result == DavStatusCode.NoContent)
                {
                    await DeleteItemAsync(sourceName, httpContext);
                }

                return(result);
            }
        }
Beispiel #41
0
        private async Task <SpecialCommandResult> ExecuteByLink(string path, string link)
        {
            var k = await Cloud.CloneItem(path, link);

            return(new SpecialCommandResult(k.IsSuccess));
        }
Beispiel #42
0
        //private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(FishCommand));

        public ListCommand(Cloud cloud, string path, IList <string> parames) : base(cloud, path, parames)
        {
        }
Beispiel #43
0
 public VcapClient(Cloud cloud)
 {
     credMgr = new VcapCredentialManager();
     credMgr.SetTarget(cloud.Url);
     this.cloud = cloud;
 }
 public SharedFolderLinkCommand(Cloud cloud, string path, IList <string> parames) : base(cloud, path, parames)
 {
 }
        public override async Task <SpecialCommandResult> Execute()
        {
            Cloud.CleanTrash();

            return(await Task.FromResult(SpecialCommandResult.Success));
        }
Beispiel #46
0
        public void SaveToFile(string path)
        {
            using (StreamWriter sw = new StreamWriter(path))
                using (XmlWriter writer = XmlWriter.Create(sw, Resource.XmlWriterSettings))
                {
                    writer.WriteStartElement("party");

                    writer.WriteStartElement("characters");
                    Cloud.WriteToXml(writer);
                    Tifa.WriteToXml(writer);
                    Barret.WriteToXml(writer);
                    Aeris.WriteToXml(writer);
                    RedXIII.WriteToXml(writer);
                    CaitSith.WriteToXml(writer);
                    Yuffie.WriteToXml(writer);
                    Vincent.WriteToXml(writer);
                    Cid.WriteToXml(writer);
                    Sephiroth.WriteToXml(writer);
                    writer.WriteEndElement(); // characters

                    for (int i = 0; i < PARTY_SIZE; i++)
                    {
                        writer.WriteElementString("slot" + i, this[i].Name);
                    }

                    foreach (Character c in Reserves)
                    {
                        if (c != null)
                        {
                            writer.WriteElementString("reserve", c.Name);
                        }
                    }

                    Inventory.WriteToXml(writer);
                    Materiatory.WriteToXml(writer);

                    writer.WriteElementString("gil", Gil.ToString());
                    writer.WriteElementString("time", Clock.TotalMilliseconds.ToString());

                    writer.WriteStartElement("config");
                    writer.WriteStartElement("menu");

                    for (int i = 0; i < 4; i++)
                    {
                        int r, g, b;

                        Menu.Menu.GetCornerColor(i, out r, out g, out b);

                        writer.WriteStartElement("corner" + i.ToString());
                        writer.WriteAttributeString("r", r.ToString());
                        writer.WriteAttributeString("g", g.ToString());
                        writer.WriteAttributeString("b", b.ToString());
                        writer.WriteEndElement(); // corner
                    }

                    writer.WriteEndElement(); // menu
                    writer.WriteEndElement(); // config

                    writer.WriteEndElement(); // party
                }
        }
Beispiel #47
0
    Vector3 RightMostOfScreen;                                                // Vector3 of middle-right most position at the edge of the camera view

    #endregion

    // ######################################################################
    // MonoBehaviour Functions
    // ######################################################################

    #region Monobehavior

    // Use this for initialization
    void Start()
    {
        // init m_CloudList
        m_CloudList = new Cloud[transform.childCount];

        // Random first direction
        int RandomDirection = Random.Range(0, 2);

        // Survey all chilren and put them to m_CloudList
        int index = 0;

        foreach (Transform child in transform)
        {
            // Create new Cloud class
            m_CloudList[index] = new Cloud();

            // Random speed
            m_CloudList[index].m_MoveSpeed = Random.Range(m_MinSpeed, m_MaxSpeed);

            // Left/right direction
            if (RandomDirection == 0)
            {
                m_CloudList[index].m_MoveSpeed *= -1;
                if (m_Behavior == eCloudFlowBehavior.SwitchLeftRight)
                {
                    RandomDirection = 1;
                }
            }
            else
            {
                if (m_Behavior == eCloudFlowBehavior.SwitchLeftRight)
                {
                    RandomDirection = 0;
                }
            }

            // Set this gameObject to current m_CloudList.m_Cloud
            m_CloudList[index].m_Cloud = child.gameObject;

            // If this is Large Cloud then duplicate current Cloud, we will use it to make seamless move on the screen
            if (m_EnableLargeCloudLoop == true)
            {
                m_CloudList[index].m_CloudFollower = (GameObject)Instantiate(child.gameObject);
            }

            // Keep original LocalPosition to use later when we have to pool this cloud when it move off the screen edge
            m_CloudList[index].m_OriginalLocalPos = m_CloudList[index].m_Cloud.transform.localPosition;

            // Increase index
            index++;
        }

        // Move Duplicated clouds as children of this gameObject
        if (m_EnableLargeCloudLoop == true)
        {
            foreach (Cloud child in m_CloudList)
            {
                child.m_CloudFollower.transform.parent = this.transform;
            }
        }

        // Make sure we have Orthographic Camera
        FindTheOrthographicCamera();
    }
Beispiel #48
0
        //</Snippet1>

        /// <summary>
        /// Parse the command line arguments
        /// </summary>
        private static bool ParseCommandLine(string[] args)
        {
            //Command line format:
            const string usage = "Usage: RegisterPeerName.exe <Peer Name Classifier> <PeerNameType:Secured|UnSecured> <Port #> <Comment> <Cloud Name:Available|AllLinkLocal|Global>";

            try
            {
                if (args.Length < 5)
                {
                    Console.WriteLine(usage);
                    return(false);
                }

                peerNameClassifier = args[0];

                //Create a secure or unsecure PeerName using the command line arguments: <PeerNameClassifier> and <PeerNameType:Secured|UnSecured>
                string peerNameTypeArgument = args[1].ToLower();
                if (peerNameTypeArgument.Equals("secured"))
                {
                    peerNameType = PeerNameType.Secured;
                }
                else if (peerNameTypeArgument.Equals("unsecured"))
                {
                    peerNameType = PeerNameType.Unsecured;
                }
                else
                {
                    Console.WriteLine("PeerNameType argument is invalid.\n");
                    Console.WriteLine(usage);
                    return(false);
                }

                // read the port number
                portNumber = int.Parse(args[2]);

                // read the commment to assign to the peername
                comment = args[3];

                // determine the cloud to register the peername into
                string cloudNameArgument = args[4].ToLower();
                if (cloudNameArgument.Equals("available"))
                {
                    cloudName = Cloud.Available;
                }
                else if (cloudNameArgument.Equals("alllinklocal"))
                {
                    cloudName = Cloud.AllLinkLocal;
                }
                else if (cloudNameArgument.Equals("global"))
                {
                    cloudName = Cloud.Global;
                }
                else
                {
                    Console.WriteLine("Cloud Name argument is invalid.\n");
                    Console.WriteLine(usage);
                    return(false);
                }
            }
            catch (Exception e)
            {
                // P2P is not supported on Windows Server 2003
                if (e.InnerException != null)
                {
                    Console.WriteLine("Error occured while attempting to register the PeerName: {0}", e.Message);
                    Console.WriteLine(e.StackTrace);

                    Console.WriteLine("Inner Exception is {0}", e.InnerException);
                }
                else
                {
                    Console.WriteLine("Error occured while attempting to register the PeerName: {0}", e.Message);
                    Console.WriteLine(usage);

                    Console.WriteLine("Exception is {0}", e);
                    Console.WriteLine(e.StackTrace);
                }
                return(false);
            }
            return(true);
        }
Beispiel #49
0
        public static void UseLambda(this Cloud cloud)
        {
            // case 1. use EngineObjectHookContext
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (context) =>
            {
                var todo = context.TheObject;
                var by   = context.By;
                return(Task.FromResult(context.TheObject));
            });

            cloud.BeforeSave("Todo", (context) =>
            {
                return(Task.FromResult(context.TheObject));
            });

            // case 2. use TheObject
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (AVObject todoObj) =>
            {
                return(Task.FromResult(todoObj));
            });

            cloud.BeforeSave("Todo", (AVObject todoObj) =>
            {
                return(Task.FromResult(todoObj));
            });

            // case 3. use TheObject and user
            cloud.UseHook("Todo", EngineHookType.BeforeSave, (AVObject todoObj, AVUser by) =>
            {
                return(Task.FromResult(todoObj));
            });

            cloud.BeforeSave("Todo", (AVObject todoObj, AVUser by) =>
            {
                return(Task.FromResult(todoObj));
            });

            // case 3. use sub-class
            AVObject.RegisterSubclass <Todo>();

            cloud.UseHook <Todo>(EngineHookType.BeforeSave, (Todo theTodoObj) =>
            {
                // theTodoObj is an Todo instance.
                return(Task.FromResult(theTodoObj));
            });

            cloud.UseHook <Todo>(EngineHookType.BeforeSave, (Todo theTodoObj, AVUser by) =>
            {
                return(Task.FromResult(theTodoObj));
            });

            cloud.BeforeSave <Todo>((todo) =>
            {
                // todo is an Todo instance.
                return(Task.FromResult(todo));
            });

            cloud.BeforeSave <Todo>((todo, by) =>
            {
                // todo is an Todo instance.
                return(Task.FromResult(todo));
            });

            cloud.BeforeUpdate("Todo", review =>
            {
                var updatedKeys = review.GetUpdatedKeys();
                if (updatedKeys.Contains("comment"))
                {
                    var comment = review.Get <string>("comment");
                    if (comment.Length > 140)
                    {
                        throw new EngineException(400, "comment 长度不得超过 140 字符");
                    }
                }
                return(Task.FromResult(true));
            });

            EngineHookDelegateSynchronous afterPostHook = (post) =>
            {
            };

            cloud.AfterSave("Post", (EngineObjectHookDeltegateSynchronous)(async post =>
            {
                // 直接修改并保存对象不会再次触发 after update hook 函数
                post["foo"] = "bar";
                await post.SaveAsync();
                // 如果有 FetchAsync 操作,则需要在新获得的对象上调用相关的 disable 方法
                // 来确保不会再次触发 Hook 函数
                await post.FetchAsync();
                post.DisableAfterHook();
                post["foo"] = "bar";

                // 如果是其他方式构建对象,则需要在新构建的对象上调用相关的 disable 方法
                // 来确保不会再次触发 Hook 函数
                post = AVObject.CreateWithoutData <AVObject>(post.ObjectId);
                post.DisableAfterHook();
                await post.SaveAsync();
            }));
        }
Beispiel #50
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (IsHeld == true)
        {
            return;
        }

        if (IsPlayer)
        {
            RatBrain brain = GetComponent <RatBrain>();
            if (brain.IsYote == false)
            {
                return;
            }
        }

        if (_killMode == true)
        {
            Debug.Log("killhit " + collision.collider.gameObject.name);
        }

        if (collision.collider.CompareTag("Player") && _killMode && Kills)
        {
            RatPlayer yeeter = this.LastYeeter.GetComponent <RatPlayer>();
            RatPlayer hit    = collision.collider.GetComponent <RatPlayer>();
            hit.Kill();
            if (hit != yeeter)
            {
                yeeter.AwardPoint();
            }
            Cinemachine.CinemachineImpulseSource impulse = GetComponent <Cinemachine.CinemachineImpulseSource>();
            impulse?.GenerateImpulse(this.MyRigidbody.velocity);
            AudioManager.Instance.PlaySound(HitSFX, this.transform.position);

            if (!IsPlayer)
            {
                PoolManager.Instance.releaseObject(this.gameObject);
            }

            Cloud.Spawn(collision.contacts[0].point, Cloud.Size.Large);
            _killMode = false;
        }
        else
        {
            if (_killMode)
            {
                AudioManager.Instance.PlaySound(HitGroundSFX, collision.contacts[0].point, AudioManager.MixerGroup.SFX, 0.8f);
                Cloud.Spawn(collision.contacts[0].point, Cloud.Size.Small);
            }
            _killMode = false;
        }


        if (SpinOnThrow)
        {
            this.Animator?.Play("ItemSpin");
        }
        else
        {
            this.Animator?.Play("ItemIdle");
        }

        if (collision.collider.CompareTag("Planet"))
        {
            var r2d = GetComponent <Rigidbody2D>();
            r2d.velocity = Vector3.zero;
            r2d.Sleep();
        }

        if (IsPlayer)
        {
            ReleaseAndSetKinematic();
        }
    }
 // Start is called before the first frame update
 void Start()
 {
     cb = CotcSdk.GetComponent <CotcGameObject>();
     cb.GetCloud().Done(cloud => { Cloud = cloud; });
 }
Beispiel #52
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //Game Menu
            if (!isStarted)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                {
                    isStarted            = true;
                    instructionText.Text = "- enter to retry -";
                    MediaPlayer.Play(backgroundSong);
                }
                return;
            }

            if (gameOver && Keyboard.GetState().IsKeyDown(Keys.Enter))
            {
                Restart();
                return;
            }
            else if (gameOver)
            {
                return;
            }

            //Increase speed time by time
            timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (timer > timeSpan && gameSpeed < 15)
            {
                gameSpeed += 2;
                timeSpan   = timer * 2;
            }

            //Add the cloud
            if (onTimeToAddCloud(gameTime))
            {
                var cloud = new Cloud(Content.Load <Texture2D>("Background/Cloud"))
                {
                    Position = GetRandomCloudPosition()
                };

                gameObjects.Add(cloud);
            }

            //Add the new tree
            if (onTimeToAddTree(gameTime))
            {
                var tree = GetRandomTreeTexture(treeTextures);

                gameObjects.Add(tree);
            }

            //Add the new flydino
            if (onTimeToAddFlyDino(gameTime))
            {
                var flyDino = new FlyDino(flyDinoAnimation)
                {
                    Position = GetRandomFlyDinoPosition(),
                };

                gameObjects.Add(flyDino);
            }

            //Update the game objects
            for (int i = 0; i < gameObjects.Count; i++)
            {
                //
                //Update the game speed
                //
                if (gameObjects[i] is FlyDino)
                {
                    /*The FlyDino will be faster.*/
                    gameObjects[i].Speed = gameSpeed + gameSpeed * 0.4f;
                }
                else if (gameObjects[i] is Cloud)
                {
                    /*The Cloud will be slower than everything. It make sense in real life :) */
                    gameObjects[i].Speed = gameSpeed - gameSpeed * 0.3f;
                }
                else
                {
                    gameObjects[i].Speed = gameSpeed;
                }

                gameObjects[i].Update(gameTime, gameObjects);


                //
                //Remove the out-screen object
                //
                if (gameObjects[i] is Tree || gameObjects[i] is FlyDino || gameObjects[i] is Cloud)
                {
                    if (gameObjects[i].Position.X + gameObjects[i].Rectangle.Width <= 0)
                    {
                        gameObjects.RemoveAt(i);
                        i--;
                    }
                }

                //
                //Check collision
                //
                if (gameObjects[i] is Dino)
                {
                    if (gameObjects[i].CheckCollision(gameObjects))
                    {
                        gameOver = true;
                        MediaPlayer.Stop();
                    }
                }
            }

            //
            // Calculate scrore
            //
            currentScore.Value = (int)timer;
            if (currentScore.Value > highScore.Value)
            {
                highScore.Value = currentScore.Value;
            }

            base.Update(gameTime);
        }
Beispiel #53
0
        // Called from LoadLevel, patched via MonoModRules.PatchLevelLoader
        public static bool LoadCustomEntity(EntityData entityData, Level level)
        {
            LevelData levelData = level.Session.LevelData;
            Vector2   offset    = new Vector2(levelData.Bounds.Left, levelData.Bounds.Top);

            if (Everest.Events.Level.LoadEntity(level, levelData, offset, entityData))
            {
                return(true);
            }

            // Everest comes with a few core utility entities out of the box.

            if (entityData.Name == "everest/spaceController")
            {
                level.Add(new SpaceController());
                return(true);
            }
            if (entityData.Name == "everest/spaceControllerBlocker")
            {
                level.Add(new SpaceControllerBlocker());
                return(true);
            }

            if (entityData.Name == "everest/flagTrigger")
            {
                level.Add(new FlagTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/changeInventoryTrigger")
            {
                level.Add(new ChangeInventoryTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/coreMessage")
            {
                level.Add(new CustomCoreMessage(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/memorial")
            {
                level.Add(new CustomMemorial(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/npc")
            {
                level.Add(new CustomNPC(entityData, offset, new EntityID(levelData.Name, entityData.ID)));
                return(true);
            }

            if (entityData.Name == "everest/dialogTrigger" ||
                entityData.Name == "dialog/dialogtrigger" ||
                entityData.Name == "cavern/dialogtrigger")
            {
                level.Add(new DialogCutsceneTrigger(entityData, offset, new EntityID(levelData.Name, entityData.ID)));
                return(true);
            }

            if (entityData.Name == "everest/crystalShatterTrigger" ||
                entityData.Name == "outback/destroycrystalstrigger")
            {
                level.Add(new CrystalShatterTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/completeAreaTrigger" ||
                entityData.Name == "outback/completeareatrigger")
            {
                level.Add(new CompleteAreaTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/lavaBlockerTrigger" ||
                entityData.Name == "cavern/lavablockertrigger")
            {
                level.Add(new LavaBlockerTrigger(entityData, offset));
                return(true);
            }

            if (entityData.Name == "everest/coreModeTrigger" ||
                entityData.Name == "cavern/coremodetrigger")
            {
                level.Add(new CoreModeTrigger(entityData, offset));
                return(true);
            }

            // The following entities have hardcoded "attributes."
            // Everest allows custom maps to set them.

            if (entityData.Name == "spinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustStaticSpinner(entityData, offset));
                    return(true);
                }

                CrystalColor color = CrystalColor.Blue;
                if (level.Session.Area.ID == 5)
                {
                    color = CrystalColor.Red;
                }
                else if (level.Session.Area.ID == 6)
                {
                    color = CrystalColor.Purple;
                }
                else if ("core".Equals(entityData.Attr("color"), StringComparison.InvariantCultureIgnoreCase))
                {
                    color = (CrystalColor)(-1);
                }
                else if (!Enum.TryParse(entityData.Attr("color"), true, out color))
                {
                    color = CrystalColor.Blue;
                }

                level.Add(new CrystalStaticSpinner(entityData, offset, color));
                return(true);
            }

            if (entityData.Name == "trackSpinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustTrackSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeTrackSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "rotateSpinner")
            {
                if (level.Session.Area.ID == 3 ||
                    (level.Session.Area.ID == 7 && level.Session.Level.StartsWith("d-")) ||
                    entityData.Bool("dust"))
                {
                    level.Add(new DustRotateSpinner(entityData, offset));
                    return(true);
                }

                level.Add(new BladeRotateSpinner(entityData, offset));
                return(true);
            }

            if (entityData.Name == "checkpoint" &&
                entityData.Position == Vector2.Zero &&
                !entityData.Bool("allowOrigin"))
            {
                // Workaround for mod levels with old versions of Ahorn containing a checkpoint at (0, 0):
                // Create the checkpoint and avoid the start position update in orig_Load.
                level.Add(new Checkpoint(entityData, offset));
                return(true);
            }

            if (entityData.Name == "triggerSpikesOriginalUp")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Up));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalDown")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Down));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalLeft")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Left));
                return(true);
            }
            if (entityData.Name == "triggerSpikesOriginalRight")
            {
                level.Add(new TriggerSpikesOriginal(entityData, offset, TriggerSpikesOriginal.Directions.Right));
                return(true);
            }

            if (entityData.Name == "darkChaserEnd")
            {
                level.Add(new BadelineOldsiteEnd(entityData, offset));
                return(true);
            }

            if (entityData.Name == "cloud")
            {
                patch_Cloud cloud = new Cloud(entityData, offset) as patch_Cloud;
                if (entityData.Has("small"))
                {
                    cloud.Small = entityData.Bool("small");
                }
                level.Add(cloud);
                return(true);
            }

            if (entityData.Name == "cobweb")
            {
                patch_Cobweb cobweb = new Cobweb(entityData, offset) as patch_Cobweb;
                if (entityData.Has("color"))
                {
                    cobweb.OverrideColor = entityData.HexColor("color");
                }
                level.Add(cobweb);
                return(true);
            }

            if (entityData.Name == "movingPlatform")
            {
                patch_MovingPlatform platform = new MovingPlatform(entityData, offset) as patch_MovingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "sinkingPlatform")
            {
                patch_SinkingPlatform platform = new SinkingPlatform(entityData, offset) as patch_SinkingPlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "crumbleBlock")
            {
                patch_CrumblePlatform platform = new CrumblePlatform(entityData, offset) as patch_CrumblePlatform;
                if (entityData.Has("texture"))
                {
                    platform.OverrideTexture = entityData.Attr("texture");
                }
                level.Add(platform);
                return(true);
            }

            if (entityData.Name == "wire")
            {
                Wire wire = new Wire(entityData, offset);
                if (entityData.Has("color"))
                {
                    wire.Color = entityData.HexColor("color");
                }
                level.Add(wire);
                return(true);
            }

            return(false);
        }
 public override Task <SpecialCommandResult> Execute()
 {
     Cloud.RemoveDeadLinks();
     return(Task.FromResult(SpecialCommandResult.Success));
 }
        public static int Upload(UploadOptions cmdoptions)
        {
            string user       = cmdoptions.Login;
            string password   = cmdoptions.Password;
            string listname   = cmdoptions.FileList;
            string targetpath = cmdoptions.Target;



            if (targetpath.StartsWith(@"\\\"))
            {
                targetpath = Regex.Replace(targetpath, @"\A\\\\\\.*?\\.*?\\", @"\");
            }

            targetpath = WebDavPath.Clean(targetpath);

            var settings = new CloudSettings
            {
                TwoFaHandler = null,
                Protocol     = Protocol.WebM1Bin
            };
            var credentials = new Credentials(user, password);
            var cloud       = new Cloud(settings, credentials);

            using (var file = new StreamReader(listname))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    System.Console.WriteLine($"Source: {line}");
                    var fileInfo = new FileInfo(line);

                    string targetfile = WebDavPath.Combine(targetpath, fileInfo.Name);
                    System.Console.WriteLine($"Target: {targetfile}");

                    using (var source = System.IO.File.Open(line, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var hasher = new MailRuSha1Hash();
                        hasher.Append(source);
                        var hash = hasher.HashString;
                        if (cloud.AddFile(hash, targetfile, fileInfo.Length, ConflictResolver.Rename).Result.Success)
                        {
                            System.Console.WriteLine("Added by hash");
                        }
                        else
                        {
                            source.Seek(0, SeekOrigin.Begin);
                            var  buffer = new byte[64000];
                            long wrote  = 0;
                            using (var target = cloud.GetFileUploadStream(WebDavPath.Combine(targetfile, fileInfo.Name), fileInfo.Length).Result)
                            {
                                int read;
                                while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    target.Write(buffer, 0, read);
                                    wrote += read;
                                    System.Console.Write($"\r{wrote / fileInfo.Length * 100}%");
                                }
                            }
                        }

                        System.Console.WriteLine(" Done.");
                        //source.CopyTo(target);
                    }
                }
            }

            return(0);
        }
Beispiel #56
0
    private void Update()
    {
        if (camera.transform.position.y > this.transform.position.y - 100)
        {
            camera.clearFlags = CameraClearFlags.Skybox;
        }
        else
        {
            camera.clearFlags = CameraClearFlags.SolidColor;
        }
        time += Time.deltaTime * cloudSpeed;
        // dayLight = Mathf.Clamp(dayLight + Time.deltaTime * (WorldTime.IsDay() ? 1 : -1), 0, 1);

        for (int c = 0; c < clouds.Count; ++c)
        {
            Cloud   cloud = clouds[c];
            Vector2 seed  = new Vector2(cloud.transform.position.x, time + cloud.transform.position.z) / 100;
            seed.x += (time + cloud.transform.position.y) * 0.1f;
            seed.y += (time + cloud.transform.position.y) * 0.1f;
            float h = Mathf.PerlinNoise(seed.x, seed.y);
            h = 1;// Mathf.Lerp(-5, 10, h);
            cloud.transform.position += new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f)) * 0.25f * Time.deltaTime;
            float alpha;

            if (cloud.currentOpacity == cloud.targetOpacity)
            {
                if (cloud.currentOpacity < 0)
                {
                    cloud.targetOpacity = cloud.maxOpacity;
                }
            }
            else
            {
                cloud.currentOpacity = Mathf.MoveTowards(cloud.currentOpacity, cloud.targetOpacity, Time.deltaTime * (cloud.targetOpacity < 0?10:0.1f));
            }


            alpha = (cloudOpacity[c] * cloudiness * h * cloud.currentOpacity);
            float distance = ((Vector3.Distance(cloud.transform.position, Camera.main.transform.position) - 10) / 1000);
            alpha = Mathf.Lerp(0, alpha, distance);
            alpha = Mathf.Clamp(alpha, 0, maxAlpha);

            if (alpha > 0)
            {
                if (!cloud.gameObject.activeSelf)
                {
                    cloud.gameObject.SetActive(true);
                }

                Color color = cloud.color * dayLight;

                color.a = alpha;

                //cloud.color = color;
                cloud.renderer.color = color;
            }
            else
            {
                if (cloud.gameObject.activeSelf)
                {
                    cloud.gameObject.SetActive(false);
                }
            }
            // cloud.targetOpacity = Mathf.MoveTowards(cloud.targetOpacity, cloud., Time.deltaTime / 10);
        }
    }
Beispiel #57
0
        public void ConstructorTest()
        {
            // coordinates is null
            {
                string parameterName = "coordinates";

                DoubleMatrix coordinates = null;
                DoubleMatrix weights     = DoubleMatrix.Dense(1, 1, 1.0 / 4.0);
                Basis        basis       = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);
            }

            // weights is null
            {
                string parameterName = "weights";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = null;
                Basis        basis       = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);
            }

            // basis is null
            {
                string parameterName = "basis";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1, 1.0 / 4.0);
                Basis        basis       = null;

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage:
                    ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: parameterName);
            }

            // weights is not a column vector
            {
                var STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR =
                    ImplementationServices.GetResourceString(
                        "STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR");

                string parameterName = "weights";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(1, 4);
                Basis        basis       = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_BE_COLUMN_VECTOR,
                    expectedParameterName: parameterName);
            }

            // weights must have the number of rows of coordinates
            {
                var STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS =
                    string.Format(CultureInfo.InvariantCulture,
                                  ImplementationServices.GetResourceString(
                                      "STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS"),
                                  "coordinates");

                string parameterName = "weights";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(5, 1);
                Basis        basis       = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);
            }

            // weights must have non negative entries
            {
                var STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE =
                    ImplementationServices.GetResourceString(
                        "STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE");

                string parameterName = "weights";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1, -1.0);
                Basis        basis       = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_BE_NON_NEGATIVE,
                    expectedParameterName: parameterName);
            }

            // weights must have entries summing up to 1
            {
                var STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1 =
                    ImplementationServices.GetResourceString(
                        "STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1");

                string parameterName = "weights";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1,
                                                              new double[4] {
                    .3, .6, .2, .1
                });
                Basis basis = Basis.Standard(2);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_ENTRIES_MUST_SUM_TO_1,
                    expectedParameterName: parameterName);
            }

            // basis must have dimension equal to the coordinates number of columns
            {
                var STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS =
                    string.Format(CultureInfo.InvariantCulture,
                                  ImplementationServices.GetResourceString(
                                      "STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_COLUMNS"),
                                  "coordinates");

                string parameterName = "basis";

                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1, 1.0 / 4.0);
                Basis        basis       = Basis.Standard(5);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    new Cloud(
                        coordinates,
                        weights,
                        basis);
                },
                    expectedType: typeof(ArgumentOutOfRangeException),
                    expectedPartialMessage:
                    STR_EXCEPT_PAR_MUST_HAVE_SAME_NUM_OF_ROWS,
                    expectedParameterName: parameterName);
            }

            // Valid input and copyData is true
            {
                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1, 1.0 / 4.0);
                Basis        basis       = Basis.Standard(2);

                {
                    var cloud = new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: true);

                    DoubleMatrixAssert.AreEqual(
                        expected: basis.GetBasisMatrix(),
                        actual: cloud.Basis.GetBasisMatrix(),
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: coordinates,
                        actual: cloud.Coordinates,
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: weights,
                        actual: cloud.Weights,
                        delta: CloudTest.Accuracy);

                    coordinates[0, 0] = Double.PositiveInfinity;

                    Assert.AreNotEqual(
                        notExpected: coordinates[0, 0],
                        actual: cloud.Coordinates[0, 0],
                        delta: CloudTest.Accuracy);
                }

                {
                    var cloud = new Cloud(
                        coordinates,
                        weights);

                    DoubleMatrixAssert.AreEqual(
                        expected: basis.GetBasisMatrix(),
                        actual: cloud.Basis.GetBasisMatrix(),
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: coordinates,
                        actual: cloud.Coordinates,
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: weights,
                        actual: cloud.Weights,
                        delta: CloudTest.Accuracy);
                }

                {
                    var cloud = new Cloud(
                        coordinates);

                    DoubleMatrixAssert.AreEqual(
                        expected: basis.GetBasisMatrix(),
                        actual: cloud.Basis.GetBasisMatrix(),
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: coordinates,
                        actual: cloud.Coordinates,
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: weights,
                        actual: cloud.Weights,
                        delta: CloudTest.Accuracy);
                }
            }

            // Valid input and copyData is false
            {
                DoubleMatrix coordinates = DoubleMatrix.Dense(4, 2);
                DoubleMatrix weights     = DoubleMatrix.Dense(4, 1, 1.0 / 4.0);
                Basis        basis       = Basis.Standard(2);

                {
                    var cloud = new Cloud(
                        coordinates,
                        weights,
                        basis,
                        copyData: false);

                    DoubleMatrixAssert.AreEqual(
                        expected: basis.GetBasisMatrix(),
                        actual: cloud.Basis.GetBasisMatrix(),
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: coordinates,
                        actual: cloud.Coordinates,
                        delta: CloudTest.Accuracy);

                    DoubleMatrixAssert.AreEqual(
                        expected: weights,
                        actual: cloud.Weights,
                        delta: CloudTest.Accuracy);

                    coordinates[0, 0] = Double.PositiveInfinity;

                    Assert.AreEqual(
                        expected: coordinates[0, 0],
                        actual: cloud.Coordinates[0, 0],
                        delta: CloudTest.Accuracy);
                }
            }
        }
Beispiel #58
0
 public LocalToServerCopyCommand(Cloud cloud, string path, IList <string> parames) : base(cloud, path, parames)
 {
 }
        public WheatherPage()
        {
            this.InitializeComponent();

            canvasControl.Draw += CanvasControl_Draw1;
            canvasControl.Invalidate();
            Window.Current.VisibilityChanged += Current_VisibilityChanged;

            canvasWidth();
            canvasHeight();

            rand = new Random();

            sun = new Sun(0, 0, 44, 12);

            moon = new Moon(150, 75, 44);

            precip = new Precipitation(cloudHeight * k, 500, 1600);



            tempType   = localSettings.Values["tempType"] != null ? localSettings.Values["tempType"].ToString() : "c";
            windType   = localSettings.Values["windType"] != null ? localSettings.Values["windType"].ToString() : "kph";
            presType   = localSettings.Values["presType"] != null ? localSettings.Values["presType"].ToString() : "mb";
            precipType = localSettings.Values["precipType"] != null ? localSettings.Values["precipType"].ToString() : "mm";
            visType    = localSettings.Values["visType"] != null ? localSettings.Values["visType"].ToString() : "km";
            days       = localSettings.Values["days"] != null?Convert.ToInt32(localSettings.Values["days"].ToString()) : 5;

            cityName = localSettings.Values["cityName"] != null ? localSettings.Values["cityName"].ToString() : "kiev";

            weatherAPI = new WeatherAPI(cityName, days);

            try
            {
                respond    = weatherAPI.getRespond();
                allWeather = JsonConvert.DeserializeObject <AllWeather>(respond);

                JObject        respondObject       = JObject.Parse(respond);
                IList <JToken> respondForecastList = respondObject["forecast"]["forecastday"].Children().ToList();
                forecastDays = new ObservableCollection <ForecastDay>();
                foreach (JToken respondForecast in respondForecastList)
                {
                    ForecastDay forecastDay = respondForecast.ToObject <ForecastDay>();
                    forecastDay.makeFormatedDate();
                    forecastDays.Add(forecastDay);
                }
                ;


                foreach (ForecastDay item in forecastDays)
                {
                    SelectedForecastDay SelectedforecastDay = new SelectedForecastDay(
                        item.dateFormated,
                        getNeedProperty <Day>("maxtemp_", tempType, item.day) + "° ",
                        getNeedProperty <Day>("mintemp_", tempType, item.day) + "° ",
                        getNeedProperty <Day>("avgtemp_", tempType, item.day) + "° " + tempType.ToUpper(),
                        getNeedProperty <Day>("maxwind_", windType, item.day) + " " + windType,
                        getNeedProperty <Day>("totalprecip_", precipType, item.day) + " " + precipType,
                        getNeedProperty <Day>("avgvis_", visType, item.day) + "° " + visType,
                        item.day.avghumidity + "%",
                        item.day.condition.text,
                        "ms-appx:///Assets/weather/" + item.day.condition.icon.Substring(30),
                        item.day.condition.code + "",
                        item.astro.moonset,
                        item.astro.moonrise,
                        item.astro.sunrise,
                        item.astro.sunset);
                    _forecastDays.Add(SelectedforecastDay);
                }

                location.Text             = allWeather.location.name + ", " + allWeather.location.country;
                currentTempreture.Text    = getNeedProperty <CurrentWeather>("temp_", tempType, allWeather.current) + "° " + tempType;
                currentDate.Text          = DateTime.Now.ToString("ddd d", new CultureInfo("en-US"));
                currentCondition.Text     = allWeather.current.condition.text;
                currentWind.Text          = "Wind" + getNeedProperty <CurrentWeather>("wind_", windType, allWeather.current) + " " + windType + " " + allWeather.current.wind_dir;
                currentPresure.Text       = "Presure " + getNeedProperty <CurrentWeather>("pressure_", presType, allWeather.current) + " " + presType;
                currentHumidity.Text      = "Humidity " + allWeather.current.humidity + "%" + " " + getNeedProperty <CurrentWeather>("precip_", precipType, allWeather.current) + " " + precipType;
                currentTempFeelslike.Text = "Feelslike " + getNeedProperty <CurrentWeather>("feelslike_", tempType, allWeather.current) + "° " + tempType;
                currentVis.Text           = "Visibility " + getNeedProperty <CurrentWeather>("vis_", visType, allWeather.current) + " " + visType;

                conditionsString = weatherAPI.getConditions();
                conditions2      = new ObservableCollection <Condition>(JsonConvert.DeserializeObject <List <Condition> >(conditionsString));
                foreach (Condition cond in JsonConvert.DeserializeObject <List <Condition> >(conditionsString))
                {
                    conditionPicker.Items.Add(cond.night);
                }
                conditionPicker.SelectedItem = allWeather.current.condition.text;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }



            getFrequency();
            clouds = new List <Cloud>();
            width  = 1700;
            float x = width / frequency;

            for (float i = 0; i < frequency; i++)
            {
                var cl = new Cloud(x / 2 + i * x, cloudHeight * k + random(-1 * (cloudHeight * k) / 2, (cloudHeight * k) / 1.5f),
                                   (int)random(4, 12), cloudHeight, 0);
                clouds.Add(cl);
            }

            moveTimer.Interval = new TimeSpan(1);
            moveTimer.Tick    += MoveTimer_Tick;
            moveTimer.Start();
        }
Beispiel #60
0
 private void initClouds()
 {
     clouds[0] = new Cloud(40, 500);
     clouds[1] = new Cloud(300, 350);
     clouds[2] = new Cloud(600, 670);
 }