From d3906e74fa62adb4f3d47d22dc322bcb68e9907e Mon Sep 17 00:00:00 2001 From: Ryan Date: Mon, 17 May 2021 16:41:19 +0800 Subject: [PATCH] Added leaderboard --- main.go | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 6fc41bf..0cf39a6 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( "os" "os/user" "runtime" + "sort" "strconv" "strings" "time" @@ -38,6 +39,13 @@ func reverseArray(arr []string) []string { return arr } +func reverseIntArray(arr []int) []int { + for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 { + arr[i], arr[j] = arr[j], arr[i] + } + return arr +} + func main() { databasePath := "." userObject, errorObject := user.Current() @@ -78,7 +86,7 @@ func main() { resetValues = true } else if argument == "help" { showHelpPage = true - } else if argument == "list" { + } else if argument == "list" || argument == "leaderboard" || argument == "lb" { showPlayerList = true } else if argument == "submit" { submitPlayer = true @@ -86,10 +94,10 @@ func main() { } if showHelpPage { - helpText := "ok - ok\nok stats - shows your statistics\nok reset - resets your statistics\nok list - shows a list of new players\nok submit - submit your profile to the player list\n" + helpText := "ok - ok\nok stats - shows your statistics\nok reset - resets your statistics\nok leaderboard - shows the OK leaderboard\nok submit - submit your profile to the player list\n" color.Printf(helpText) } else if showPlayerList { - fmt.Println("Fetching player list...") + fmt.Println("Fetching leaderboard...") httpResponse, errorObject := http.Get("http://ok-server.herokuapp.com/list") if errorObject != nil { fmt.Println("\rFailed to fetch player list") @@ -102,13 +110,26 @@ func main() { return } _ = json.Unmarshal(responseBytes, &response) + numberArray := []int{} + playerList := make(map[int]string) if response.Count > 0 { fmt.Println("") + for _, player := range response.Players { - color.Printf("%v - %v OKs\n", player.Name, player.Score) + numberArray = append(numberArray, player.Score) + playerList[player.Score] = player.Name + } + sort.Ints(numberArray) + numberArray = reverseIntArray(numberArray) + for index, number := range numberArray { + playerName := playerList[number] + color.Printf("%v. %v - %v OKs\n", index+1, playerName, number) + if index == 9 { + return + } } } else { - fmt.Println("There are no players on the OK list...") + fmt.Println("There are no players on the OK leaderboard...") } return } else if submitPlayer {