Example #1
0
        public void SaveSuccsefulClassicSession(Classic newSession)
        {
            if (null == PacientsData[CurrentPacient.ID].lastClassicSessions)
            {
                PacientsData[CurrentPacient.ID].lastClassicSessions = new List <Classic>();
            }

            bool alreadyExists = false;
            int  existsIndex   = -1;

            for (int i = 0; i < PacientsData[CurrentPacient.ID].lastClassicSessions.Count && !alreadyExists; i++)
            {
                if (PacientsData[CurrentPacient.ID].lastClassicSessions[i].tone.FrequencyIndex == newSession.tone.FrequencyIndex)
                {
                    if (PacientsData[CurrentPacient.ID].lastClassicSessions[i].tone.Ear == newSession.tone.Ear)
                    {
                        alreadyExists = true;
                        existsIndex   = i;
                    }
                }
            }

            if (alreadyExists)
            {
                PacientsData[CurrentPacient.ID].lastClassicSessions[existsIndex] = newSession;
            }
            else
            {
                PacientsData[CurrentPacient.ID].lastClassicSessions.Add(newSession);
            }

            PacientsData[CurrentPacient.ID].lastTestDate = DateTime.Now.ToString("dd/MM/yyyy");

            SavePacientData();
        }
        public static void InitTikets()
        {
            var connectionString = "mongodb://localhost/?safe=true";
            var server           = MongoServer.Create(connectionString);
            var db = server.GetDatabase("TransportSystem");

            var collectionTicket = db.GetCollection <Ticket>("Ticket");



            Classic clasicTicket = new Classic()
            {
                Type = "classic"
            };

            clasicTicket.DynamicFields.Add("Bus", 15);
            clasicTicket.DynamicFields.Add("Metro", 21);
            clasicTicket.DynamicFields.Add("Brod", 2);
            TimeTicket timeTicket = new TimeTicket()
            {
                Duration = 20, StartTime = DateTime.Now, EndTime = DateTime.Now.AddMonths(+2), Type = "time", Zone = 32
            };

            collectionTicket.Insert(clasicTicket);
            collectionTicket.Insert(timeTicket);
        }
Example #3
0
    public void OnInitialised()
    {
        CP = Classic.SetUpCanopy(
            CanopyType.C4, // Canopy type
            363,           // CO2 partial pressure
            0.7,           // Curvature factor
            0.047,         // Diffusivity-solubility ratio
            210000,        // O2 partial pressure
            0.78,          // Diffuse extinction coefficient
            0.8,           // Diffuse extinction coefficient NIR
            0.036,         // Diffuse reflection coefficient
            0.389,         // Diffuse reflection coefficient NIR
            60,            // Leaf angle
            0.15,          // Leaf scattering coefficient
            0.8,           // Leaf scattering coefficient NIR
            0.15,          // Leaf width
            1.3,           // SLN ratio at canopy top
            14,            // Minimum Nitrogen
            1.5,           // Wind speed
            1.5);          // Wind speed extinction


        PP = Classic.SetUpPathway(
            0,                  // jTMin
            37.8649150880407,   // jTOpt
            55,                 // jTMax
            0.711229539802063,  // jC
            1,                  // jBeta
            0,                  // gTMin
            42,                 // gTOpt
            55,                 // gTMax
            0.462820450976839,  // gC
            1,                  // gBeta
            1210,               // KcAt25
            64200,              // KcFactor
            292000,             // KoAt25
            10500,              // KoFactor
            5.51328906454566,   // VcVoAt25
            21265.4029552906,   // VcVoFactor
            75,                 // KpAt25
            36300,              // KpFactor
            78000,              // VcFactor
            46390,              // RdFactor
            57043.2677590512,   // VpFactor
            120,                // pepRegeneration
            0.15,               // spectralCorrectionFactor
            0.1,                // ps2ActivityFraction
            0.003,              // bundleSheathConductance
            0.465 * PsiFactor,  // maxRubiscoActivitySLNRatio
            2.7 * PsiFactor,    // maxElectronTransportSLNRatio
            0.0 * PsiFactor,    // respirationSLNRatio
            1.55 * PsiFactor,   // maxPEPcActivitySLNRatio
            0.0135 * PsiFactor, // mesophyllCO2ConductanceSLNRatio
            2,                  // extraATPCost
            0.45);              // intercellularToAirCO2Ratio

        //Set the LAI trigger
        MyPaddock.Set("laiTrigger", LAITrigger);
    }
Example #4
0
        private async Task <Result> GetUserTeamIfNotInRetrievedPage(Classic l, PointsController pointsController, List <Game> gwGames, List <Player> allPlayers, List <Team> allTeams, List <Game> allGames, List <GWPlayer> allGwPlayers, EventStatus eventStatus, int gameweekId, int topOfLeaguePointsTotal)
        {
            var userTeam = new Result();

            HttpClientHandler handler = new HttpClientHandler();

            var response = await _httpClient.GetAuthAsync(CreateHandler(handler), $"entry/{teamId}/");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var leaguesJSON = JObject.Parse(content);

            JObject leaguesObject = (JObject)leaguesJSON["leagues"];
            Leagues leagues       = leaguesObject.ToObject <Leagues>();

            var selectedLeague = leagues.classic.Find(x => x.id == l.id);

            if (selectedLeague != null)
            {
                GWTeam gwTeam = new GWTeam();
                gwTeam = await pointsController.PopulateGwTeam(gwTeam, gameweekId, teamId);

                gwTeam = pointsController.AddPlayerSummaryDataToTeam(allPlayers, allTeams, allGames, gwTeam, teamId, gameweekId);
                gwTeam = await pointsController.AddTransfersToGwTeam(allPlayers, gwTeam, teamId, gameweekId);

                gwTeam.picks = pointsController.AddPlayerGameweekDataToTeam(gwGames, allGwPlayers, gwTeam.picks, gameweekId);
                gwTeam       = pointsController.AddAutoSubs(gwTeam, gwTeam.picks, teamId, eventStatus, gameweekId);
                userTeam.CompleteEntryHistory = await pointsController.GetCompleteEntryHistory(userTeam.CompleteEntryHistory, teamId);

                gwTeam.picks = pointsController.AddEstimatedBonusToTeamPicks(gwTeam.picks, eventStatus);
                var teamDetails = await pointsController.GetTeamInfo(teamId);

                gwTeam.OverallRank = (int)teamDetails.summary_overall_rank;

                foreach (var p in gwTeam.picks)
                {
                    CalculatePlayersYetToPlay(gwTeam, p);
                }

                //CalculateRankAndPFF(l);

                int gwpoints = pointsController.GetGameWeekPoints(gwTeam.picks, eventStatus);
                userTeam.Last5GwPoints   = userTeam.CompleteEntryHistory.GetLast5GwPoints(gwpoints);
                userTeam.total           = CalculatePlayerTotal(teamDetails, gwpoints);
                userTeam.PointsFromFirst = topOfLeaguePointsTotal - userTeam.total;
                userTeam.event_total     = gwpoints;
                userTeam.GWTeam          = gwTeam;
                userTeam.rank            = selectedLeague.entry_rank;
                userTeam.player_name     = teamDetails.player_first_name + ' ' + teamDetails.player_last_name;
                userTeam.entry_name      = teamDetails.name;

                return(userTeam);
            }

            return(null);
        }
Example #5
0
    private void Awake()
    {
        originalPos = transform.position;
        originalRot = transform.rotation;

        camera   = GetComponent <Camera>();
        classic  = new Classic(camera);
        jonasson = new Jonasson(camera, JonassonPoint);
    }
Example #6
0
    private bool empty = true; // tracks if the header has been printed for the interval value data
    [EventHandler] public void Ondodcapst()
    {
        int    DOY            = 0;
        double latitude       = 0;
        double maxT           = 0;
        double minT           = 0;
        double radn           = 0;
        double RootShootRatio = 0;
        double SLN            = 0;
        double SWAvailable    = 0;
        double lai            = 0;

        MyPaddock.Get("DCAPSTDOY", out DOY);
        MyPaddock.Get("DCAPSTsln", out SLN);
        MyPaddock.Get("DCAPSTRootShootRatio", out RootShootRatio);
        MyPaddock.Get("DCAPSTswAvail", out SWAvailable);

        MyPaddock.Get("latitude", out latitude);
        MyPaddock.Get("maxT", out maxT);
        MyPaddock.Get("minT", out minT);
        MyPaddock.Get("radn", out radn);
        MyPaddock.Get("lai", out lai);

        // Model the photosynthesis
        DCAPSTModel DM = Classic.SetUpModel(CP, PP, DOY, latitude, maxT, minT, radn);

        // Optional values
        DM.PrintIntervalValues = false; // Switch to print extra data (default = false)
        DM.Biolimit            = 0;     // Biological transpiration limit of the crop (0 disables mechanism)
        DM.Reduction           = 0;     // Excess water reduction fraction for bio-limited transpiration (0 disables mechanism)

        // Run the simulation
        DM.DailyRun(lai, SLN, SWAvailable, RootShootRatio);

        if (DM.PrintIntervalValues)
        {
            if (empty)
            {
                writer.WriteLine(DM.PrintResultHeader());
                empty = false;
            }

            writer.WriteLine(DM.IntervalResults);
        }

        // Outputs
        RootShoot      = RootShootRatio;
        BIOshootDAY    = dcapst[0] = DM.ActualBiomass;
        BIOtotalDAY    = BIOshootDAY * (1 + RootShoot);
        EcanDemand     = dcapst[1] = DM.WaterDemanded;
        EcanSupply     = dcapst[2] = DM.WaterSupplied;
        RadIntDcaps    = dcapst[3] = DM.InterceptedRadiation;
        RUE            = (RadIntDcaps == 0 ? 0 : BIOshootDAY / RadIntDcaps);
        TE             = (EcanSupply == 0 ? 0 : BIOshootDAY / EcanSupply);
        BIOshootDAYPot = dcapst[4] = DM.PotentialBiomass;
        SoilWater      = SWAvailable;
    }
Example #7
0
        public async Task <IActionResult> Index(int id)
        {
            List <Player> allPlayers = await GetAllPlayers();

            List <Team> allTeams = await GetAllTeams();

            List <Game> allGames = await GetAllGames();

            var currentGameweekId = await GetCurrentGameWeekId();

            List <GWPlayer> allGwPlayers = await GetAllGwPlayers(currentGameweekId);

            EventStatus eventStatus = await GetEventStatus();

            List <Game> gwGames = await GetGwGames(currentGameweekId);

            var viewModel = new LeaguesViewModel();

            HttpClientHandler handler = new HttpClientHandler();

            if (Request.Cookies["teamId"] == null)
            {
                teamId = await GetTeamId();
            }
            else
            {
                teamId = Convert.ToInt32(Request.Cookies["teamId"]);
            }

            var response = await _httpClient.GetAuthAsync(CreateHandler(handler), $"entry/{teamId}/");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var leaguesJSON = JObject.Parse(content);

            JObject leaguesObject = (JObject)leaguesJSON["leagues"];
            Leagues leagues       = leaguesObject.ToObject <Leagues>();

            leagues = await AddBasicInfoToPrivateLeagues(gwGames, allPlayers, allTeams, allGames, allGwPlayers, leagues, eventStatus, currentGameweekId);

            Classic selectedLeague = await GetPlayerStandingsForClassicLeague(id, currentGameweekId);

            //var gwGames = await GetGwFixtures(currentGameweekId);

            viewModel.SelectedLeague = selectedLeague;
            viewModel.IsEventLive    = IsEventLive(eventStatus);
            viewModel.ClassicLeagues = leagues.classic;
            viewModel.H2HLeagues     = leagues.h2h;
            viewModel.Cup            = leagues.cup;
            viewModel.CurrentGwId    = currentGameweekId;
            viewModel.TeamId         = teamId;
            viewModel.LastUpdated    = GetLastTimeLeagueWasUpdated(gwGames);

            return(View(viewModel));
        }
Example #8
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.InitializeComponent();
            var renderer = new GameRenderer(this.GameCanvas);
            var map      = new Classic();
            var engine   = new Engine(map, renderer);

            engine.InitGame();
            engine.DrawGameObjects();
        }
Example #9
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string nameOne   = tbOne.Text;
            string nameTwo   = tbTwo.Text;
            string nameThree = tbThree.Text;
            int    type      = GetGameType();

            if (DoesOngoingGameExist(nameOne, nameTwo, nameThree) == false)
            {
                if (rbClassic.IsChecked == true)
                {
                    Classic g = new Classic();
                    CheckPlayer(nameOne, nameTwo, nameThree, type, g);
                    if (sure == true)
                    {
                        PlayGame(nameOne, nameTwo, nameThree, type, g);
                    }
                    else if (sure == false)
                    {
                        if (MessageBox.Show("Någon utav spelarna finns inte med i databasen. Vill du ändå fortsätta och spela orankat ? ", "Säkert?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            //do no stuff
                        }
                        else
                        {
                            PlayGame(nameOne, nameTwo, nameThree, type, g);
                        }
                    }
                }
                else if (rbForced.IsChecked == true)
                {
                    Forced g = new Forced();
                    CheckPlayer(nameOne, nameTwo, nameThree, type, g);
                    if (sure == true)
                    {
                        PlayGame(nameOne, nameTwo, nameThree, type, g);
                    }
                    else if (sure == false)
                    {
                        if (MessageBox.Show("Någon utav spelarna finns inte med i databasen. Vill du ändå fortsätta och spela orankat ? ", "Säkert?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            //do no stuff
                        }
                        else
                        {
                            PlayGame(nameOne, nameTwo, nameThree, type, g);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Du har redan ett spel igång!");
            }
        }
Example #10
0
        public MainWindow()
        {
            this.InitializeComponent();
            var renderer = new GameRenderer(this.GameCanvas);
            var map      = new Classic();
            var engine   = new Engine(map, renderer);

            engine.InitGame();
            engine.DrawGameObjects();
            ///this.Dots();
        }
Example #11
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (_allClassics.Count(x => x.Name == _selectedClassic.Name) == 0 && !string.IsNullOrEmpty(_selectedClassic.Name) && _selectedClassic.Max > 0)
            {
                _selectedClassic.Id = 0;
                _repo.InsertItem <Classic>(_selectedClassic);
                GetAllClassics();

                _selectedClassic = new Classic();
            }
        }
        public static Ticket BuyNewClassicTicket(Classic ticket)
        {
            var connectionString = "mongodb://localhost/?safe=true";
            var server           = MongoServer.Create(connectionString);
            var db = server.GetDatabase("TransportSystem");


            var collectionTicket = db.GetCollection <Ticket>("Ticket");

            collectionTicket.Insert(ticket);

            return(ticket);
        }
Example #13
0
        private void CalculateRankAndPFF(Classic league)
        {
            if (league.Standings.results.Count > 0)
            {
                var standingsByLivePointsTotal = league.Standings.results.OrderByDescending(x => x.total).ToList();
                int topOfLeaguePoints          = league.Standings.results.OrderByDescending(x => x.total).FirstOrDefault().total;

                foreach (var player in league.Standings.results)
                {
                    player.rank            = standingsByLivePointsTotal.IndexOf(player) + 1;
                    player.PointsFromFirst = topOfLeaguePoints - player.total;
                }
            }
        }
Example #14
0
        private void CalculatePlayersTallyForLeague(Classic league, List <Pick> players, int leagueCount)
        {
            List <Transfer> allGwTransfers = new List <Transfer>();

            foreach (Result player in league.Standings.results)
            {
                foreach (Transfer transfer in player.GWTeam.GWTransfers)
                {
                    allGwTransfers.Add(transfer);
                }
            }

            foreach (var player in players)
            {
                if (!league.PlayersTally.Any(x => x.Pick.element == player.element))
                {
                    var count     = players.FindAll(x => x.element == player.element).Count();
                    var ownership = ((double)count / (double)leagueCount).ToString("0%");

                    var startingCount = players.FindAll(x => x.element == player.element && x.multiplier > 0).Count();
                    var startingSelectionPercentage = ((double)startingCount / (double)leagueCount).ToString("0%");

                    var benchCount = players.FindAll(x => x.element == player.element && x.multiplier == 0).Count();
                    var benchSelectionPercentage = ((double)benchCount / (double)leagueCount).ToString("0%");

                    int captainCount = players.FindAll(x => x.element == player.element && x.is_captain).Count();
                    var captainSelectionPercentage = ((double)captainCount / (double)leagueCount).ToString("0%");

                    int transferInCount = allGwTransfers.FindAll(x => x.PlayerIn.id == player.element).Count();
                    var transferredIn   = ((double)transferInCount / (double)leagueCount).ToString("0%");

                    int transferOutCount = allGwTransfers.FindAll(x => x.PlayerOut.id == player.element).Count();
                    var transferredOut   = ((double)transferOutCount / (double)leagueCount).ToString("0%");

                    var pt = new PlayerTally()
                    {
                        Pick              = player,
                        Count             = count,
                        Ownership         = ownership,
                        StartingSelection = startingSelectionPercentage,
                        BenchSelection    = benchSelectionPercentage,
                        CaptainSelection  = captainSelectionPercentage,
                        TransferredOut    = transferredOut,
                        TransferredIn     = transferredIn
                    };

                    league.PlayersTally.Add(pt);
                }
            }
        }
Example #15
0
        public void QuotRemTest()
        {
            int[] param1     = { 10, -10 }, param2 = { 3, -3 };
            var   prodParams =
                from n0 in param1
                from n1 in param2
                select new { n0, n1 };

            foreach (var tup in prodParams)
            {
                int ansQ = tup.n0 / tup.n1, ansR = tup.n0 % tup.n1;
                Assert.AreEqual(ansQ, Classic.QuotM(tup.n0, tup.n1), "QuotTest");
                Assert.AreEqual(ansR, Classic.RemM(tup.n0, tup.n1), "RemTest");
            }
        }
        public override void UpdateEntity(TextBox[] textBoxName)
        {
            int      qid      = Convert.ToInt32(textBoxName.FirstOrDefault(s => s.ID == "id")?.Text);
            Question question = Context.Get(s => s.Id == qid);

            Easy             easy          = new Easy();
            Classic          classic       = new Classic();
            ClassicAnswer    classicAnswer = new ClassicAnswer();
            IAnswerPresenter answer        = null;

            TextBox[] answerTextBoxs = textBoxName.Where(s => s.ID.ToLower().Contains("answer")).ToArray();
            foreach (TextBox textBox in textBoxName)
            {
                if (!textBox.ID.ToLower().Contains("answer"))
                {
                    if (textBox.ID.ToLower().Contains("points"))
                    {
                        decimal d = Convert.ToDecimal(textBox.Text.Replace(".", ","));
                        question.Points = d;
                    }
                    else if (textBox.ID.ToLower().Contains("question"))
                    {
                        question.MyQuestion = textBox.Text;
                    }
                    else if (textBox.ID.ToLower().Contains("selectdifficulty"))
                    {
                        question.Difficulty = easy.Handle(Convert.ToInt32(textBox.Text));
                    }
                    else if (textBox.ID.ToLower().Contains("selecttype"))
                    {
                        question.Type = classic.Handle(Convert.ToInt32(textBox.Text));
                        answer        = classicAnswer.Handle((int)question.Type);
                    }
                    else if (textBox.ID.ToLower().Contains("selectlesson"))
                    {
                        question.LessonId = Convert.ToInt32(textBox.Text);
                    }
                }
            }
            Context.Update(question);
            if (answerTextBoxs.Length > 0)
            {
                answer?.UpdateAnswer(answerTextBoxs, question.Id);
            }

            ListEntityWithCollapsibleTable();
        }
        public override void AddEntity(TextBox[] textBoxName)
        {
            Easy             easy          = new Easy();
            Classic          classic       = new Classic();
            ClassicAnswer    classicAnswer = new ClassicAnswer();
            Question         question      = new Question();
            IAnswerPresenter answer        = null;

            TextBox[] answerTextBoxs = textBoxName.Where(s => s.ID.ToLower().Contains("answer")).ToArray();
            int       lid            = 0;

            foreach (TextBox textBox in textBoxName)
            {
                if (!textBox.ID.ToLower().Contains("answer"))
                {
                    if (textBox.ID.ToLower().Contains("points"))
                    {
                        decimal d = Convert.ToDecimal(textBox.Text.Replace(".", ","));
                        question.Points = d;
                    }
                    else if (textBox.ID.ToLower().Contains("question"))
                    {
                        question.MyQuestion = textBox.Text;
                    }
                    else if (textBox.ID.ToLower().Contains("selectdifficulty"))
                    {
                        question.Difficulty = easy.Handle(Convert.ToInt32(textBox.Text));
                    }
                    else if (textBox.ID.ToLower().Contains("selecttype"))
                    {
                        question.Type = classic.Handle(Convert.ToInt32(textBox.Text));
                        answer        = classicAnswer.Handle((int)question.Type);
                    }
                    else if (textBox.ID.ToLower().Contains("selectlesson"))
                    {
                        lid = Convert.ToInt32(textBox.Text);
                        question.LessonId = lid;
                    }
                }
            }


            Context.Add(question);
            answer?.AddAnswer(answerTextBoxs, question.Id);
            ListEntityWithCollapsibleTable();
        }
Example #18
0
        public async Task <Classic> GetBasicInfoForLeague(int leagueId)
        {
            Classic l = new Classic();

            var PointsController = new PointsController(_httpClient);

            var response = await _httpClient.GetAsync($"leagues-classic/{leagueId}/standings");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var leagueJSON = JObject.Parse(content);

            var leagueDetailsJSON = AllChildren(JObject.Parse(content))
                                    .First(c => c.Type == JTokenType.Object && c.Path.Contains("league"));

            l = leagueDetailsJSON.ToObject <Classic>();

            var temp = new JObject();

            if (await GetCurrentGameWeekId() == 0)
            {
                temp = (JObject)leagueJSON["new_entries"];
            }
            else
            {
                temp = (JObject)leagueJSON["standings"];
            }

            l.Standings.has_next = (bool)temp["has_next"];
            l.Standings.page     = (int)temp["page"];

            var leaguePlayersJSON = AllChildren(temp)
                                    .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
                                    .Children <JObject>();

            foreach (JObject result in leaguePlayersJSON)
            {
                Result r = result.ToObject <Result>();
                l.Standings.results.Add(r);
            }

            return(l);
        }
    static void Main(string[] args)
    {
        Music        song1 = new Rock("ac-dc", "highway to hell");
        Music        song2 = new Classic("elvis presley", "love me tender");
        List <Music> list  = new List <Music>();

        list.Add(song1);
        list.Add(song2);
        Console.WriteLine(list[0].Artist + ", " + list[0].Title);
        Console.WriteLine(list[1].Artist + ", " + list[1].Title);
        string a = Console.ReadLine();     // just type "yeah" or whatever

        song1.play(a);
        song1.play(a);
        song1.play(a);
        song1.play(a);
        Console.ReadLine();
    }
Example #20
0
        public override void StartTest()
        {
            base.StartTest();

            currentSession = new Classic(toneManager.freqIndex, toneManager.currentDB, this, ear);

            for (int i = 0; i < interactableDuringSession.Length; i++)
            {
                previousState[i] = interactableDuringSession[i].interactable;
                interactableDuringSession[i].interactable = false;
            }

            pacientButton.onButtonDown.AddListener(currentSession.PacientButtonDown);
            pacientButton.onButtonUp.AddListener(currentSession.PacientButtonUp);
            pacientButton.onButtonDown.AddListener(LedOn);
            pacientButton.onButtonUp.AddListener(LedOff);

            showGraphsButton.image.sprite = graphsSprites[0];
        }
Example #21
0
    void OnCollisionEnter(Collision collision)
    {
        if (!isLeapMenuTet) {
            TetrominoState tetrominoState = transform.gameObject.GetComponent<TetrominoState> ();

            // TODO: Merge this & apply state changes... this code initalizes the lose screen
            if (tetrominoState.getState() == TetrominoState.states.INACTIVE && collision.gameObject.name == "roof")
            {
                GameObject go = GameObject.Find("Main Camera");
                _classicModeState = (Classic)go.GetComponent(typeof(Classic));
                _classicModeState.InitLoseScreen();
            }

            foreach (Transform child in transform) {
                child.GetComponent<Renderer> ().material.color = Color.grey;
            }
            tetrominoState.setState (TetrominoState.states.INACTIVE);
        }
    }
Example #22
0
        public void Classic_Match()
        {
            var hsv       = new HSV(213, 46, 49);
            var algorithm = new Classic();
            var actual    = algorithm.Match(hsv);
            var expected  = new Blend()
            {
                Colors = new[]
                {
                    new HSV(213, 46, 49),
                    new HSV(213, 46, 79),
                    new HSV(53, 46, 49),
                    new HSV(43, 46, 79),
                    new HSV(0, 0, 51),
                    new HSV(0, 0, 49)
                }
            };

            Assert.Equal(expected, actual, new BlendEqualityComparer());
        }
    void Awake()
    {
        _instance = this;
        Rules     = new Classic();

        //States = new int[(int)CellCount.x, (int)CellCount.y];
        //lastProcessedStates = new int[(int)CellCount.x, (int)CellCount.y];

        for (int i = 0; i < CellCount.x; i++)
        {
            for (int j = 0; j < CellCount.y; j++)
            {
                int s = Rules.getRandomCell();
                States.Add(new Vector2(i, j), s);
                lastProcessedStates.Add(new Vector2(i, j), s);
                //States[i, j] = s;
                //lastProcessedStates[i, j] = s;
            }
        }

        incrementCurrentGeneration();
    }
Example #24
0
        private bool DoesOngoingGameExist(string name1, string name2, string name3)
        {
            Classic g        = new Classic();
            bool    isit     = false;
            bool    ongoing1 = g.CheckOngoing(name1);
            bool    ongoing2 = g.CheckOngoing(name2);

            if (cbThree.IsChecked == true)
            {
                bool ongoing3 = g.CheckOngoing(name3);
                if (ongoing1 == true || ongoing2 == true || ongoing3 == true)
                {
                    isit = true;
                }
            }
            else
            {
                if (ongoing1 == true || ongoing2 == true)
                {
                    isit = true;
                }
            }
            return(isit);
        }
    // Use this for initialization
    void Start()
    {
        // Set to spawn every 4 seconds
        _period = 5f;
        _decreaseAmount = 0.10f;		// Decrease by this many seconds (for time between spawns)
        _intervalPerDecrease = 30f;		// Second interval to up the difficulty (a.k.a. decrease the spawn rate by _decreaseAmont time)
        _nextIntervalDecreaseTime = 0f + _intervalPerDecrease;
        _minTimeBetweenSpawns = 1.5f;

        // Set spawn location
        transform.position = new Vector3(0f, 21.80f, 0f);

        // Grab reference of the tetromino queue
        GameObject go = GameObject.Find("TetrinoSelector");
        _tetrinoSelector = (TetrinoSelector) go.GetComponent(typeof(TetrinoSelector));

        // Grab reference of the tetromino spawn timer
        GameObject go2 = GameObject.Find("TetrinoSpawnTimer");
        _tetrinoSpawnTimer = (TetrinoSpawnTimer) go2.GetComponent(typeof(TetrinoSpawnTimer));
        _tetrinoSpawnTimer.SetTimer(0f, float.PositiveInfinity, 0f, _period);
        _tetrinoSpawnTimer.ShouldPop = true;
        _tetrinoSpawnTimer.BeginCountUp();

        // Grab reference of the tetromino spawn rate modifier (for adjusting difficulty on the spawn timer)
        GameObject go3 = GameObject.Find("TetrinoSpawnRateModifier");
        _tetrinoSpawnRateModifier = (TetrinoSpawnRateModifier) go3.GetComponent(typeof(TetrinoSpawnRateModifier));
        _tetrinoSpawnRateModifier.SetDecreaseAmount(_decreaseAmount);				// Decrease by _decreaseAmount seconds at a set interval
        _tetrinoSpawnRateModifier.SetIntervalPerDecrease(_intervalPerDecrease);		// Every _intervalPerDecrease seconds, decrease the interval by _decreaseAmount seconds

        // Get Classic mode state to check if game is over
        GameObject go4 = GameObject.Find("Main Camera");
        _classicModeState = (Classic)go4.GetComponent(typeof(Classic));

        // Get score manager reference
        GameObject go5 = GameObject.Find("ScoreManager");
        _scoreManager = (ScoreManager) go5.GetComponent(typeof(ScoreManager));
    }
 /// <summary>
 /// Creates a new <see cref="ExtensionQuery"/>
 /// </summary>
 /// <param name="topLevelParser"></param>
 /// <param name="field">the query field</param>
 /// <param name="rawQueryString">the raw extension query string</param>
 public ExtensionQuery(Classic.QueryParser topLevelParser, string field, string rawQueryString)
 {
     this.Field = field;
     this.RawQueryString = rawQueryString;
     this.TopLevelParser = topLevelParser;
 }
Example #27
0
    public void OnInitialised()
    {
        /* IMPORTANT - Do NOT change the order of these values */

        CP = Classic.SetUpCanopy(
            CanopyType.C3, // Canopy type
            370,           // CO2 partial pressure
            0.7,           // Empirical curvature factor
            0.047,         // Diffusivity-solubility ratio
            210000,        // O2 partial pressure
            0.78,          // PAR diffuse extinction coefficient
            0.8,           // NIR diffuse extinction coefficient
            0.036,         // PAR diffuse reflection coefficient
            0.389,         // NIR diffuse reflection coefficient
            60,            // Leaf angle
            0.15,          // PAR leaf scattering coefficient
            0.8,           // NIR leaf scattering coefficient
            0.05,          // Leaf width
            1.3,           // SLN ratio at canopy top
            14,            // Minimum structural nitrogen
            1.5,           // Wind speed
            1.5);          // Wind speed profile distribution coefficient

        PP = Classic.SetUpPathway(
            0,                   // Electron transport minimum temperature
            30.0,                // Electron transport optimum temperature
            45.0,                // Electron transport maximum temperature
            0.911017958600129,   // Electron transport scaling constant
            1,                   // Electron transport Beta value

            6048.95289,          //mesophyll conductance factor

            273.422964228666,    // Kc25 - Michaelis Menten constant of Rubisco carboxylation at 25 degrees C
            93720,               // KcFactor

            165824.064155384,    // Ko25 - Michaelis Menten constant of Rubisco oxygenation at 25 degrees C
            33600,               // KoFactor

            4.59217066521612,    // VcVo25 - Rubisco carboxylation to oxygenation at 25 degrees C
            35713.19871277176,   // VcVoFactor

            0.0,                 // Kp25 - Michaelis Menten constant of PEPc activity at 25 degrees C (Unused in C3)
            0.0,                 // KpFactor (Unused in C3)

            65330,               // VcFactor
            46390,               // RdFactor
            57043.2677590512,    // VpFactor

            0.0,                 // PEPc regeneration (Unused in C3)
            0.15,                // Spectral correction factor
            0.1,                 // Photosystem II activity fraction
            0.003,               // Bundle sheath CO2 conductance
            1.1 * PsiFactor,     // Max Rubisco activity to SLN ratio
            1.85 * PsiFactor,    // Max electron transport to SLN ratio
            0.0 * PsiFactor,     // Respiration to SLN ratio
            1.0 * PsiFactor,     // Max PEPc activity to SLN ratio
            0.00412 * PsiFactor, // Mesophyll CO2 conductance to SLN ratio
            0.75,                // Extra ATP cost
            0.7);                // Intercellular CO2 to air CO2 ratio

        //Set the LAI trigger
        MyPaddock.Set("DCaPSTTriggerLAI", LAITrigger);
        MyPaddock.Get("PsModelName1", out PsModelName1);
    }
Example #28
0
    public void Ondodcapst()
    {
        int    DOY            = 0;
        double latitude       = 0;
        double maxT           = 0;
        double minT           = 0;
        double radn           = 0;
        double RootShootRatio = 0;
        double sln            = 0;
        double greenN         = 0;
        double SWAvailable    = 0;
        double lai            = 0;

        MyPaddock.Get("DCAPSTDOY", out DOY);
        MyPaddock.Get("DCAPSTRootShootRatio", out RootShootRatio);
        MyPaddock.Get("DCAPSTswAvail", out SWAvailable);
        MyPaddock.Get("LeafGreenN", out greenN);
        MyPaddock.Get("latitude", out latitude);
        MyPaddock.Get("maxT", out maxT);
        MyPaddock.Get("minT", out minT);
        MyPaddock.Get("radn", out radn);
        MyPaddock.Get("lai", out lai);

        // Model the photosynthesis
        double      rpar = 0.5;
        DCAPSTModel DM   = Classic.SetUpModel(CP, PP, DOY, latitude, maxT, minT, radn, rpar);

        // OPTIONAL VALUES:
        // Biological transpiration limit of the crop
        DM.Biolimit = 0;     // default = 0 (disabled)

        // Excess water reduction fraction for bio-limited transpiration
        DM.Reduction = 0;    // default = 0 (disabled)

        if (lai > LAITrigger && lai < NLAITrigger)
        {
            sln = Math.Max(greenN, NLowLimit);
        }
        else
        {
            sln = greenN / lai;
        }

        // Run the simulation
        DM.DailyRun(lai, sln, SWAvailable, RootShootRatio);

        // Daily outputs
        RootShoot      = RootShootRatio;
        BIOshootDAY    = dcapst[0] = DM.ActualBiomass;
        BIOtotalDAY    = BIOshootDAY * (1 + RootShoot);
        EcanDemand     = dcapst[1] = DM.WaterDemanded;
        EcanSupply     = dcapst[2] = DM.WaterSupplied;
        RadIntDcaps    = dcapst[3] = DM.InterceptedRadiation;
        RUE            = (RadIntDcaps == 0 ? 0 : BIOshootDAY / RadIntDcaps);
        TE             = (EcanSupply == 0 ? 0 : BIOshootDAY / EcanSupply);
        BIOshootDAYPot = dcapst[4] = DM.PotentialBiomass;
        SoilWater      = SWAvailable;
        dsln           = sln;

        // Interval outputs

        // For reasons unknown, wheat calls this method twice, but only the 2nd call is used/valid.
        // This skipper just stops the bad data from showing up in the interval report
        skipper = !skipper;
        if (skipper)
        {
            foreach (var interval in DM.Intervals)
            {
                Hour = interval.Time;
                SunlitTemperature = interval.Sunlit.Temperature;
                ShadedTemperature = interval.Shaded.Temperature;
                SunlitAc1         = interval.Sunlit.Ac1.Assimilation;
                SunlitAc2         = interval.Sunlit.Ac2.Assimilation;
                SunlitAj          = interval.Sunlit.Aj.Assimilation;
                ShadedAc1         = interval.Shaded.Ac1.Assimilation;
                ShadedAc2         = interval.Shaded.Ac2.Assimilation;
                ShadedAj          = interval.Shaded.Aj.Assimilation;

                if (IntervalStep != null)
                {
                    IntervalStep.Invoke();
                }
            }
        }
    }
Example #29
0
    public void Ondodcaps()
    {
        int    DOY            = 0;
        double latitude       = 0;
        double maxT           = 0;
        double minT           = 0;
        double radn           = 0;
        double RootShootRatio = 0;
        double SLN            = 0;
        double SWAvailable    = 0;
        double lai            = 0;

        MyPaddock.Get("DOY", out DOY);
        MyPaddock.Get("latitude", out latitude);
        MyPaddock.Get("maxT", out maxT);
        MyPaddock.Get("minT", out minT);
        MyPaddock.Get("radn", out radn);
        MyPaddock.Get("RootShootRatio", out RootShootRatio);
        MyPaddock.Get("SLN", out SLN);
        MyPaddock.Get("SWAvailable", out SWAvailable);
        MyPaddock.Get("lai", out lai);

        // Model the photosynthesis
        double      rpar = 0.5;
        DCAPSTModel DM   = Classic.SetUpModel(CP, PP, DOY, latitude, maxT, minT, radn, rpar);

        // Optional values
        DM.PrintIntervalValues = false; // Switch to print extra data (default = false)
        DM.Biolimit            = 0;     // Biological transpiration limit of the crop (0 disables mechanism)
        DM.Reduction           = 0;     // Excess water reduction fraction for bio-limited transpiration (0 disables mechanism)

        // Run the simulation
        DM.DailyRun(lai, SLN, SWAvailable, RootShootRatio);

        // Daily Outputs
        RootShoot      = RootShootRatio;
        BIOshootDAY    = dcaps[0] = DM.ActualBiomass;
        BIOtotalDAY    = BIOshootDAY * (1 + RootShoot);
        EcanDemand     = dcaps[1] = DM.WaterDemanded;
        EcanSupply     = dcaps[2] = DM.WaterSupplied;
        RadIntDcapst   = dcaps[3] = DM.InterceptedRadiation;
        RUE            = (RadIntDcapst == 0 ? 0 : BIOshootDAY / RadIntDcapst);
        TE             = (EcanSupply == 0 ? 0 : BIOshootDAY / EcanSupply);
        BIOshootDAYPot = dcaps[4] = DM.PotentialBiomass;
        SoilWater      = SWAvailable;

        // Interval outputs
        foreach (var interval in DM.Intervals)
        {
            Hour = interval.Time;
            SunlitTemperature = interval.Sunlit.Temperature;
            ShadedTemperature = interval.Shaded.Temperature;
            SunlitAc1         = interval.Sunlit.Ac1.Assimilation;
            SunlitAc2         = interval.Sunlit.Ac2.Assimilation;
            SunlitAj          = interval.Sunlit.Aj.Assimilation;
            ShadedAc1         = interval.Shaded.Ac1.Assimilation;
            ShadedAc2         = interval.Shaded.Ac2.Assimilation;
            ShadedAj          = interval.Shaded.Aj.Assimilation;

            if (IntervalStep != null)
            {
                IntervalStep.Invoke();
            }
        }
    }
Example #30
0
 public static string GetUrl(string key)
 {
     _ = Classic.TryGetValue(key, out int link);
     return($"https://wow.zamimg.com/images/wow/classic/maps/enus/zoom/{link}.jpg");
 }
Example #31
0
        /*private void ResetScreen()
         * {
         *  Engine.Graphics.GraphicsDevice.Textures[0] = null;
         *  Engine.Graphics.GraphicsDevice.Textures[1] = null;
         *
         *  for (var x = 0; x < 128; x++)
         *  for (var y = 0; y < 128; y++)
         *      pixels[x + y * 128] = Color.Black;
         *  buffer.Target.SetData(pixels);
         * }*/

        public override void Update()
        {
            base.Update();

            // pause menu
            //if (pauseMenu != null)
            //pauseMenu.Update();
            //else if (!leaving && (Input.Pause.Pressed || Input.ESC.Pressed))
            //CreatePauseMenu();
            //pauseFade = Calc.Approach(pauseFade, pauseMenu != null ? 0.75f : 0f, Engine.DeltaTime * 6f);

            // this is a pretty dumb hack but because Celeste is locked to 60fps
            // and PICO-8 runs at 30 ... we just skip every 2nd frame
            // the game buffers inputs so they wont get eaten
            skipFrame = !skipFrame;
            if (skipFrame)
            {
                return;
            }

            // don't update the game
            gameDelay -= Engine.DeltaTime;
            if (!gameActive || gameDelay > 0)
            {
                return;
            }

            // recreating the PICO-8 Boot Sequence
            if (booting)
            {
                /*Engine.Graphics.GraphicsDevice.Textures[0] = null;
                 * Engine.Graphics.GraphicsDevice.Textures[1] = null;
                 *
                 * gameFrame++;
                 * var t = gameFrame - 20;
                 *
                 * if (t == 1)
                 * {
                 *  for (var y = 0; y < 128; y++)
                 *      for (var x = 2; x < 128; x += 8)
                 *          pixels[x + y * 128] = colors[Calc.Random.Next(4) + (y / 32)];
                 *  //buffer.Target.SetData(pixels);
                 * }
                 * if (t == 4)
                 * {
                 *  for (var y = 0; y < 128; y += 2)
                 *      for (var x = 0; x < 128; x += 4)
                 *          pixels[x + y * 128] = colors[6 + (((x + y) / 8) & 7)];
                 *  //buffer.Target.SetData(pixels);
                 * }
                 * if (t == 7)
                 * {
                 *  for (var y = 0; y < 128; y += 3)
                 *      for (var x = 2; x < 128; x += 4)
                 *          pixels[x + y * 128] = colors[10 + Calc.Random.Next(4)];
                 *  //buffer.Target.SetData(pixels);
                 * }
                 *
                 * // wide
                 * if (t == 9)
                 * {
                 *  for (var y = 0; y < 128; y++)
                 *      for (var x = 1; x < 127; x += 2)
                 *          pixels[x + y * 128] = pixels[x + 1 + y * 128];
                 *  buffer.Target.SetData(pixels);
                 * }
                 *
                 * // stripe blank
                 * if (t == 12)
                 * {
                 *  for (var y = 0; y < 128; y++)
                 *      if ((y & 3) > 0)
                 *          for (var x = 0; x < 128; x++)
                 *              pixels[x + y * 128] = colors[0];
                 *  buffer.Target.SetData(pixels);
                 * }
                 *
                 * // clear
                 * if (t == 15)
                 * {
                 *  for (var y = 0; y < 128; y++)
                 *      for (var x = 0; x < 128; x++)
                 *          pixels[x + y * 128] = colors[0];
                 *  buffer.Target.SetData(pixels);
                 * }
                 *
                 * if (t == 30)
                 *  Audio.Play(Sfxs.music_pico8_boot);
                 *
                 * // logo
                 * if (t == 30 || t == 35 || t == 40)
                 * {
                 *  Engine.Graphics.GraphicsDevice.SetRenderTarget(buffer);
                 *  Engine.Graphics.GraphicsDevice.Clear(colors[0]);
                 *  Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, RasterizerState.CullNone);
                 *  picoBootLogo.Draw(new Vector2(1, 1));
                 *  if (t >= 35)
                 *      print("pico-8 0.1.9B", 1, 18, 6);
                 *  if (t >= 40)
                 *  {
                 *      print("(c) 2014-16 lexaloffle games llp", 1, 24, 6);
                 *      print("booting cartridge..", 1, 36, 6);
                 *  }
                 *  Draw.SpriteBatch.End();
                 *  Engine.Graphics.GraphicsDevice.SetRenderTarget(null);
                 * }*/

                // start it up
                //if (t == 90)
                //{
                gameFrame = 0;
                game      = new Classic();
                game.Init(this);
                if (bootLevel.X != 0 || bootLevel.Y != 0)
                {
                    game.load_room(bootLevel.X, bootLevel.Y);
                }
                //}
            }
            else
            {
                gameFrame++;
                game.Update();

                if (game.freeze <= 0)
                {
                    // draw
                    {
                        engine.GraphicsDevice.SetRenderTarget(buffer);
                        engine.GraphicsDevice.Clear(colors[0]);
                        Draw.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, RasterizerState.CullNone, null, Matrix.CreateTranslation(-offset.X, -offset.Y, 0));
                        game.Draw();
                        Draw.SpriteBatch.End();

                        // unset in case we do a palette swap
                        engine.GraphicsDevice.SetRenderTarget(null);
                    }

                    // do a palette swap
                    // this could be done with a shader but on a 128x128 screen ... I don't really care
                    if (paletteSwap.Count > 0)
                    {
                        buffer.GetData(pixels);

                        for (var i = 0; i < pixels.Length; i++)
                        {
                            var index = 0;
                            if (paletteSwap.TryGetValue(pixels[i], out index))
                            {
                                pixels[i] = colors[index];
                            }
                        }

                        buffer.SetData(pixels);
                    }
                }
            }
        }
Example #32
0
        public static ControllerState ReadFromPacket(byte[] packet)
        {
            ControllerStateBuilder state = null;

            if (packet.Length == 13)
            {
                return(Classic.ReadFromPacket(packet));
            }
            if (packet.Length == BUTTONS_CD32.Length)
            {
                state = new ControllerStateBuilder();

                for (int i = 0; i < BUTTONS_CD32.Length; ++i)
                {
                    if (string.IsNullOrEmpty(BUTTONS_CD32[i]))
                    {
                        continue;
                    }

                    state.SetButton(BUTTONS_CD32[i], (packet[i] & 0b10000000) == 0x00);
                }

                state.SetButton("up", (packet[8] & 0b00000001) == 0);
                state.SetButton("down", (packet[0] & 0b00000100) == 0);
                state.SetButton("left", (packet[0] & 0b00001000) == 0);
                state.SetButton("right", (packet[0] & 0b00010000) == 0);
            }
            else if (packet.Length == BUTTONS_CDTV_REMOTE.Length)
            {
                int checksum        = (packet[33] >> 4) | packet[34];
                int checkedCheckSum = 0;
                for (int i = 0; i < 33; ++i)
                {
                    checkedCheckSum += packet[i] == 0 ? 0 : 1;
                }

                if (checksum == checkedCheckSum)
                {
                    state = new ControllerStateBuilder();

                    for (int i = 0; i < BUTTONS_CDTV_REMOTE.Length; ++i)
                    {
                        if (string.IsNullOrEmpty(BUTTONS_CDTV_REMOTE[i]))
                        {
                            continue;
                        }

                        state.SetButton(BUTTONS_CDTV_REMOTE[i], packet[i] != 0x00);
                    }

                    float x = 0;
                    float y = 0;

                    if (packet[0] != 0x00)
                    {
                        x = -0.25f;
                    }
                    else if (packet[2] != 0x00)
                    {
                        x = 0.25f;
                    }

                    if (packet[1] != 0x00)
                    {
                        y = 0.25f;
                    }
                    else if (packet[3] != 0x00)
                    {
                        y = -0.25f;
                    }

                    SignalTool.SetMouseProperties(x, y, state, .25f);
                }
            }
            else if (packet.Length == BUTTONS_CDTV_JOYSTICK.Length && packet[0] == 0)
            {
                int checksum        = (packet[24] >> 4) | packet[25];
                int checkedCheckSum = 0;
                for (int i = 0; i < 24; ++i)
                {
                    checkedCheckSum += packet[i] == 0 ? 0 : 1;
                }

                if (checksum == checkedCheckSum)
                {
                    state = new ControllerStateBuilder();

                    for (int i = 0; i < BUTTONS_CDTV_JOYSTICK.Length; ++i)
                    {
                        if (string.IsNullOrEmpty(BUTTONS_CDTV_JOYSTICK[i]))
                        {
                            continue;
                        }

                        state.SetButton(BUTTONS_CDTV_JOYSTICK[i], packet[i] != 0x00);
                    }

                    SignalTool.FakeAnalogStick(packet[6], packet[5], packet[4], packet[3], state, "x", "y");
                    SignalTool.FakeAnalogStick(packet[12], packet[11], packet[10], packet[9], state, "Joy2x", "Joy2y");
                }
            }
            else if (packet.Length == 26 && packet[0] == 1)
            {
                int checksum        = (packet[24] >> 4) | packet[25];
                int checkedCheckSum = 0;
                for (int i = 0; i < 24; ++i)
                {
                    checkedCheckSum += packet[i] == 0 ? 0 : 1;
                }

                if (checksum == checkedCheckSum)
                {
                    state = new ControllerStateBuilder();

                    state.SetButton("left_button", packet[2] == 0x00);
                    state.SetButton("right_button", packet[1] == 0x00);

                    sbyte xVal = (sbyte)SignalTool.ReadByte(packet, 3);
                    sbyte yVal = (sbyte)SignalTool.ReadByte(packet, 11);

                    SignalTool.SetMouseProperties(xVal / -128.0f, yVal / 128.0f, state);
                }
            }
            else if (packet.Length == 19)
            {
                state = new ControllerStateBuilder();

                state.SetButton("left_button", packet[0] != 0x00);
                state.SetButton("right_button", packet[2] != 0x00);

                sbyte xVal = (sbyte)SignalTool.ReadByteBackwards(packet, 3);
                sbyte yVal = (sbyte)SignalTool.ReadByteBackwards(packet, 11);

                SignalTool.SetMouseProperties(xVal / -128.0f, yVal / 128.0f, state);
            }
            else if (packet.Length == 36)
            {
                byte[] reconstructedPacket = new byte[18];

                int j = 0;
                for (int i = 0; i < 18; ++i)
                {
                    reconstructedPacket[i] = (byte)((packet[j] >> 4) | packet[j + 1]);
                    j += 2;
                }

                byte[] polishedPacket = new byte[128];

                int checksum = 0;
                for (int i = 0; i < 16; ++i)
                {
                    checksum += reconstructedPacket[i];
                    for (int k = 0; k < 8; ++k)
                    {
                        polishedPacket[(i * 8) + k] = (byte)((reconstructedPacket[i] & (1 << k)) != 0 ? 1 : 0);
                    }
                }

                short sentChecksum = (short)((reconstructedPacket[17] << 8) | reconstructedPacket[16]);
                if (checksum == sentChecksum)
                {
                    state = new ControllerStateBuilder();

                    for (int i = 0; i < 128; ++i)
                    {
                        string scanCode = i.ToString("X").ToUpper();;
                        state.SetButton(scanCode, polishedPacket[i] != 0x00);
                    }
                }
            }

            return(state?.Build());
        }
Example #33
0
        public async Task <Classic> GetPlayerStandingsForClassicLeague(int leagueId, int gameweekId)
        {
            List <Player> allPlayers = await GetAllPlayers();

            List <Team> allTeams = await GetAllTeams();

            List <Game> allGames = await GetAllGames();

            EventStatus eventStatus = await GetEventStatus();

            List <GWPlayer> allGwPlayers = await GetAllGwPlayers(gameweekId);

            List <Game> gwGames = await GetGwGames(gameweekId);

            Classic l = new Classic();

            var PointsController = new PointsController(_httpClient);

            var response = await _httpClient.GetAsync($"leagues-classic/{leagueId}/standings");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            var leagueJSON = JObject.Parse(content);

            var leagueDetailsJSON = AllChildren(JObject.Parse(content))
                                    .First(c => c.Type == JTokenType.Object && c.Path.Contains("league"));

            l = leagueDetailsJSON.ToObject <Classic>();

            var temp = new JObject();

            if (gameweekId == 0)
            {
                temp = (JObject)leagueJSON["new_entries"];
            }
            else
            {
                temp = (JObject)leagueJSON["standings"];
            }

            l.Standings.has_next = (bool)temp["has_next"];
            l.Standings.page     = (int)temp["page"];

            var leaguePlayersJSON = AllChildren(temp)
                                    .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
                                    .Children <JObject>();

            foreach (JObject result in leaguePlayersJSON)
            {
                Result r = result.ToObject <Result>();
                l.Standings.results.Add(r);
            }

            int             leagueCount    = Convert.ToInt32(l.Standings.results.Count);
            List <Pick>     players        = new List <Pick>();
            List <Transfer> allGwTransfers = new List <Transfer>();

            foreach (var player in l.Standings.results)
            {
                GWTeam gwTeam = new GWTeam();
                gwTeam = await PointsController.PopulateGwTeam(gwTeam, gameweekId, player.entry);

                gwTeam = PointsController.AddPlayerSummaryDataToTeam(allPlayers, allTeams, allGames, gwTeam, player.entry, gameweekId);
                gwTeam = await PointsController.AddTransfersToGwTeam(allPlayers, gwTeam, player.entry, gameweekId);

                gwTeam.picks = PointsController.AddPlayerGameweekDataToTeam(gwGames, allGwPlayers, gwTeam.picks, gameweekId);
                gwTeam       = PointsController.AddAutoSubs(gwTeam, gwTeam.picks, player.entry, eventStatus, gameweekId);
                player.CompleteEntryHistory = await PointsController.GetCompleteEntryHistory(player.CompleteEntryHistory, player.entry);

                gwTeam.picks = PointsController.AddEstimatedBonusToTeamPicks(gwTeam.picks, eventStatus);
                var teamDetails = await PointsController.GetTeamInfo(player.entry);

                gwTeam.OverallRank = (int)teamDetails.summary_overall_rank;

                foreach (var p in gwTeam.picks)
                {
                    players.Add(p);
                    CalculatePlayersYetToPlay(gwTeam, p);
                }

                foreach (var transfer in gwTeam.GWTransfers)
                {
                    allGwTransfers.Add(transfer);
                }

                int gwpoints = PointsController.GetGameWeekPoints(gwTeam.picks, eventStatus);
                player.Last5GwPoints = player.CompleteEntryHistory.GetLast5GwPoints(gwpoints);
                //player.total += (gwpoints - player.event_total);
                //player.event_total += (gwpoints - player.event_total);
                player.total       = CalculatePlayerTotal(teamDetails, gwpoints);
                player.event_total = gwpoints;
                player.GWTeam      = gwTeam;
            }

            CalculateRankAndPFF(l);
            CalculatePlayersTallyForLeague(l, players, leagueCount);

            //if l.UserTeam = null && standings.hasnext = true then get logged in users team along with its rank in this league
            l.UserTeam = l.Standings.results.Find(x => x.entry == teamId);

            if (l.UserTeam == null && l.Standings.has_next && teamId != 0)
            {
                l.UserTeam = await GetUserTeamIfNotInRetrievedPage(l, PointsController, gwGames, allPlayers, allTeams, allGames, allGwPlayers, eventStatus, gameweekId, l.Standings.results.OrderByDescending(x => x.total).FirstOrDefault().total);
            }

            l.PlayersTally   = l.PlayersTally.ToList();
            l.AllGwTransfers = allGwTransfers;

            return(l);
        }