Skip to content

Commit

Permalink
Added farming weight leaderboard support
Browse files Browse the repository at this point in the history
  • Loading branch information
hannibal002 committed Mar 12, 2023
1 parent 1b9aca4 commit 6749894
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 35 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
+ Added **Custom Keybinds** - Use custom keybinds while having a farming tool or Daedalus Axe in the hand in the garden.
+ Added Desk shortcut in SkyBlock Menu.
+ Added **Garden Level Display** - Show the current garden level and progress to the next level.
+ Added **Farming Weight**, provided by the elite skyblock farmers.
+ Added **Farming Weight and Leaderboard**, provided by the elite skyblock farmers.


### Features from other Mods
Expand Down
2 changes: 1 addition & 1 deletion FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@
+ **Optimal Speed** - Show the optimal speed for your current tool in the hand. (Ty MelonKingDE for the values)
+ Desk shortcut in SkyBlock Menu.
+ **Garden Level Display** - Show the current garden level and progress to the next level.
+ **Farming Weight**, provided by the elite skyblock farmers.
+ **Farming Weight and Leaderboard**, provided by the elite skyblock farmers.

## Commands
- /wiki (using hypixel-skyblock.fandom.com instead of Hypixel wiki)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,13 @@ public class Garden {
@ConfigAccordionId(id = 10)
public Position eliteFarmingWeightPos = new Position(-370, -167, false, true);

@Expose
@ConfigOption(name = "Leaderboard Ranking", desc = "Show your position in the farming weight leaderboard. " +
"Only if your farming weight is high enough! Updates every 10 minutes.")
@ConfigEditorBoolean
@ConfigAccordionId(id = 10)
public boolean eliteFarmingWeightLeaderboard = false;

@Expose
@ConfigOption(name = "Plot Price", desc = "Show the price of the plot in coins when inside the Configure Plots inventory.")
@ConfigEditorBoolean
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/at/hannibal2/skyhanni/data/HyPixelData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class HyPixelData {
var stranded = false
var bingo = false

var profile = ""
var profileName = ""

fun readSkyBlockArea(): String {
return ScoreboardData.sidebarLinesFormatted
Expand Down Expand Up @@ -64,13 +64,13 @@ class HyPixelData {
val message = event.message.removeColor().lowercase()
if (message.startsWith("your profile was changed to:")) {
val newProfile = message.replace("your profile was changed to:", "").replace("(co-op)", "").trim()
profile = newProfile
profileName = newProfile
ProfileJoinEvent(newProfile).postAndCatch()
}
if (message.startsWith("you are playing on profile:")) {
val newProfile = message.replace("you are playing on profile:", "").replace("(co-op)", "").trim()
if (profile == newProfile) return
profile = newProfile
if (profileName == newProfile) return
profileName = newProfile
ProfileJoinEvent(newProfile).postAndCatch()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import at.hannibal2.skyhanni.api.CollectionAPI
import at.hannibal2.skyhanni.data.HyPixelData
import at.hannibal2.skyhanni.events.CollectionUpdateEvent
import at.hannibal2.skyhanni.events.GuiRenderEvent
import at.hannibal2.skyhanni.events.ProfileJoinEvent
import at.hannibal2.skyhanni.utils.APIUtil
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.LorenzUtils.round
Expand All @@ -23,7 +24,7 @@ class EliteFarmingWeight {
@SubscribeEvent
fun onCollectionUpdate(event: CollectionUpdateEvent) {
if (isEnabled()) {
breakBlocksToTryAgain = false
farmCropsToUpdate = false
update()
}
}
Expand All @@ -39,73 +40,133 @@ class EliteFarmingWeight {
fun onWorldChange(event: WorldEvent.Load) {
if (apiError) {
apiError = false
breakBlocksToTryAgain = true
farmCropsToUpdate = true
if (config.eliteFarmingWeightDisplay) {
update()
}
}
}

@SubscribeEvent
fun onProfileJoin(event: ProfileJoinEvent) {
weightApiCache = null
lbApiCache = null
display = "§6Farming Weight§7: §cFarm crops to update!"
}

companion object {
private val LB_POSTION_UPDATE_INTERVAL = 600_000 // 10 minutes

private val config get() = SkyHanniMod.feature.garden
private val extraCollection = mutableMapOf<String, Long>()

private var display = "§6Farming Weight§7: §eLoading.."
private var profileId = ""
private var lastPositionUpdate = 0L
private var weightApiCache: JsonObject? = null
private var lbApiCache: JsonObject? = null
private var lbApiDirty = false
private var apiError = false
private var farmCropsToUpdate = false

private fun isEnabled() = GardenAPI.inGarden() && config.eliteFarmingWeightDisplay

fun addCrop(crop: String, diff: Int) {
val old = extraCollection[crop] ?: 0L
extraCollection[crop] = old + diff
breakBlocksToTryAgain = false
farmCropsToUpdate = false
if (isEnabled()) {
update()
}
}

private fun update() = SkyHanniMod.coroutineScope.launch {
display = "§6Farming Weight§7: " + if (apiError) {
"§cAPI error!"
} else if (breakBlocksToTryAgain) {
"§cBreak blocks to try again!"
} else {
val collectionWeight = calculateCollectionWeight()
val cropWeight = collectionWeight.values.sum()

try {
val totalWeight = cropWeight + getBonusWeight()
val format = DecimalFormat("#,##0.00").format(totalWeight)
"§e$format"
} catch (e: Exception) {
apiError = true
LorenzUtils.error("[SkyHanni] Failed to load farming weight data from elitebot.dev! please report this on discord!")
e.printStackTrace()
"§cAPI error!"
val weight = getWeight()
val leaderBoard = if (config.eliteFarmingWeightLeaderboard) getLeaderBoard() else ""

display = "§6Farming Weight§7: $weight$leaderBoard"
}

private suspend fun getLeaderBoard() = if (apiError || farmCropsToUpdate) {
""
} else {
try {
val position = getLBPosition()
if (position != -1) {
val format = DecimalFormat("###,##0").format(position)
" §7[§b#$format§7]"
} else {
""
}
} catch (e: Exception) {
apiError = true
LorenzUtils.error("[SkyHanni] Failed to load farming weight data from elitebot.dev! please report this on discord!")
e.printStackTrace()
""
}
}

private suspend fun getLBPosition(): Int {
if (System.currentTimeMillis() > lastPositionUpdate + LB_POSTION_UPDATE_INTERVAL) {
lbApiDirty = true
lastPositionUpdate = System.currentTimeMillis()
}

return getLBPositionAPI()["rank"].asInt
}

private suspend fun getLBPositionAPI(): JsonObject {
if (!lbApiDirty) {
lbApiCache?.let { return it }
}
lbApiDirty = false

val uuid = Minecraft.getMinecraft().thePlayer.uniqueID.toString().replace("-", "")
val url = "https://elitebot.dev/api/leaderboard/rank/weight/farming/$uuid/$profileId"
val result = withContext(Dispatchers.IO) { APIUtil.getJSONResponse(url) }.asJsonObject
lbApiCache = result
return result
}

private suspend fun getWeight() = if (apiError) {
"§cAPI error!"
} else if (farmCropsToUpdate) {
"§cFarm crops to update!"
} else {
val collectionWeight = calculateCollectionWeight()
val cropWeight = collectionWeight.values.sum()

try {
val totalWeight = cropWeight + getBonusWeight()
val format = DecimalFormat("#,##0.00").format(totalWeight)
"§e$format"
} catch (e: Exception) {
apiError = true
LorenzUtils.error("[SkyHanni] Failed to load farming weight data from elitebot.dev! please report this on discord!")
e.printStackTrace()
"§cAPI error!"
}
}

private suspend fun getBonusWeight(): Int {
for (profileEntry in getApiResult()["profiles"].asJsonObject.entrySet()) {
for (profileEntry in getWeightApi()["profiles"].asJsonObject.entrySet()) {
val profile = profileEntry.value.asJsonObject
val profileName = profile["cute_name"].asString.lowercase()
if (profileName == HyPixelData.profile) {
if (profileName == HyPixelData.profileName) {
profileId = profileEntry.key
return profile["farming"].asJsonObject["bonus"].asInt
}
}
return 0
}

private var apiCache: JsonObject? = null
private var apiError = false
private var breakBlocksToTryAgain = false

private suspend fun getApiResult(): JsonObject {
apiCache?.let { return it }
private suspend fun getWeightApi(): JsonObject {
weightApiCache?.let { return it }

val uuid = Minecraft.getMinecraft().thePlayer.uniqueID.toString().replace("-", "")
val url = "https://elitebot.dev/api/weight/$uuid"
val result = withContext(Dispatchers.IO) { APIUtil.getJSONResponse(url) }.asJsonObject
apiCache = result
weightApiCache = result
return result
}

Expand Down

0 comments on commit 6749894

Please sign in to comment.