Last active
February 26, 2017 09:14
-
-
Save Georgi87/95a80894c9c682faa217af9dcb3278df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity 0.4.9; | |
contract Leaderboard { | |
mapping (uint => User) leaderboard; | |
struct User { | |
address user; | |
uint score; | |
} | |
function addScore(uint score) returns (bool) { | |
if (leaderboard[9].score >= score) | |
// user didn't make it into top 10 | |
return false; | |
for (uint i=0; i<10; i++) { | |
if (leaderboard[i].score < score) { | |
// resort | |
if (leaderboard[i].user != msg.sender) { | |
bool duplicate = false; | |
for (uint j=i+1; j<10; j++) { | |
if (leaderboard[j].user == msg.sender) { | |
duplicate = true; | |
delete leaderboard[j]; | |
} | |
if (duplicate) | |
leaderboard[j] = leaderboard[j+1]; | |
else | |
leaderboard[j] = leaderboard[j-1]; | |
} | |
} | |
// add new highscore | |
leaderboard[i] = User({ | |
user: msg.sender, | |
score: score | |
}); | |
return true; | |
} | |
if (leaderboard[i].user == msg.sender) | |
// user is alrady in list with higher or equal score | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment