Beispiel #1
0
    public IEnumerator GetRanking(ScoreQuery localEntryData, Action <ScoreResponse> onSuccess, Action onFailure)
    {
        Debug.Log("getRank: " + localEntryData.guid);
        string queryJson = JsonConvert.SerializeObject(localEntryData);

        byte[] queryBytes = new UTF8Encoding().GetBytes(queryJson);
        Debug.Log("getRank: " + queryJson);
        using (UnityWebRequest request = new UnityWebRequest("https://us-central1-pok-game.cloudfunctions.net/getRankingRequest", "POST"))
        {
            request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(queryBytes);
            request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return(request.SendWebRequest());

            if (request.isNetworkError == true)
            {
                Debug.LogError("An error has occured while puting Rank request: " + request.error);
                onFailure?.Invoke();
            }
            else
            {
                Debug.Log($"Successfully retrieved Ranks: {request.downloadHandler.text}");
                ScoreResponse data = JsonConvert.DeserializeObject <ScoreResponse>(request.downloadHandler.text);
                onSuccess?.Invoke(data);
            }
        }
    }
        private static readonly string _imageFolderPath = "path/to/imageFolder";        // TODO: Enter the path to your Image Folder

        public static void Main(string[] args)
        {
            GameSettingsInfo result = Api.InitGame(_apiKey);
            string           gameId = result.GameId;
            int roundsLeft          = result.NumberOfRounds;

            Console.WriteLine($"Starting a new game with id: {gameId}");
            Console.WriteLine($"The game has {roundsLeft} rounds and {result.ImagesPerRound} images per round");
            while (roundsLeft > 0)
            {
                Console.WriteLine($"Starting new round, {roundsLeft} rounds left");
                var           solution   = new Solution();
                var           zip        = Api.GetImages(_apiKey);
                List <string> imageNames = SolutionHelper.SaveImagesToDisk(zip, _imageFolderPath);
                foreach (string name in imageNames)
                {
                    var imagePath     = _imageFolderPath + "/" + name;
                    var imageSolution = ImageAnalyzer(imagePath);
                    solution.Add(name, imageSolution);
                }
                ScoreResponse response = Api.ScoreSolution(_apiKey, solution.GetRequest());
                SolutionHelper.PrintErrors(response);
                SolutionHelper.PrintScores(response);
                roundsLeft = response.RoundsLeft;
            }
            SolutionHelper.ClearImagesFromFolder(_imageFolderPath);
        }
Beispiel #3
0
    IEnumerator GetScores()
    {
        scoresLoading = true;

        UnityWebRequest www = UnityWebRequest.Get(API_URL + "/scores");

        yield return(www.SendWebRequest());

        scoresLoading = false;
        if (www.result != UnityWebRequest.Result.Success)
        {
            OnScoresError(www.error);
        }
        else
        {
            OnScoresError("");

            ScoreResponse scoreResponse = JsonUtility.FromJson <ScoreResponse>(www.downloadHandler.text);

            if (scoreResponse != null && scoreResponse.values != null)
            {
                currentScores = new List <ScoreOutput>(scoreResponse.values);
                currentScores.Sort((a, b) => - a.elapsedTime.CompareTo(b.elapsedTime));
            }
            else
            {
                currentScores = new List <ScoreOutput>();
            }

            RefreshScores(currentScores);
        }
    }
Beispiel #4
0
 /**
  * <summary>Prints the scores for this round</summary>
  */
 public static void PrintScores(ScoreResponse response)
 {
     Console.WriteLine($"Total score: {response.TotalScore}");
     foreach (var imageScore in response.ImageScores)
     {
         Console.WriteLine($"Image {imageScore.ImageName,25} got a score of {imageScore.Score}");
     }
 }
Beispiel #5
0
 public void GetRanking(ScoreQuery localEntryData)
 {
     StartCoroutine(FirebaseManager.Instance.GetRanking(localEntryData, (response) =>
     {
         this.response = response;
     }, () =>
     {
         Debug.LogWarning("Couldn't get leaderboards");
     }));
 }
Beispiel #6
0
        /// <summary>
        ///     the classic 4,4,5,5,6 hand
        /// </summary>
        public async Task TestDoubleRuns()
        {
            try
            {
                string url = BuildUrl("/cribbage/scorehand/FiveOfHearts,FiveOfClubs,FourOfSpades,SixOfClubs/FourOfDiamonds/false");
                HttpResponseMessage response = await _client.GetAsync(url);

                AssertTrue(response.IsSuccessStatusCode);
                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();

                    ScoreResponse scoreRes = JsonConvert.DeserializeObject <ScoreResponse>(jsonResponse);
                    AssertEqual(24, scoreRes.TotalScore);
                    AssertEqual(10, scoreRes.Scores.Count);
                    int runs    = 0;
                    int pairs   = 0;
                    int fifteen = 0;
                    foreach (var score in scoreRes.Scores)
                    {
                        switch (score.ScoreName)
                        {
                        case ScoreName.Run:
                            runs++;
                            AssertEqual(3, score.Cards.Count);
                            break;

                        case ScoreName.Fifteen:
                            fifteen++;
                            AssertEqual(3, score.Cards.Count);
                            break;

                        case ScoreName.Pair:
                            AssertEqual(2, score.Cards.Count);
                            pairs++;
                            break;

                        default:
                            AssertTrue(false, "Unexpected score name in Score");
                            break;
                        }
                    }

                    AssertEqual(4, runs);
                    AssertEqual(2, pairs);
                    AssertEqual(4, fifteen);
                }
            }
            catch (Exception e)
            {
                OutputError("FAILED " + e.Message);
            }

            OutputInfo("PASSED");
        }
Beispiel #7
0
        /**
         * <summary>Prints any errors encountered in the solution</summary>
         */
        public static void PrintErrors(ScoreResponse response)
        {
            if (response.Errors == null || response.Errors.Count == 0)
            {
                return;
            }

            Console.WriteLine("Encountered some errors with the solution:");
            foreach (string error in response.Errors)
            {
                Console.WriteLine(error);
            }
        }
        public static ScoreResponse ToScoreResponse(this Score value)
        {
            var scoreResponse = new ScoreResponse
            {
                User       = value.User,
                Lenght     = value.Lenght,
                Deck       = Newtonsoft.Json.JsonConvert.DeserializeObject <List <int> >(value.Deck),
                IsVerified = (value.Verified != null),
                Players    = value.Players
            };

            return(scoreResponse);
        }
Beispiel #9
0
        /// <summary>
        ///     2 pairs and some fifteens.  also has Nibs
        /// </summary>

        public async Task TestPairsAsync()
        {
            string url = BuildUrl("/cribbage/scorehand/FiveOfHearts,FiveOfClubs,FourOfSpades,JackOfDiamonds/FourOfDiamonds/false");
            HttpResponseMessage response = await _client.GetAsync(url);

            Debug.Assert(response.IsSuccessStatusCode);
            if (response.IsSuccessStatusCode)
            {
                string jsonResponse = await response.Content.ReadAsStringAsync();

                ScoreResponse scoreRes = JsonConvert.DeserializeObject <ScoreResponse>(jsonResponse);
                AssertEqual(9, scoreRes.TotalScore);
                AssertEqual(5, scoreRes.Scores.Count);
                int nibsCount = 0;
                int pairs     = 0;
                int fifteen   = 0;
                foreach (var score in scoreRes.Scores)
                {
                    switch (score.ScoreName)
                    {
                    case ScoreName.HisNibs:
                        nibsCount++;
                        AssertEqual(2, score.Cards.Count);
                        break;

                    case ScoreName.Fifteen:
                        fifteen++;
                        AssertEqual(2, score.Cards.Count);
                        break;

                    case ScoreName.Pair:
                        AssertEqual(2, score.Cards.Count);
                        pairs++;
                        break;

                    default:
                        AssertTrue(false, "Unexpected score name in Score");
                        break;
                    }
                }

                AssertEqual(1, nibsCount);
                AssertEqual(2, pairs);
                AssertEqual(2, fifteen);
            }

            OutputInfo("PASSED");
        }
Beispiel #10
0
    private IEnumerator Populate(ScoreResponse response, float fadeDuration)
    {
        waitingForScoresText.DOFade(0, fadeDuration);
        entriesCanvasGroup.DOFade(1, fadeDuration);
        List <ScoreEntryData> orderedEntries = response.entries.OrderBy(x => x.rank).ToList();

        for (int i = 0; i < orderedEntries.Count; i++)
        {
            ScoreEntryData entryData = orderedEntries[i];
            entries[i].SetScoreEntryData(entryData, i == response.senderIndex, fadeDuration);
            yield return(new WaitForSeconds(fadeDuration / 2f));
        }
        yield return(new WaitForSeconds(fadeDuration * 10f));

        menuManager.Hide();
    }
Beispiel #11
0
        public async Task <ActionResult> setScore(string pessoaId, int score)
        {
            ScoreResponse response = new ScoreResponse();

            try
            {
                MyHttp myHttp = new MyHttp(@"https://hackathonbtpapi.azurewebsites.net/api/");
                var    result = await myHttp.Post("Score/Pontuacao/", new { PessoaId = pessoaId, Pontuacao = score });

                response.ResultCode = (int)HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                response.ResultCode = (int)HttpStatusCode.InternalServerError;
            }

            return(View("~/Views/Home/DetalheAtividade.cshtml?validado=true"));
        }
Beispiel #12
0
    public IEnumerator Show(float fadeDuration)
    {
        canvasGroup.DOFade(1, fadeDuration);
        float waitTimeStart = Time.time;

        if (response == null)
        {
            ShowWaitingForScores(fadeDuration);
            yield return(new WaitWhile(() => response == null && Time.time - waitTimeStart < maxAwaitTime));
        }
        if (response != null)
        {
            StartCoroutine(Populate(response, fadeDuration));
            response = null;
        }
        else
        {
            StartCoroutine(ShowTimeout(fadeDuration));
        }
    }
Beispiel #13
0
    async Task <ScoreResponse> GetScoreResponse()
    {
        await Task.Delay(0);

        var res = new ScoreResponse();

        var flattened = GetFlattened();

        //todo: for speed analyse flattened to see if Count(DISTINCT mimeType) > 1 - if mimeType only ever null OR jpg, then don't include in combinations (repeat for all other fields)
        //todo: split photos and video duplication check

        var lGroupByCombinations = Utils.GetAllCombinations <GroupByProperty>().ToList();

        if (type == MediaType.Photo)
        {
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.fps));
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.status));
            flattened = flattened.Where(p => p.mimeType.StartsWith("image", StringComparison.OrdinalIgnoreCase)).ToList();
        }
        if (type == MediaType.Video)
        {
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.focalLength));
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.apertureFNumber));
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.isoEquivalent));
            lGroupByCombinations.RemoveAll(p => p.HasFlag(GroupByProperty.exposureTime));
            flattened = flattened.Where(p => p.mimeType.StartsWith("video", StringComparison.OrdinalIgnoreCase)).ToList();
        }

        //flattened = flattened.Take(2_000).ToList();//make testing faster!

        var msg = $"Now processing {flattened.Count} records against {lGroupByCombinations.Count} property combinations.";



        var dtStart           = DateTime.UtcNow;
        var estimatedDuration = TimeSpan.FromMilliseconds(lGroupByCombinations.Count * 25);

        if (false)
        {
            using var pbar = new ProgressBar(lGroupByCombinations.Count, msg, pbarOptions)
                  {
                      EstimatedDuration = estimatedDuration
                  };
            foreach (var myGroup in lGroupByCombinations)
            {
                CalculateScore(myGroup);
                UpdateProgress(pbar, myGroup);
            }
        }
        else
        {
            var cts = new CancellationTokenSource();

            var po = new ParallelOptions {
                CancellationToken = cts.Token, MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            // Run a task so that we can cancel from another thread.
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            Task.Factory.StartNew(() =>
            {
                if (Console.ReadKey().KeyChar == 'c')
                {
                    cts.Cancel();
                }
                Console.WriteLine("press any key to exit");
            });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            try
            {
                using var pbar = new ProgressBar(lGroupByCombinations.Count, msg, pbarOptions)
                      {
                          EstimatedDuration = estimatedDuration
                      };
                Parallel.ForEach(lGroupByCombinations, po, (myGroup) =>
                {
                    //using (var child = pbar.Spawn(1, myGroup.ToString(), childOptions))
                    //{
                    CalculateScore(myGroup);
                    UpdateProgress(pbar, myGroup);
                    //    child.Tick();
                    //todo: can't exit early now with progress bar?
                    po.CancellationToken.ThrowIfCancellationRequested();
                    //}
                    //pbar.Tick();
                });
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                cts.Dispose();
            }
        }
        return(res);

        void CalculateScore(GroupByProperty myGroup)
        {
            Interlocked.Increment(ref iteration);
            //https://stackoverflow.com/questions/33286297/linq-groupby-with-a-dynamic-group-of-columns
            var results = flattened
                          .GroupBy(item =>
                                   new
            {
                filename     = myGroup.HasFlag(GroupByProperty.filename) ? item.filename : null,
                mimeType     = myGroup.HasFlag(GroupByProperty.mimeType) ? item.mimeType : null,
                dimensions   = myGroup.HasFlag(GroupByProperty.dimensions) ? $"{item.height}x{item.width}" : null,
                creationTime = myGroup.HasFlag(GroupByProperty.creationTime) ? item.creationTime : DateTime.MinValue,
                description  = myGroup.HasFlag(GroupByProperty.description) ? item.description : null,
                //photo
                focalLength     = myGroup.HasFlag(GroupByProperty.focalLength) ? item.focalLength : float.MinValue,
                apertureFNumber = myGroup.HasFlag(GroupByProperty.apertureFNumber) ? item.apertureFNumber : float.MinValue,
                isoEquivalent   = myGroup.HasFlag(GroupByProperty.isoEquivalent) ? item.isoEquivalent : int.MinValue,
                exposureTime    = myGroup.HasFlag(GroupByProperty.exposureTime) ? item.exposureTime : null,
                //video
                fps    = myGroup.HasFlag(GroupByProperty.fps) ? item.fps : float.MinValue,
                status = myGroup.HasFlag(GroupByProperty.status) ? item.status : null,
                //photo & video
                cameraMake  = myGroup.HasFlag(GroupByProperty.cameraMake) ? item.cameraMake : null,
                cameraModel = myGroup.HasFlag(GroupByProperty.cameraModel) ? item.cameraModel : null,
                //collections
                albumIds             = myGroup.HasFlag(GroupByProperty.albumIds) ? item.albumIds : null,
                contentCategoryTypes = myGroup.HasFlag(GroupByProperty.contentCategoryTypes) ? item.contentCategoryTypes : null,
            })
                          .Select(g => new
            {
                //g.Key.filename,
                //g.Key.mimeType,
                //g.Key.dimensions,
                //g.Key.creationTime,
                //g.Key.description,

                //g.Key.focalLength,
                //g.Key.apertureFNumber,
                //g.Key.isoEquivalent,
                //g.Key.exposureTime,

                //g.Key.fps,
                //g.Key.status,

                //g.Key.cameraMake,
                //g.Key.cameraModel,

                //g.Key.albumIds,
                //g.Key.contentCategoryTypes,
                //quantity = i.Sum()
                medaItemIds = g.Select(p => p.id).ToList(),
                count       = g.Count()
            }).Where(p => p.count > 1).AsParallel().ToList();

            //res.dScore2.AddOrUpdate(myGroup, results.medaItemIds, (k, v) => v = result.medaItemIds);

            //Parallel.ForEach ??
            foreach (var result in results)
            {//todo: we can also record on what properties/enums the matches occurred (those properties could appear in an enum checkbox list?)
                foreach (var id in result.medaItemIds)
                {
                    _ = res.dScore.AddOrUpdate(id, new MediaItemScore {
                        count = 1, propertyMatches = myGroup
                    }, (k, v) =>
                    {
                        v.count++;
                        v.propertyMatches |= myGroup;
                        return(v);
                    });
                }
                //record a count of matches per bitmask
                _ = res.dStats.AddOrUpdate(myGroup, result.medaItemIds.Count, (k, v) =>
                {
                    v = result.medaItemIds.Count;
                    return(v);
                });
                //_ = res.dScore2.AddOrUpdate(myGroup, new HashSet<string>(result.medaItemIds), (k, v) =>
                //{
                //    //v.AddRange(result.medaItemIds);
                //    foreach (var _id in result.medaItemIds)
                //    {
                //        if (!v.Contains(_id))
                //            v.Add(_id);
                //        else
                //            Debugger.Break();
                //    }
                //    return v;
                //});
            }
        }

        void UpdateProgress(ProgressBar pbar, GroupByProperty myGroup)
        {
            //pbar.Tick();
            pbar.Tick($"Iteration {iteration} of {lGroupByCombinations.Count} completed, {myGroup}");
            if (Interlocked.Read(ref iteration) % 25 == 0)
            {
                var tsTaken            = DateTime.UtcNow.Subtract(dtStart).TotalMilliseconds;
                var timePerCombination = tsTaken / iteration;
                pbar.EstimatedDuration = TimeSpan.FromMilliseconds((lGroupByCombinations.Count - iteration) * timePerCombination);
            }
        }
    }
 protected virtual void AssertScore(ScoreResponse score)
 {
     Assert.IsTrue(score.FinalScore > 0, $"Run failed to get a positive score");
     Assert.IsTrue(score.FinalPopulation > 0, $"Run failed to maintain population in the city");
 }
Beispiel #15
0
        /// <summary>
        ///     this will test 4 and 5 card flushes for both crib and regular hand
        /// </summary>
        public async Task TestFlush()
        {
            try
            {
                string url = BuildUrl("/cribbage/scorehand/AceOfClubs,NineOfClubs,ThreeOfClubs,SevenOfClubs/KingOfSpades/false");
                HttpResponseMessage response = await _client.GetAsync(url);

                AssertTrue(response.IsSuccessStatusCode);
                if (response.IsSuccessStatusCode)
                {
                    string jsonResponse = await response.Content.ReadAsStringAsync();

                    ScoreResponse scoreRes = JsonConvert.DeserializeObject <ScoreResponse>(jsonResponse);
                    AssertEqual(4, scoreRes.TotalScore);
                    AssertEqual(1, scoreRes.Scores.Count);
                    int flush = 0;
                    foreach (var score in scoreRes.Scores)
                    {
                        switch (score.ScoreName)
                        {
                        case ScoreName.Flush:
                            AssertEqual(4, score.Cards.Count);
                            flush++;
                            break;

                        default:
                            AssertTrue(false, "Unexpected score name in Score");
                            break;
                        }
                    }

                    AssertEqual(1, flush);

                    url      = BuildUrl("/cribbage/scorehand/AceOfClubs,NineOfClubs,ThreeOfClubs,SevenOfClubs/KingOfSpades/true");
                    response = await _client.GetAsync(url);

                    AssertTrue(response.IsSuccessStatusCode);
                    if (response.IsSuccessStatusCode)
                    {
                        jsonResponse = await response.Content.ReadAsStringAsync();

                        scoreRes = JsonConvert.DeserializeObject <ScoreResponse>(jsonResponse);
                        AssertEqual(0, scoreRes.TotalScore);
                    }

                    url      = BuildUrl("/cribbage/scorehand/AceOfClubs,NineOfClubs,ThreeOfClubs,SevenOfClubs/KingOfClubs/true");
                    response = await _client.GetAsync(url);

                    AssertTrue(response.IsSuccessStatusCode);
                    if (response.IsSuccessStatusCode)
                    {
                        jsonResponse = await response.Content.ReadAsStringAsync();

                        scoreRes = JsonConvert.DeserializeObject <ScoreResponse>(jsonResponse);
                        AssertEqual(5, scoreRes.TotalScore);
                        AssertEqual(1, scoreRes.Scores.Count);
                    }
                }
            }
            catch (Exception e)
            {
                OutputError("FAILED " + e.Message);
            }
            OutputInfo("PASSED");
        }