Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement leaderboard model/entity and functions #100

Merged

Conversation

beeguy74
Copy link
Contributor

@beeguy74 beeguy74 commented Nov 28, 2024

Closes #28
In this pull request i work on a dynamically updated leaderboard feature.

There is a conflict with new version of Alexandria which uses starknet 2.8.5 but dojo in project uses 2.7.0.
I imported previous version of Alexandria for starknet version 2.6.0 - it works but there are a lot of warnings on compilation/

Screenshot of build
But all tests are good 🆗
Screenshot of tests
**Migrations** applied as well
Screenshot of migrate

About solution: The main idea in maintaining Leaderboard up to date: after each changes into leaderboard, i sort entries array by rating. That way players with best rank always will be on top of the leaderboard and you can now rank of player by get his index in array.

This pull request introduces implementing the Leaderboard and LeaderboardEntry models with associated methods and tests.

Dependencies

  • Added alexandria_sorting tag=cairo-v2.6.0 to manipulate arrays.

New Module:

  • Added a new leaderboard module to the src/lib.cairo file to encapsulate the leaderboard functionality.

Module Structure:

  • Added a new module leaderboard to the project in src/lib.cairo.

Leaderboard Implementation:

  • Implemented the LeaderboardEntry and Leaderboard models in src/models/leaderboard.cairo, based on models from this PR
  • for LeaderboardEntry model I wrote an impl of PartialEq trait for searching entry by player_id and an impl of Partialord for sorting by score
  • Leaderboard is always in sorted state with best player in the 0 index. Score is calculated with this formula
    self.wins * 100 + self.highest_score - self.losses * 70. Leaderboard has methods for add, delete, and update entries.
  • Created tests for the Leaderboard and LeaderboardEntry models to ensure proper functionality with some negative scenarios as well

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a leaderboard system with functionalities to add, update, and remove player entries.
    • Added tournament management capabilities, including creating and registering players for tournaments.
  • Improvements

    • Enhanced leaderboard entry statistics calculation and retrieval methods.
    • Implemented error handling for leaderboard operations.
  • Testing

    • Added comprehensive unit tests for leaderboard functionalities to ensure reliability and correctness.

These updates enhance user interaction with leaderboard and tournament features in the application.

@beeguy74 beeguy74 force-pushed the feat-Implement-leaderboard-model branch from e50c23a to 623f676 Compare November 29, 2024 07:06
@beeguy74 beeguy74 marked this pull request as ready for review November 29, 2024 08:02
Copy link

coderabbitai bot commented Nov 29, 2024

Warning

Rate limit exceeded

@beeguy74 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 28 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 512b728 and 21d3948.

Walkthrough

This pull request introduces several significant changes to the bytebeasts application. A new dependency, alexandria_sorting, is added to the Scarb.toml file, linking it to a specific Git repository and tag. Additionally, multiple new JSON and TOML files are created to define data structures and models for a leaderboard system and leaderboard entries. These files introduce various structures, interfaces, and enumerations that encapsulate player statistics, leaderboard metadata, and tournament details. The code also includes a new module for the leaderboard within the source code, enhancing the functionality of the leaderboard system. Furthermore, a comprehensive suite of unit tests is added to validate the leaderboard functionality, ensuring that methods for managing entries, calculating scores, and retrieving data operate as expected. Overall, the changes aim to implement a robust leaderboard model and associated functionalities within the bytebeasts application.

Assessment against linked issues

Objective Addressed Explanation
Implement a leaderboard model that tracks and ranks players ( #28 )
Include functions for getting rank by player ID and top players ( #28 )
Use the alexandria library for dynamic leaderboard management ( #28 )

Possibly related PRs

Suggested labels

enhancement, actual: 2

Suggested reviewers

  • coxmars
  • danielcdz

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot]

This comment was marked as spam.

@beeguy74
Copy link
Contributor Author

@coxmars Hello sir, can you look at my PR... 🙏

@RolandoDrRobot
Copy link
Contributor

@beeguy74 at the end of the work, could you please add a pic of the outputs of

  • sozo build
  • sozo test
    to make sure all previous and current code is good? thank you!

…derboard's test file moved to test directory.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (5)
src/models/leaderboard.cairo (3)

25-41: Simplify PartialOrd implementation using derived traits

The manual implementation of PartialOrd for LeaderboardEntry can be simplified by deriving the trait automatically. This improves code readability and maintainability.

Apply this change:

- //trait for sorting by score
- impl LeaderboardEntryPartialOrd of PartialOrd<LeaderboardEntry> {
-     fn le(lhs: LeaderboardEntry, rhs: LeaderboardEntry) -> bool {
-         lhs.score <= rhs.score
-     }
-     fn ge(lhs: LeaderboardEntry, rhs: LeaderboardEntry) -> bool {
-         lhs.score >= rhs.score
-     }
-     fn lt(lhs: LeaderboardEntry, rhs: LeaderboardEntry) -> bool {
-         lhs.score < rhs.score
-     }
-     fn gt(lhs: LeaderboardEntry, rhs: LeaderboardEntry) -> bool {
-         lhs.score > rhs.score
-     }
- }
+ #[derive(PartialOrd)]

118-118: Typographical error in comment

There's a typo in the comment on line 118: "addning" should be "adding".

Apply this fix:

- // addning new wins, losses and changing highest score to an old entry
+ // adding new wins, losses and changing highest score to an old entry

140-156: Inefficient search in get_index_by_player_id

Creating a dummy LeaderboardEntry with default values to find the index by player_id may lead to inefficiencies and potential bugs if fields other than player_id are considered in equality checks in the future. Consider iterating over the entries and comparing player_id directly.

Apply this change:

- let entry = LeaderboardEntry {
-     player_id: player_id,
-     player_name: '',
-     score: 0,
-     wins: 0,
-     losses: 0,
-     highest_score: 0,
-     is_active: false,
- };
- match self.entries.index_of(entry) {
+ let mut index = 0;
+ let mut found = false;
+ while (index < self.entries.len()) {
+     if self.entries.at(index).player_id == player_id {
+         found = true;
+         break;
+     };
+     index += 1;
+ };
+ if found {
+     Result::Ok(index)
+ } else {
src/tests/test_leaderboard.cairo (2)

10-10: Remove unused import bubble_sort_elements

The import of bubble_sort_elements is not used in the test file. Removing it will clean up the code.

Apply this change:

- use alexandria_sorting::bubble_sort::bubble_sort_elements;

37-37: Check the result of add_entry in tests

In test_add_single_entry, the result of leaderboard.add_entry(entry) is stored in res but not used meaningfully. Consider asserting that the operation was successful to validate the test.

Apply this change:

let res = leaderboard.add_entry(entry);
+ assert_eq!(res.is_ok(), true, "Failed to add entry");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d1508ad and 619ddc7.

📒 Files selected for processing (3)
  • src/lib.cairo (1 hunks)
  • src/models/leaderboard.cairo (1 hunks)
  • src/tests/test_leaderboard.cairo (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib.cairo
🔇 Additional comments (5)
src/models/leaderboard.cairo (4)

159-169: Inefficient sorting with bubble sort

Using bubble sort (bubble_sort_elements) is inefficient for large datasets due to its O(n²) time complexity. Consider using a more efficient sorting algorithm like quicksort or mergesort to improve performance.


187-200: Optimize remove_entry to avoid reconstructing the array

The remove_entry method reconstructs the array after removal, which is inefficient. Consider using an in-place removal method or swapping the element to remove with the last element and popping it.


202-213: Inefficient update_entry method

The update_entry method removes and re-adds an entry, which is not optimal. Updating the entry in place would be more efficient.


221-242: ⚠️ Potential issue

Potential off-by-one error in get_slice method

The check if (end > self.entries.len()) might allow end to equal self.entries.len(), leading to an out-of-bounds access since arrays are zero-indexed. Adjust the condition to prevent this.

Apply this fix:

- if (end > self.entries.len()) {
+ if (end > self.entries.len() || end == self.entries.len()) {

Or more succinctly:

- if (end > self.entries.len()) {
+ if (end >= self.entries.len()) {

Likely invalid or redundant comment.

src/tests/test_leaderboard.cairo (1)

223-223: Potential overflow in score calculation

When upgrading entry stats, adding entry3.wins and new_wins could result in an overflow if the totals exceed u32::MAX. Consider adding checks or using larger integer types to prevent this.

Run the following script to verify the maximum values:

src/models/leaderboard.cairo Show resolved Hide resolved
@beeguy74
Copy link
Contributor Author

beeguy74 commented Dec 2, 2024

after my last commit: tests are ok 👍

Screenshot of tests

build is ok, but with some warnings about old cairo version, as i mentioned in PR description

Screenshot of build

migration applied as well

Screenshot of migrate

If you are satisfied with my work, please mark the PR as ready, sir!

Copy link
Contributor

@coxmars coxmars left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, solid contribution! 🚀 Just resolve the conflicts @beeguy74

saimeunt and others added 3 commits December 3, 2024 15:27
* Add tests for tournament_system

* Quickfixes

* sozo build
…derboard's test file moved to test directory.
@beeguy74 beeguy74 force-pushed the feat-Implement-leaderboard-model branch from 95e8ec1 to 770d8f0 Compare December 3, 2024 14:33
coderabbitai[bot]

This comment was marked as spam.

@beeguy74 beeguy74 marked this pull request as draft December 3, 2024 14:45
@beeguy74 beeguy74 marked this pull request as ready for review December 3, 2024 14:45
@beeguy74 beeguy74 force-pushed the feat-Implement-leaderboard-model branch from 512b728 to 21d3948 Compare December 3, 2024 14:49
@coxmars coxmars merged commit d1aeefa into ByteBuildersLabs:main Dec 3, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement leaderboard model/entity and functions
7 participants