Inheritance: MonoBehaviour
Example #1
0
    void Awake()
    {
        var tempo = 130f;

        var notes = new List<Note>()
        {
            new Note(new Clock(tempo , 4 * 0 + 0), NoteNumber.C),
            new Note(new Clock(tempo , 4 * 0 + 1), NoteNumber.D),
            new Note(new Clock(tempo , 4 * 0 + 2), NoteNumber.E),
            new Note(new Clock(tempo , 4 * 0 + 3), NoteNumber.E),
            new Note(new Clock(tempo , 4 * 1 + 1), NoteNumber.D),
            new Note(new Clock(tempo , 4 * 1 + 2), NoteNumber.C),
        };

        var copybook = new Copybook(new Clock(tempo, 4 * 0), new Clock(tempo, 4 * 4), notes);
        var userplay = new UserPlay(new Clock(tempo, 4 * 4), copybook);

        var phases = new List<IPlayPhase>()
        {
            copybook,
            userplay,
        };

        Score = new Score(phases);
    }
Example #2
0
 public void ExportScore(Score score, Stream stream)
 {
     using (var writer = new BinaryWriter(stream, Encoding.GetEncoding(1252)))
     {
         ExportScore(score, writer);
     }
 }
Example #3
0
 private static Card UpdateCard(Card card, Score score)
 {
     card.LastTrainingDate = DateTime.UtcNow;
     card.Score = score;
     card.NumberOfRepetitions++;
     //If None - return interval
     if (score == Score.None)
     {
         return ResetCard(card);
     }
     //If first or second time - return interval
     if (card.NumberOfRepetitions == 1)
     {
         card.LastInterval = FirstInterval;
     }
     else if (card.NumberOfRepetitions == 2)
     {
         card.LastInterval = SecondInterval;
     }
     else
     {
         //Calculate new EF
         card.EFactor = CalculateNextEFactor(card.EFactor, score);
         //Calculate and return new interval
         card.LastInterval = CalculateNextInterval(card.LastInterval, card.EFactor);
     }
     card.NextDate = DateTime.UtcNow.Date.AddDays(card.LastInterval);
     return card;
 }
Example #4
0
 public EmptyLevel(Content content, Renderer renderer, Score score)
     : base(content, renderer, score)
 {
     for (int x = 0; x < rows; x++)
         for (int y = 0; y < columns; y++)
             bricks[x, y].Dispose();
 }
Example #5
0
 public void ExportScore(Score score, string fileName)
 {
     using (var file = File.Open(fileName, FileMode.Create))
     {
         ExportScore(score, file);
     }
 }
Example #6
0
 void Awake()
 {
     // Setting up the references.
     ren = transform.Find("body").GetComponent<SpriteRenderer>();
     frontCheck = transform.Find("frontCheck").transform;
     score = GameObject.Find("Score").GetComponent<Score>();
 }
Example #7
0
 private static double CalculateNextEFactor(double eFactor, Score score)
 {
     //EF':=EF+(0.1-(5-q)*(0.08+(5-q)*0.02))
     var q = (int)score;
     var newEF = eFactor + (0.1 - (5 - q) * (0.08 + (5 - q) * 0.02));
     return newEF < MinEF ? MinEF : newEF;
 }
 public Match(Team homeTeam, Team awayTeam, Score score, int id)
 {
     this.HomeTeam = homeTeam;
     this.AwayTeam = awayTeam;
     this.Score = score;
     this.Id = id;
 }
Example #9
0
 void Awake()
 {
     instanceCount++;
     if (instanceCount > 1)
         return;
     selfInstance = this;
 }
Example #10
0
 // Use this for initialization
 void OnEnable()
 {
     _Score = GameObject.FindGameObjectWithTag ("Score").GetComponent<Score> ();
     _text = gameObject.GetComponent<Text> ();
     //		gameObject.GetComponent<Canvas>().sortingLayerName = "Buttons";
     _text.text =  _Score._score.ToString() ;
 }
Example #11
0
 public void EndQuiz(Score score)
 {
     _scoreManager.AddScore(score);
     _menuStack.Pop();
     _menuStack.Push(new QuizResultsDisplay(this,_scoreManager.GetCumulativeQuizScore(), false));
     _systemMain.SetStack(_menuStack);
 }
Example #12
0
        private static void ReadFromFile()
        {
            try
            {
                StreamReader sr = new StreamReader("Content/Text Files/HighScores.txt");

                string input = sr.ReadLine();

                while (input != null)
                {
                    string[] data = input.Split(',');
                    Score s = new Score(data[0], int.Parse(data[1]));

                    HighscoreList.Add(s);

                    input = sr.ReadLine();
                }
                sr.Close();
                HighscoreList.Sort();
            }
            catch
            {
                //No Current Scores in File
                HighscoreList.Add(new Score("No scores to display", 0));
            }
        }
Example #13
0
 public void Darren()
 {
     Server.Stub(new ApiExpectation { Method = "POST", Url = "/gamma/scores", Request = "lid=mybaloney&username=Scytale&userkey=gom%20jabbar&points=10039&key=thekey&sig=ea56e70da9398d58eff2ec78d7d00605021dba12", Response = "{}" });
      var score = new Score { Points = 3, UserName = "******", Data = "Name"};
      new Driver("4ee6add2563d8a7d3200001d", "Fw>HPS^OXw1Kx=_SATiE@32[FUZ9lW@uO").SaveScore("4ee6b064563d8a7d32000038", score, "android-emulator", SetIfSuccess);
      WaitOne();
 }
Example #14
0
 // Use this for initialization
 void Start()
 {
     _wheel = GetComponent<WheelCollider>();
     //bikerhealth = transform.parent.Find( "bodyHealthTrigger" ).GetComponent<Health>();
     bikerhealth = transform.parent.GetComponentInChildren<Health>();
     bikerscore = transform.parent.GetComponent<Score>();
 }
Example #15
0
 public Match(Team home, Team away,int id,int homeTeamGoals, int awayTeamGoals)
 {
     this.homeTeam = home;
     this.awayTeam = away;
     this.score = new Score(homeTeamGoals,awayTeamGoals);
     this.id = id;
 }
Example #16
0
 public static void Initialize()
 {
     // Set up the game
     player = new Player();
     score = new Score();
     junctionManager = new JunctionManager();
 }
Example #17
0
		//create a crazy world...
		public static World GenerateCustomWorld(){
			World mainWorld = new World("main_world");

			Score s = new Score("numberScore");
			World machineA = new World("machine_a");
			World machineB = new World("machine_b");

			// machine A
			machineA.BatchAddLevelsWithTemplates(2, null, s, null);

			// machine B

			Gate machineALevel1Complete = new WorldCompletionGate("level1_complete", machineA.GetInnerWorldAt(0).ID);

			machineB.BatchAddLevelsWithTemplates(20, machineALevel1Complete, s, null);

			Mission mission1 = new WorldCompletionMission("level2_complete", "Level 2 Completed Mission!", machineA.GetInnerWorldAt(1).ID);
			Mission mission2 = new RecordMission("level1_record_mission", "Level 1 Record Mission!", machineA.GetInnerWorldAt(0).GetSingleScore().ID, 20.0);
			Mission allMissions = new Challenge("main_challange", "MAIN CHALLENGE", new List<Mission>() { mission1, mission2 });

			machineB.GetInnerWorldAt(5).AddMission(allMissions);

			mainWorld.AddInnerWorld(machineA);
			mainWorld.AddInnerWorld(machineB);

			return mainWorld;
		}
Example #18
0
 void Start()
 {
     S = this;
     this.uiScore = GetComponentInParent<UnityEngine.UI.Text>();
     score = PlayerPrefs.GetInt("LevelScore");
     this.DisplayScore();
 }
Example #19
0
 void Start()
 {
     isAlive = true;
     score = GameObject.FindGameObjectWithTag ("Score").GetComponent<Score> ();
     gameplayControls = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameplayControls>();
     soundControls = GameObject.FindGameObjectWithTag("SoundsController").GetComponent<SoundControls>();
 }
Example #20
0
	public void AddScore (int level, int value)
	{
		Score s = new Score ();
		s.Level = level;
		s.Value = value;
		scores.Add (s);
	}
Example #21
0
 void Awake()
 {
     Application.targetFrameRate = 60;
     player = GameObject.Find("Player").GetComponent<Player>();
     spawner = GameObject.Find("Spawner").GetComponent<Spawner>();
     Score = Hud.GetComponent<Score>();
 }
Example #22
0
    public void RunEnd(string cuseOfDeath)
    {
        Score newScore = new Score(gameController.seed, score);
        scoreData.lastRun = newScore;

        if (scoreData.scores.Count == 0)
        {
            scoreData.scores.Add(newScore);
        }
        else
        {
            bool inserted = false;
            for (int i = 0; i < scoreData.scores.Count; ++i)
            {
                if (newScore.score >= scoreData.scores[i].score)
                {
                    scoreData.scores.Insert(i, newScore);
                    inserted = true;
                    break;
                }
            }
            if (!inserted)
            {
                scoreData.scores.Add(newScore);
            }

            if (scoreData.scores.Count > 10)
            {
                scoreData.scores.RemoveAt(10);
            }
        }
        SaveScores();
    }
Example #23
0
        public ScoreHUD(PlayerManager playerManager)
        {
            this.playerManager = playerManager;

            myScore = new Score();
            players = new List<Player>(ProtocolInformation.DummySlot);
        }
        public void ToStringShouldReturnString()
        {
            var score = new Score(this.playerName, this.points, this.time);
            var result = score.ToString();

            Assert.IsInstanceOfType(result, typeof(string));
        }
	void Awake () {
		select_subscription = selected_scores.Subscribe((s)=>{
			if (s != null){
				if (date_time != null)
					date_time.text = s.time.date_recorded_local().ToString();
				//Yeah, it's ugly abuse of static variables, but I'll fix it later.
				score = s;
				MenuStateMachine.fsm.trigger_transition("scores->details");
			}
		});
		
		rx_player_name = rx_score.SelectMany(s=>{
			if (s == null)
				return Observable.Never<String>();
			return s.rx_player_name.AsObservable();
		}).CombineLatest(LanguageController.controller.rx_load_text("score_default_name"), (name, default_name)=>{
			if (IsNullOrWhiteSpace(name))
				return default_name;
			return name;
		}).ToReadOnlyReactiveProperty<string>();
		
		rx_player_name.Subscribe(t=>{
			if (player_name != null)
				player_name.text = t;
		});
	}
//--------------------------------------------------------------------------------------------

	public void handleLevelCompleted(SceneIndex level)
	{
		isLevelComplete = true;

		//get the saved game manager
		gameManager = GameObject.Find("SavedGameManager").GetComponent<SavedGameManager>();
		if(gameManager == null)
		{
			return;
		}

		//save whether or not the final chassis was used
		didUseFinalChassis = gameManager.getCurrentGame().getCurrentLoadout().getChasis() == Loadout.LoadoutChasis.FINAL;

		//save the score, and if there were no hits (if player not hit, bonus added to final score)
		score = GameObject.Find("Score").GetComponent<Score>();
		finalScore = score.wasPlayerHit ? 
			score.trueScore : 
			score.trueScore + (int)PointVals.NO_HITS;

		//save score and get the old high scores
		oldPersonalHighScore = gameManager.getCurrentGame().highScores[(int)level - 3];
		oldGlobalHighScore = gameManager.globalHighScores[(int)level - 3];

		//save game
		gameManager.handleLevelCompleted(level, finalScore, didUseFinalChassis);

		//now we can activate the panel and run its animations
		gameObject.SetActive(true);
		StartCoroutine(handlePanelAnimations());

		//activate the button
		button.Select();
	}
Example #27
0
 private void Start()
 {
     blockspawner = GameObject.Find ("Blockspawner").GetComponent<Blockspawner>();
     thisButton = GetComponent<Button> ();
     score = GameObject.Find ("Main Camera").GetComponent<Score> ();
     audioSource = GetComponent<AudioSource> ();
 }
Example #28
0
        public void Update()
        {
            if (!isActive)
                return;

            // first update the local player's score
            myScore = playerManager.LocalPlayer.Score;            

            ks = Keyboard.GetState();
            if (ks.IsKeyDown(Keys.Tab) && oldKs.IsKeyUp(Keys.Tab))
            {
                isOpen = !isOpen;
            }
            oldKs = ks;

            // only load and sort data if we must
            if (isOpen)
            {
                // step 1: get the players from player manager
                players.Clear(); // first clear it out

                // add all remote players
                players.AddRange(playerManager.RemotePlayers.Cast<Player>());

                // add local player, if we can
                if (playerManager.LocalPlayer != null)
                    players.Add(playerManager.LocalPlayer);

                // step 2: sort players in descending order
                // first by wins, then by overall score
                players = players.OrderByDescending(p => p.Score.Wins).ThenByDescending(p => p.Score.Overall).ToList();
            }
        }
Example #29
0
    // Use this for initialization
    void Start()
    {
        currentScore = GameObject.Find("CurrentScore").GetComponent<CurrentScore>();
        fullScore = GameObject.FindObjectOfType<FullScore>();
        score = GetComponent<Score>();
        energy = GetComponent<Energy>();
        energyLine = GameObject.FindObjectOfType<EnergyLine>();
        inputController = GameObject.FindObjectOfType<InputController>();
        timerScript = GameObject.FindObjectOfType<TimerScript>();
        timerUI = GameObject.FindObjectOfType<TimerUI>();
        info = GetComponent<Info>();
        taskStrings = GetComponent<TaskStrings>();
        pauseButton = GameObject.FindObjectOfType<PauseButton>().gameObject;
        pauseMenu = GameObject.Find("Canvas").GetComponentInChildren<PauseMenu>();
          //  endMenu = GameObject.FindObjectOfType<EndMenu>();
        taskHelper = GameObject.FindObjectOfType<TaskHelper>();
        globalController = GetComponent<GlobalController>();
        cam = GameObject.Find("MainCamera");
        secondCamera = GameObject.Find("SecondCamera");
        wordRideCanvas = GameObject.FindObjectOfType<WordRideCanvas>();

        metalSparksPrefab = Resources.Load("Prefabs/Particles/MetalSpark") as GameObject;
        carUserParametres = GetComponent<CarUserParametres>();
        gameUI = GameObject.FindObjectOfType<GameUI>();
        canvasController = GameObject.FindObjectOfType<CanvasController>();

        particleCanvas = GameObject.Find("ParticleCanvas");
        carCreator = GameObject.FindObjectOfType<CarCreator>();

        mainBonus = GameObject.FindObjectOfType<MainBonus>();

        waitBackground = GameObject.FindObjectOfType<WaitBackground>();
    }
Example #30
0
 // Use this for initialization
 void Awake()
 {
     killCombo = GetComponent<KillCombo>();
     score = GetComponent<Score>();
     deathBlowGauge = GetComponent<DeathBlowGauge>();
     lifes2D = GetComponent<Lifes2D>();
 }
Example #31
0
        public Level5()
        {
            Console.WriteLine("Level5");
            Reset();
            timebarSpace = 10.768F;
            this.Add(new SpriteGameObject("spr_background"));
            thePlayer = new Player(25, 4);
            door      = new Door(24, 0);
            xaxis     = new Xaxis(9, "Map/spr_horizontal_art_blue");
            yaxis     = new Yaxis(12, "Map/spr_vertical_art_blue");
            goal      = new MainGoal(9, 13);

            Mouse.SetPosition(GameEnvironment.Screen.X / 2, GameEnvironment.Screen.Y / 2);

            floors = new GameObjectList();
            walls  = new GameObjectList();
            goals  = new GameObjectList();

            inputScreen = new InputScreen(GameEnvironment.Screen.X / 2 - 64 * 2, GameEnvironment.Screen.Y);
            inputanswer = new InputAnswer(GameEnvironment.Screen.X / 2 - 64 * 2, GameEnvironment.Screen.Y);
            timeGround  = new SpriteGameObject("Map/time_ground");

            guards       = new GameObjectList();
            lasers       = new GameObjectList();
            times        = new GameObjectList();
            score        = new Score(12, 20, (int)time);
            Axis_nums    = new Axis_numbers(12, 9);
            switchBoards = new GameObjectList();

            this.Add(floors);
            this.Add(switchBoards);
            this.Add(lasers);
            this.Add(walls);
            this.Add(door);
            this.Add(xaxis);
            this.Add(yaxis);
            this.Add(Axis_nums);
            this.Add(goal);
            this.Add(goals);
            this.Add(guards);
            this.Add(thePlayer);
            this.Add(inputScreen);
            this.Add(timeGround);
            this.Add(times);
            this.Add(score);
            this.Add(inputanswer);

            goals.Add(new ExtraGoal(14, 13));
            goals.Add(new ExtraGoal(19, 7));
            guards.Add(new Guard(new Vector2(2, 2), new Vector2(25, 2)));
            guards.Add(new Guard(new Vector2(3, 3), new Vector2(1, 13)));
            guards.Add(new Guard(new Vector2(26, 5), new Vector2(23, 15)));
            guards.Add(new Guard(new Vector2(21, 8), new Vector2(2, 6)));
            FloorSetup();
            WallSetup();
            TimeBarSetup();
            SoundSetup();
            lasers.Add(new Laser(new Vector2(1, 6), new Vector2(4, 8), Color.Red, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(13, 13), new Vector2(16, 10), Color.Blue, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(21, 11), new Vector2(24, 15), Color.Yellow, xaxis.gridPos, yaxis.gridPos));
            lasers.Add(new Laser(new Vector2(23, 10), new Vector2(28, 9), Color.Purple, xaxis.gridPos, yaxis.gridPos));
            switchBoards.Add(new SwitchBoard(13, 4, Color.Red));
            switchBoards.Add(new SwitchBoard(4, 9, Color.Blue));
            switchBoards.Add(new SwitchBoard(12, 11, Color.Yellow));
            switchBoards.Add(new SwitchBoard(17, 11, Color.Purple));
        }
Example #32
0
 public void CheckIfClassCalculateCorrectlyCounterPositive()
 {
     score = new Score("2:C", 8, true, false, "NS", "WE");
     Assert.AreEqual(180, score.GetScore());
 }
Example #33
0
 public void CheckIfClassCalculateCorrectlyOvertricks()
 {
     score = new Score("2:C", 9, false, false, "NS", "WE");
     Assert.AreEqual(110, score.GetScore());
 }
Example #34
0
 public void CheckIfClassChecksCorrectlyIfContractIsPassed()
 {
     score = new Score("2:C", 10, false, false, "NS", "WE");
     Assert.Positive(score.GetScore());
 }
 // Use this for initialization
 void Start()
 {
     Score.CalculateLoss();
     total.text      = "Score: " + Score.score.ToString();
     components.text = "Victories Bonus: " + Score.victories.ToString() + " * 10\nDungeon Bonus: " + Score.clears.ToString() + " * 50";
 }
Example #36
0
        public static int ScoreCountingCardsPlayed(List <Card> playedCards, Card card, int currentCount,
                                                   out List <Score> scoreList)
        {
            scoreList = new List <Score>();
            if (playedCards == null)
            {
                return(0);
            }

            if (card.Value + currentCount > 31)
            {
                return(-1);
            }

            int score = 0;

            currentCount += card.Value;
            //
            //  hit 15?
            if (currentCount == 15)
            {
                Score scr = new Score(ScoreName.Fifteen, 2, playedCards);
                scoreList.Add(scr);
                score += 2;
            }

            // hit 31?
            if (currentCount == 31)
            {
                scoreList.Add(new Score(ScoreName.ThirtyOne, 2, playedCards));
                score += 2;
            }

            List <Card> allCards = new List <Card>(playedCards)
            {
                card
            };


            //
            //   search for 2, 3, or 4 of a kind -- this has to happen before the sort!
            List <Card> tempList      = new List <Card>();
            int         samenessCount = 0;

            for (int i = allCards.Count - 1; i > 0; i--)
            {
                if (allCards[i].Rank == allCards[i - 1].Rank)
                {
                    if (!tempList.Contains(allCards[i]))
                    {
                        tempList.Add(allCards[i]);
                    }

                    if (!tempList.Contains(allCards[i - 1]))
                    {
                        tempList.Add(allCards[i - 1]);
                    }

                    samenessCount++;
                }
                else
                {
                    break;
                }
            }

            switch (samenessCount)
            {
            case 1:     // pair
                scoreList.Add(new Score(ScoreName.Pair, 2, tempList));
                score += 2;
                break;

            case 2:     // 3 of a kind
                scoreList.Add(new Score(ScoreName.ThreeOfaKind, 6, tempList));
                score += 6;
                break;

            case 3:     // 4 of a kind
                scoreList.Add(new Score(ScoreName.FourOfAKind, 12, tempList));
                score += 12;
                break;

            default:
                break;
            }

            // search for runs
            (int score, List <Card> cards)runs = ScoreCountedRun(allCards);

            if (runs.score > 0)
            {
                scoreList.Add(new Score(ScoreName.CountedRun, runs.score, runs.cards));
                score += runs.score;
            }

            return(score);
        }
Example #37
0
 public ScoreAccessibleReplayPlayer(Score score)
     : base(score, false, false)
 {
 }
Example #38
0
 // Use this for initialization
 void Start()
 {
     Score_score = GameObject.Find("System").GetComponent <Score> ();
 }
Example #39
0
 public ExamScoringSagaScoreReceived(Score score)
 {
     Score = score;
 }
Example #40
0
        public List <int> GetFrameTotals()
        {
            int tmpValue   = 0;
            int totalValue = 0;

            FrameTotals.Clear();
            foreach (Score s in scores)
            {
                if (s.scoreType != Score.ScoreType.Skip)
                {
                    if (s.frameType == Score.FrameType.First && !s.InLastFrame)
                    {
                        tmpValue += s.Value;
                        if (s.scoreType == Score.ScoreType.Strike)
                        {
                            int currentId = scores.IndexOf(s);
                            if (scores.Count > currentId + 2)
                            {
                                Score nextScore = scores[currentId + 2];


                                tmpValue += nextScore.Value;

                                if (nextScore.scoreType == Score.ScoreType.Strike)
                                {
                                    if (scores.Count > currentId + 4)
                                    {
                                        Score next2Scores = scores[currentId + 4];

                                        tmpValue += next2Scores.Value;
                                    }
                                }
                                else if (nextScore.scoreType != Score.ScoreType.Strike)
                                {
                                    if (scores.Count > currentId + 3)
                                    {
                                        Score next2Scores = scores[currentId + 3];

                                        tmpValue += next2Scores.Value;
                                    }
                                }
                            }

                            totalValue += tmpValue;
                            FrameTotals.Add(totalValue);
                            tmpValue = 0;
                        }
                    }
                    else if (s.frameType == Score.FrameType.Second && !s.InLastFrame)
                    {
                        tmpValue += s.Value;
                        if (s.scoreType == Score.ScoreType.Spare)
                        {
                            int currentID = scores.IndexOf(s);

                            if (scores.Count > currentID + 1)
                            {
                                tmpValue += scores[currentID + 1].Value;
                            }
                        }
                        totalValue += tmpValue;

                        FrameTotals.Add(totalValue);
                        tmpValue = 0;
                    }
                    else if (s.InLastFrame)
                    {
                        if (s.frameType == Score.FrameType.First)
                        {
                            tmpValue += s.Value;
                        }
                        else if (s.frameType == Score.FrameType.Second)
                        {
                            tmpValue += s.Value;

                            if (tmpValue >= 10)
                            {
                                ExtraBallAwarded = true;
                            }
                            else
                            {
                                totalValue += tmpValue;
                                FrameTotals.Add(totalValue);
                                tmpValue = 0;
                            }
                        }
                        else if (s.frameType == Score.FrameType.Extra)
                        {
                            tmpValue   += s.Value;
                            totalValue += tmpValue;
                            FrameTotals.Add(totalValue);
                            tmpValue = 0;
                        }
                    }
                }
            }

            return(FrameTotals);
        }
Example #41
0
 // Use this for initialization
 void Start()
 {
     scoreObject = GameObject.Find("ScoreObject");
     score       = scoreObject.GetComponent <Score>();
     mainCamera  = GameObject.Find("Main Camera");
 }
Example #42
0
 void Initialize(Score score)
 {
     this.score = score;
 }
Example #43
0
        /// <summary>
        /// Handler for posting a score.
        /// </summary>
        /// <returns>The posted score.</returns>
        public async Task <IActionResult> OnPostPostScoreAsync([FromForm(Name = "id_token")] string idToken, string lineItemUrl)
        {
            if (idToken.IsMissing())
            {
                Error = $"{nameof(idToken)} is missing.";
                return(Page());
            }

            if (lineItemUrl.IsMissing())
            {
                Error = $"{nameof(lineItemUrl)} is missing.";
                return(Page());
            }

            var handler = new JwtSecurityTokenHandler();
            var jwt     = handler.ReadJwtToken(idToken);

            LtiRequest = new LtiResourceLinkRequest(jwt.Payload);

            var tokenResponse = await _accessTokenService.GetAccessTokenAsync(
                LtiRequest.Iss,
                Constants.LtiScopes.Ags.Score);

            // The IMS reference implementation returns "Created" with success.
            if (tokenResponse.IsError && tokenResponse.Error != "Created")
            {
                Error = tokenResponse.Error;
                return(Page());
            }

            var httpClient = _httpClientFactory.CreateClient();

            httpClient.SetBearerToken(tokenResponse.AccessToken);
            httpClient.DefaultRequestHeaders.Accept
            .Add(new MediaTypeWithQualityHeaderValue(Constants.MediaTypes.Score));

            try
            {
                var score = new Score
                {
                    ActivityProgress = ActivityProgress.Completed,
                    GradingProgress  = GradingProgess.FullyGraded,
                    ScoreGiven       = new Random().NextDouble() * 100,
                    ScoreMaximum     = 100,
                    TimeStamp        = DateTime.UtcNow,
                    UserId           = LtiRequest.UserId
                };
                if (score.ScoreGiven > 75)
                {
                    score.Comment = "Good job!";
                }

                using (var response = await httpClient.PostAsync(
                           lineItemUrl.EnsureTrailingSlash() + "scores",
                           new StringContent(JsonConvert.SerializeObject(score), Encoding.UTF8, Constants.MediaTypes.Score)))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        Error = response.ReasonPhrase;
                        return(Page());
                    }
                }
            }
            catch (Exception e)
            {
                Error = e.Message;
                return(Page());
            }

            return(Relaunch(
                       LtiRequest.Iss,
                       LtiRequest.UserId,
                       LtiRequest.ResourceLink.Id,
                       LtiRequest.Context.Id));
        }
Example #44
0
 // Awake is called before the first frame update & Start()
 void Awake()
 {
     scoreScript   = FindObjectOfType <Score>();
     managerScript = FindObjectOfType <GameManager>();
     startCanvas.SetActive(true);
 }
Example #45
0
        public override void RenderWinner(IGraphics g, TournamentNameTable names, float x, float y, float textHeight, Score score)
        {
            string teamName = "";

            if (this.IsDecided)
            {
                var winner = this.GetWinner();
                if (winner != null)
                {
                    teamName = names[winner.TeamId];
                }
                else
                {
                    teamName = "bye";
                }
            }

            this.RenderTextBox(g, x, y, textHeight, teamName, score);
        }
Example #46
0
 /// <summary>
 /// Invokes the Score event
 /// </summary>
 /// <param name="score"></param>
 /// <param name="lines"></param>
 /// <param name="level"></param>
 protected virtual void OnScore(int score, int lines, Level level)
 {
     Score?.Invoke(this, new ScoreEventArgs(score, lines, Level));
 }
Example #47
0
        public override NodeMeasurement MeasureWinner(IGraphics g, TournamentNameTable names, float textHeight, Score score)
        {
            string teamName = "";

            if (this.IsDecided)
            {
                var winner = this.GetWinner();
                if (winner != null)
                {
                    teamName = names[winner.TeamId];
                }
                else
                {
                    teamName = "bye";
                }
            }

            return(this.MeasureTextBox(g, textHeight, teamName, score));
        }
Example #48
0
 // Increases score by one
 public void IncreaseScore()
 {
     Score++;
     UI.Score_Text.text = Score.ToString();
 }
 public void Init()
 {
     // 알맞은 게임 얻기 및 스코어 초기화 등 게임 데이터 초기화
     _songObjectManager.Init();
     Score.Init();
 }
Example #50
0
 public override NodeMeasurement MeasureLoser(IGraphics g, TournamentNameTable names, float textHeight, Score score)
 {
     throw new InvalidOperationException("Cannot determine a loser from a pass through.");
 }
 public override string GetStatusReadout()
 {
     return(Score.ToString() + " / " + MaxScore);
 }
 public bool IsGameEnd()
 {
     // 게임 끝났는지 확인하는 함수
     return(Score.IsPlayerDie() || _songObjectManager.IsSongEnd);
 }
Example #53
0
        public void StartRescue(IHubContext context, PlayerSetup.Player player, Room room, string target = "")
        {
            //Check if player has spell
            var hasSkill = Skill.CheckPlayerHasSkill(player, RescueAb().Name);

            if (hasSkill == false)
            {
                context.SendToClient("You don't know that skill.", player.HubGuid);
                return;
            }

            var canDoSkill = Skill.CanDoSkill(player);

            if (!canDoSkill)
            {
                return;
            }

            if (string.IsNullOrEmpty(target))
            {
                context.SendToClient("Rescue whom?.", player.HubGuid);
                return;
            }

            var _target = Skill.FindTarget(target, room);

            //Fix issue if target has similar name to user and they use abbrivations to target them
            if (_target == player)
            {
                context.SendToClient("Try fleeing instead.", player.HubGuid);
                player.ActiveSkill = null;
                return;
            }

            if (player.ActiveSkill != null)
            {
                context.SendToClient("wait till you have finished " + player.ActiveSkill.Name, player.HubGuid);
                return;
            }
            else
            {
                player.ActiveSkill = RescueAb();
            }



            if (_target != null)
            {
                if (_target.HitPoints <= 0)
                {
                    context.SendToClient("You can't rescue them as they are dead.", player.HubGuid);
                    player.ActiveSkill = null;
                    return;
                }

                if (player.MovePoints < RescueAb().MovesCost)
                {
                    context.SendToClient("You are too tired to use Rescue.", player.HubGuid);
                    player.ActiveSkill = null;
                    return;
                }

                if (_target.Target == null)
                {
                    context.SendToClient("They are not fighting.", player.HubGuid);
                    player.ActiveSkill = null;
                    return;
                }


                player.MovePoints -= RescueAb().MovesCost;

                Score.UpdateUiPrompt(player);


                var chanceOfSuccess = Helpers.Rand(1, 100);
                var skill           = player.Skills.FirstOrDefault(x => x.Name.Equals("Rescue"));
                if (skill == null)
                {
                    player.ActiveSkill = null;
                    return;
                }

                var skillProf = skill.Proficiency;

                if (skillProf >= chanceOfSuccess)
                {
                    Task.Run(() => DoRescue(context, player, _target, room));
                }
                else
                {
                    player.ActiveSkill = null;
                    PlayerSetup.Player.LearnFromMistake(player, RescueAb(), 250);



                    Score.ReturnScoreUI(player);
                }
            }
            else if (_target == null)
            {
                context.SendToClient($"You can't find anything known as '{target}' here.", player.HubGuid);
                player.ActiveSkill = null;
            }
        }
Example #54
0
 private void Start()
 {
     score = FindObjectOfType <Score>();
 }
Example #55
0
        public Image Convert()
        {
            var   sigs           = Score.TimeSignatures.OrderBy(p => p.Key).ToList();
            int   lanesCount     = Ched.Core.Constants.LanesCount;
            int   columnTick     = MeasurementProfile.CalcColumnTickFromTicksPerBeat(Score.TicksPerBeat);
            int   paddingTick    = MeasurementProfile.CalcPaddingTickFromTicksPerBeat(Score.TicksPerBeat);
            float laneWidth      = MeasurementProfile.UnitLaneWidth + MeasurementProfile.BorderThickness;
            float wholeLaneWidth = laneWidth * lanesCount;
            float columnHeight   = columnTick * MeasurementProfile.UnitBeatHeight / Score.TicksPerBeat;
            float paddingHeight  = paddingTick * MeasurementProfile.UnitBeatHeight / Score.TicksPerBeat;
            int   headTick       = 0;

            var bmp                   = new Bitmap((int)(MeasurementProfile.PaddingWidth * 2 + wholeLaneWidth) * (int)Math.Ceiling((double)Score.GetLastTick() / columnTick), (int)(paddingHeight * 2 + columnHeight));
            var longEndsPos           = new HashSet <NotePosition>(Score.LongNotes['2'].Concat(Score.LongNotes['3']).Select(p => p.Last().Position));
            var unUsedShortNoteQueues = Score.ShortNotes.ToDictionary(p => p.Key, p =>
            {
                var q = new ConcurrentPriorityQueue <NoteDefinition, int>();
                foreach (var item in p.Value)
                {
                    q.Enqueue(item, -item.Position.Tick);
                }
                return(q);
            });
            var usingShortNoteQueues = Score.ShortNotes.ToDictionary(p => p.Key, p => new ConcurrentPriorityQueue <NoteDefinition, int>());
            var unUsedLongNoteQueues = Score.LongNotes.ToDictionary(p => p.Key, p =>
            {
                var q = new ConcurrentPriorityQueue <List <NoteDefinition>, int>();
                foreach (var item in p.Value)
                {
                    q.Enqueue(item, -item[0].Position.Tick);
                }
                return(q);
            });
            var usingLongNoteQueues = Score.LongNotes.ToDictionary(p => p.Key, p => new ConcurrentPriorityQueue <List <NoteDefinition>, int>());
            var emptyLong           = Enumerable.Empty <List <NoteDefinition> >();

            bool visibleStep(NoteDefinition p) => p.Type == '1' || p.Type == '2' || p.Type == '3';
            void moveToOrigin(Graphics g) => g.TranslateTransform(MeasurementProfile.PaddingWidth, paddingHeight + columnHeight - 1, MatrixOrder.Append);
            void moveToColumn(Graphics g, int columnsCount) => g.TranslateTransform((MeasurementProfile.PaddingWidth * 2 + wholeLaneWidth) * columnsCount, 0, MatrixOrder.Append);
            void moveToHead(Graphics g, int head) => g.TranslateTransform(0, head * MeasurementProfile.UnitBeatHeight / TicksPerBeat, MatrixOrder.Append);

            using (var g = Graphics.FromImage(bmp))
            {
                int   columnsCount = 0;
                SizeF strSize      = g.MeasureString("000", MeasurementProfile.Font);
                var   dc           = new DrawingContext(g, NoteColorProfile);
                g.Clear(BackgroundColorProfile.BackgroundColor);

                while (unUsedShortNoteQueues.Any(p => p.Value.Count > 0) || usingShortNoteQueues.Any(p => p.Value.Count > 0) || usingLongNoteQueues.Any(p => p.Value.Count > 0) || unUsedLongNoteQueues.Any(p => p.Value.Count > 0))
                {
                    int tailTick = headTick + columnTick;

                    // 範囲外に出たノーツの更新
                    foreach (var type in usingShortNoteQueues)
                    {
                        while (type.Value.Count > 0 && type.Value.Peek().Position.Tick < headTick - paddingTick)
                        {
                            type.Value.Dequeue();
                        }
                    }

                    foreach (var type in usingLongNoteQueues)
                    {
                        while (type.Value.Count > 0 && type.Value.Peek()[type.Value.Peek().Count - 1].Position.Tick < headTick - paddingTick)
                        {
                            type.Value.Dequeue();
                        }
                    }

                    // 範囲内に入るノーツの更新
                    foreach (var type in unUsedShortNoteQueues)
                    {
                        while (type.Value.Count > 0 && type.Value.Peek().Position.Tick < tailTick + paddingTick)
                        {
                            var item = type.Value.Dequeue();
                            usingShortNoteQueues[type.Key].Enqueue(item, -item.Position.Tick);
                        }
                    }

                    foreach (var type in unUsedLongNoteQueues)
                    {
                        while (type.Value.Count > 0 && type.Value.Peek()[0].Position.Tick < tailTick + paddingTick)
                        {
                            var item = type.Value.Dequeue();
                            usingLongNoteQueues[type.Key].Enqueue(item, -item[item.Count - 1].Position.Tick);
                        }
                    }

                    g.ResetTransform();
                    g.ScaleTransform(1, -1);
                    moveToOrigin(g);
                    moveToHead(g, headTick);
                    moveToColumn(g, columnsCount);

                    // レーン分割線描画
                    using (var pen = new Pen(BackgroundColorProfile.LaneBorderColor, MeasurementProfile.BorderThickness))
                    {
                        for (int i = 0; i <= lanesCount; i++)
                        {
                            if (i % 2 != 0)
                            {
                                continue;
                            }
                            float x = i * laneWidth;
                            g.DrawLine(pen, x, GetYPositionFromTick(headTick - paddingTick), x, GetYPositionFromTick(tailTick + paddingTick));
                        }
                    }

                    // 時間ガイドの描画
                    // そのイベントが含まれる小節(ただし[小節開始Tick, 小節開始Tick + 小節Tick)の範囲)からその拍子を適用

                    using (var beatPen = new Pen(BackgroundColorProfile.BeatLineColor, MeasurementProfile.BorderThickness))
                        using (var barPen = new Pen(BackgroundColorProfile.BarLineColor, MeasurementProfile.BorderThickness))
                        {
                            int headPos = 0;
                            int pos     = 0;
                            for (int j = 0; j < sigs.Count; j++)
                            {
                                int barTick  = (int)(TicksPerBeat * sigs[j].Value);
                                int beatTick = Math.Min(TicksPerBeat, barTick);

                                while (pos <= tailTick)
                                {
                                    if (j < sigs.Count - 1 && pos - headPos >= (sigs[j + 1].Key - headPos) / barTick * barTick)
                                    {
                                        break;
                                    }
                                    float y = GetYPositionFromTick(pos);
                                    g.DrawLine((pos - headPos) % barTick == 0 ? barPen : beatPen, 0, y, wholeLaneWidth, y);
                                    pos += beatTick;
                                }
                                headPos = pos;
                            }
                        }


                    // ノーツ描画
                    foreach (var hold in usingLongNoteQueues.ContainsKey('2') ? usingLongNoteQueues['2'] : emptyLong)
                    {
                        dc.DrawHoldBackground(new RectangleF(
                                                  (MeasurementProfile.UnitLaneWidth + MeasurementProfile.BorderThickness) * hold[0].Position.LaneIndex + MeasurementProfile.BorderThickness,
                                                  GetYPositionFromTick(hold[0].Position.Tick),
                                                  (MeasurementProfile.UnitLaneWidth + MeasurementProfile.BorderThickness) * hold[0].Position.Width - MeasurementProfile.BorderThickness,
                                                  GetYPositionFromTick(hold[1].Position.Tick - hold[0].Position.Tick)
                                                  ));
                    }

                    foreach (var slide in usingLongNoteQueues.ContainsKey('3') ? usingLongNoteQueues['3'] : emptyLong)
                    {
                        var visibleSteps = slide.Where(visibleStep).ToList();
                        for (int i = 0; i < slide.Count - 1; i++)
                        {
                            dc.DrawSlideBackground(
                                laneWidth * slide[i].Position.Width - MeasurementProfile.BorderThickness,
                                laneWidth * slide[i + 1].Position.Width - MeasurementProfile.BorderThickness,
                                laneWidth * slide[i].Position.LaneIndex,
                                GetYPositionFromTick(slide[i].Position.Tick),
                                laneWidth * slide[i + 1].Position.LaneIndex,
                                GetYPositionFromTick(slide[i + 1].Position.Tick) + 0.4f,
                                GetYPositionFromTick(visibleSteps.Last(p => p.Position.Tick <= slide[i].Position.Tick).Position.Tick),
                                GetYPositionFromTick(visibleSteps.First(p => p.Position.Tick >= slide[i + 1].Position.Tick).Position.Tick),
                                MeasurementProfile.ShortNoteHeight);
                        }
                    }

                    foreach (var airAction in usingLongNoteQueues.ContainsKey('4') ? usingLongNoteQueues['4'] : emptyLong)
                    {
                        dc.DrawAirHoldLine(
                            laneWidth * (airAction[0].Position.LaneIndex + airAction[0].Position.Width / 2f),
                            GetYPositionFromTick(airAction[0].Position.Tick),
                            GetYPositionFromTick(airAction[airAction.Count - 1].Position.Tick),
                            MeasurementProfile.ShortNoteHeight);
                    }

                    foreach (var hold in usingLongNoteQueues.ContainsKey('2') ? usingLongNoteQueues['2'] : emptyLong)
                    {
                        dc.DrawHoldBegin(GetRectFromNotePosition(hold[0].Position));
                        dc.DrawHoldEnd(GetRectFromNotePosition(hold[hold.Count - 1].Position));
                    }

                    foreach (var slide in usingLongNoteQueues.ContainsKey('3') ? usingLongNoteQueues['3'] : emptyLong)
                    {
                        dc.DrawSlideBegin(GetRectFromNotePosition(slide[0].Position));
                        foreach (var item in slide.Where(visibleStep).Skip(1))
                        {
                            if (item.Position.Tick < headTick - paddingTick)
                            {
                                continue;
                            }
                            if (item.Position.Tick > tailTick + paddingTick)
                            {
                                break;
                            }
                            dc.DrawSlideStep(GetRectFromNotePosition(item.Position));
                        }
                    }

                    // ロング終点AIR
                    var airs = usingShortNoteQueues.ContainsKey('5') ? usingShortNoteQueues['5'] : Enumerable.Empty <NoteDefinition>();
                    foreach (var air in airs)
                    {
                        if (!longEndsPos.Contains(air.Position))
                        {
                            continue;
                        }
                        dc.DrawAirStep(GetRectFromNotePosition(air.Position));
                    }

                    var shortNotesDic = usingShortNoteQueues['1'].GroupBy(p => p.Type).ToDictionary(p => p.Key, p => p.Select(q => q.Position));
                    void drawNotes(char key, Action <NotePosition> drawer)
                    {
                        if (!shortNotesDic.ContainsKey(key))
                        {
                            return;
                        }
                        foreach (var item in shortNotesDic[key])
                        {
                            drawer(item);
                        }
                    }

                    drawNotes('1', item => dc.DrawTap(GetRectFromNotePosition(item)));
                    drawNotes('2', item => dc.DrawExTap(GetRectFromNotePosition(item)));
                    drawNotes('5', item => dc.DrawExTap(GetRectFromNotePosition(item)));
                    drawNotes('6', item => dc.DrawExTap(GetRectFromNotePosition(item)));
                    drawNotes('3', item => dc.DrawFlick(GetRectFromNotePosition(item)));
                    drawNotes('4', item => dc.DrawDamage(GetRectFromNotePosition(item)));

                    foreach (var airAction in usingLongNoteQueues.ContainsKey('4') ? usingLongNoteQueues['4'] : emptyLong)
                    {
                        foreach (var item in airAction.Skip(1))
                        {
                            if (item.Position.Tick < headTick - paddingTick)
                            {
                                continue;
                            }
                            if (item.Position.Tick > tailTick + paddingTick)
                            {
                                break;
                            }
                            dc.DrawAirAction(GetRectFromNotePosition(item.Position).Expand(-MeasurementProfile.ShortNoteHeight * 0.28f));
                        }
                    }

                    foreach (var air in airs)
                    {
                        var vd = air.Type == '2' || air.Type == '5' || air.Type == '6' ? VerticalAirDirection.Down : VerticalAirDirection.Up;
                        var hd = air.Type == '1' || air.Type == '2' || air.Type == '7' ? HorizontalAirDirection.Center :
                                 (air.Type == '3' || air.Type == '5' || air.Type == '8' ? HorizontalAirDirection.Left : HorizontalAirDirection.Right);
                        dc.DrawAir(GetRectFromNotePosition(air.Position), vd, hd);
                    }

                    g.ResetTransform();
                    moveToOrigin(g);
                    moveToHead(g, headTick);
                    moveToColumn(g, columnsCount);

                    // 小節番号
                    using (var brush = new SolidBrush(BackgroundColorProfile.BarIndexColor))
                    {
                        int pos      = 0;
                        int barCount = 0;
                        for (int j = 0; j < sigs.Count; j++)
                        {
                            int currentBarTick = (int)(TicksPerBeat * sigs[j].Value);
                            for (int i = 0; pos + i * currentBarTick < tailTick; i++)
                            {
                                if (j < sigs.Count - 1 && i * currentBarTick >= (sigs[j + 1].Key - pos) / currentBarTick * currentBarTick)
                                {
                                    break;
                                }

                                int tick = pos + i * currentBarTick;
                                barCount++;
                                if (tick < headTick)
                                {
                                    continue;
                                }
                                var point = new PointF(-strSize.Width, -GetYPositionFromTick(tick) - strSize.Height);
                                g.DrawString(string.Format("{0:000}", barCount), MeasurementProfile.Font, brush, point);
                            }

                            if (j < sigs.Count - 1)
                            {
                                pos += (sigs[j + 1].Key - pos) / currentBarTick * currentBarTick;
                            }
                        }
                    }

                    float rightBaseX = wholeLaneWidth + strSize.Width / 3;

                    // BPM
                    using (var brush = new SolidBrush(BackgroundColorProfile.BpmColor))
                    {
                        foreach (var item in Score.BpmDefinitions.Where(p => p.Key >= headTick && p.Key < tailTick))
                        {
                            var point = new PointF(rightBaseX, -GetYPositionFromTick(item.Key) - strSize.Height);
                            g.DrawString(string.Format("{0:000.#}", item.Value), MeasurementProfile.Font, brush, point);
                        }
                    }

                    // 次の列に移動
                    headTick += columnTick;
                    columnsCount++;
                }
            }

            return(bmp);
        }
Example #56
0
 public HighScoreData()
 {
     highScore = Score.GetScore();
 }
    private void UpdateHighscore()
    {
        int highscore = Score.GetHighscore();

        transform.Find("highscoreText").GetComponent <Text>().text = "HIGHSCORE\n" + highscore.ToString();
    }
Example #58
0
        private async Task DoRescue(IHubContext context, PlayerSetup.Player attacker, PlayerSetup.Player target,
                                    Room room)
        {
            attacker.Status = PlayerSetup.Player.PlayerStatus.Busy;



            if (attacker.ManaPoints < RescueAb().MovesCost)
            {
                context.SendToClient("You are too tired to use Rescue.", attacker.HubGuid);
                attacker.ActiveSkill = null;
                PlayerSetup.Player.SetState(attacker);
                return;
            }

            var die = new PlayerStats();

            var ToRescue =
                Helpers.GetPercentage(
                    attacker.Skills.Find(x => x.Name.Equals(RescueAb().Name, StringComparison.CurrentCultureIgnoreCase))
                    .Proficiency, 95);

            int chance = die.dice(1, 100);

            bool alive = Fight2.IsAlive(attacker, target);


            if (alive)
            {
                if (ToRescue > chance)
                {
                    if (Fight2.IsAlive(attacker, target))
                    {
                        HubContext.Instance.SendToClient(
                            "You <span style='color:cyan'> rescue " +
                            Helpers.ReturnName(target, attacker, null).ToLower() + "</span>!",
                            attacker.HubGuid);


                        HubContext.Instance.SendToClient(
                            $"<span style='color:cyan'>{Helpers.ReturnName(attacker, target, null)} rescues you!</span>",
                            target.HubGuid);

                        HubContext.Instance.SendToClient(
                            $"<span style='color:cyan'>{Helpers.ReturnName(attacker, target, null)} rescues {Helpers.ReturnName(target, attacker, null).ToLower()}!</span>",
                            target.Target.HubGuid);


                        foreach (var player in room.players)
                        {
                            if (player != attacker && player != target)
                            {
                                HubContext.Instance.SendToClient(
                                    Helpers.ReturnName(attacker, target, null) + " rescues " +
                                    Helpers.ReturnName(target, attacker, null) + "!", target.HubGuid);
                            }
                        }

                        var saveFromWhom = target.Target.Name;
                        target.Target.Target         = null;
                        target.Target.ActiveFighting = false;
                        target.Target.Target         = null;

                        target.Target         = null;
                        target.Status         = Player.PlayerStatus.Standing;
                        target.ActiveFighting = false;
                        ;
                        Command.ParseCommand($"kill {saveFromWhom}", attacker, room);
                    }
                }
                else
                {
                    if (Fight2.IsAlive(attacker, target))
                    {
                        var attackerMessage = "You fail to rescue " + Helpers.ReturnName(target, attacker, null);

                        var targetMessage = Helpers.ReturnName(attacker, target, null) + " fails to rescue you.";

                        var observerMessage = Helpers.ReturnName(attacker, target, null) + " fails to rescue " +
                                              Helpers.ReturnName(target, attacker, null);


                        HubContext.Instance.SendToClient(attackerMessage + " <br><br> ", attacker.HubGuid);
                        HubContext.Instance.SendToClient(targetMessage + " <br><br> ", target.HubGuid);

                        foreach (var player in room.players)
                        {
                            if (player != attacker && player != target)
                            {
                                HubContext.Instance.SendToClient(
                                    observerMessage, player.HubGuid);
                            }
                        }
                    }
                }


                Score.ReturnScoreUI(target);


                attacker.ActiveSkill = null;
            }
        }
 private void Update()
 {
     scoreText.text = Score.GetScore().ToString();
 }
Example #60
0
        public void TestUnitNumberMultiplier()
        {
            Score score     = new Score(3, 3, 3, 3L, 3, 3, new decimal(3), new RawInt128(new byte[] { 3 }), 3);
            Score scoreOrig = new Score(3, 3, 3, 3L, 3, 3, new decimal(3), new RawInt128(new byte[] { 3 }), 3);

            PropertyManipulator byteManipulator    = new PropertyManipulator("ByteValue");
            PropertyManipulator shortManipulator   = new PropertyManipulator("ShortValue");
            PropertyManipulator intManipulator     = new PropertyManipulator("IntValue");
            PropertyManipulator longManipulator    = new PropertyManipulator("LongValue");
            PropertyManipulator floatManipulator   = new PropertyManipulator("FloatValue");
            PropertyManipulator doubleManipulator  = new PropertyManipulator("DoubleValue");
            PropertyManipulator decimalManipulator = new PropertyManipulator("DecimalValue");
            PropertyManipulator int128Manipulator  = new PropertyManipulator("RawInt128Value");

            NumberMultiplier processorByte  = new NumberMultiplier(byteManipulator, 2, true);
            NumberMultiplier processorByte2 = new NumberMultiplier("ByteValue", 2, false);

            Assert.IsTrue(processorByte.Equals(processorByte2));
            NumberMultiplier processorShort   = new NumberMultiplier(shortManipulator, 2, true);
            NumberMultiplier processorInt     = new NumberMultiplier(intManipulator, 2, true);
            NumberMultiplier processorLong    = new NumberMultiplier(longManipulator, 2, true);
            NumberMultiplier processorFloat   = new NumberMultiplier(floatManipulator, 2, true);
            NumberMultiplier processorDouble  = new NumberMultiplier(doubleManipulator, 2, true);
            NumberMultiplier processorDecimal = new NumberMultiplier(decimalManipulator, new decimal(2), true);

            Exception        e = null;
            NumberMultiplier processorInt128 = null;

            try
            {
                processorInt128 = new NumberMultiplier(int128Manipulator, new RawInt128(new byte[] { 6 }), true);
            }
            catch (Exception ex)
            {
                e = ex;
            }
            Assert.IsNull(processorInt128);
            Assert.IsNotNull(e);
            Assert.IsInstanceOf(typeof(ArgumentException), e);

            processorInt128 = new NumberMultiplier(int128Manipulator, 2, true);

            LocalCache.Entry entry   = new LocalCache.Entry(new LocalCache(), "score", score);
            object           result1 = processorByte.Process(entry);

            Assert.IsNotNull(result1);
            Assert.IsInstanceOf(typeof(byte), result1);
            Assert.AreEqual((byte)result1, 3);
            result1 = processorByte2.Process(entry);
            Assert.IsNotNull(result1);
            Assert.IsInstanceOf(typeof(byte), result1);
            Assert.AreEqual((byte)result1, 12);

            processorShort.Process(entry);
            processorInt.Process(entry);
            processorLong.Process(entry);
            processorFloat.Process(entry);
            processorDouble.Process(entry);
            processorDecimal.Process(entry);
            processorInt128.Process(entry);

            Assert.AreEqual(scoreOrig.ByteValue * 4, ((Score)entry.Value).ByteValue);
            Assert.AreEqual(scoreOrig.ShortValue * 2, ((Score)entry.Value).ShortValue);
            Assert.AreEqual(scoreOrig.IntValue * 2, ((Score)entry.Value).IntValue);
            Assert.AreEqual(scoreOrig.LongValue * 2, ((Score)entry.Value).LongValue);
            Assert.AreEqual(scoreOrig.FloatValue * 2, ((Score)entry.Value).FloatValue);
            Assert.AreEqual(scoreOrig.DoubleValue * 2, ((Score)entry.Value).DoubleValue);
            Assert.AreEqual(scoreOrig.RawInt128Value.ToDecimal() * 2, ((Score)entry.Value).RawInt128Value.ToDecimal());
            Assert.AreEqual(Decimal.Multiply(scoreOrig.DecimalValue, new Decimal(2)), ((Score)entry.Value).DecimalValue);

            processorShort = new NumberMultiplier(shortManipulator, 2.5, true);
            processorLong  = new NumberMultiplier(longManipulator, 2.5, true);
            processorByte  = new NumberMultiplier(byteManipulator, 2.5, true);
            processorShort.Process(entry);
            processorLong.Process(entry);
            processorByte.Process(entry);
            Assert.AreEqual(scoreOrig.ByteValue * 10, ((Score)entry.Value).ByteValue);
            Assert.AreEqual(scoreOrig.ShortValue * 5, ((Score)entry.Value).ShortValue);
            Assert.AreEqual(scoreOrig.LongValue * 5, ((Score)entry.Value).LongValue);
        }