aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/ScoreboardUtil.kt
blob: d94eb545cb1322dd5bf314f910a3a5e8634cd5fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package moe.nea.firmament.util

import java.util.Optional
import net.minecraft.client.gui.Gui
import net.minecraft.world.scores.DisplaySlot
import net.minecraft.world.scores.PlayerTeam
import net.minecraft.network.chat.FormattedText
import net.minecraft.network.chat.Style
import net.minecraft.network.chat.Component
import net.minecraft.ChatFormatting
import moe.nea.firmament.annotations.Subscribe
import moe.nea.firmament.events.TickEvent

object ScoreboardUtil {
	var scoreboardLines: List<Component> = listOf()
	var simplifiedScoreboardLines: List<String> = listOf()

	@Subscribe
	fun onTick(event: TickEvent) {
		scoreboardLines = getScoreboardLinesUncached()
		simplifiedScoreboardLines = scoreboardLines.map { it.unformattedString }
	}

	private fun getScoreboardLinesUncached(): List<Component> {
		val scoreboard = MC.instance.level?.scoreboard ?: return listOf()
		val activeObjective = scoreboard.getDisplayObjective(DisplaySlot.SIDEBAR) ?: return listOf()
		return scoreboard.listPlayerScores(activeObjective)
			.filter { !it.isHidden() }
			.sortedWith(Gui.SCORE_DISPLAY_ORDER)
			.take(15).map {
				val team = scoreboard.getPlayersTeam(it.owner)
				val text = it.ownerName()
				PlayerTeam.formatNameForTeam(team, text)
			}
	}
}

fun Component.formattedString(): String {
	val sb = StringBuilder()
	visit(FormattedText.StyledContentConsumer<Unit> { style, string ->
		val c = ChatFormatting.getByName(style.color?.serialize())
		if (c != null) {
			sb.append(${c.char}")
		}
		if (style.isUnderlined) {
			sb.append("§n")
		}
		if (style.isBold) {
			sb.append("§l")
		}
		sb.append(string)
		Optional.empty()
	}, Style.EMPTY)
	return sb.toString().replace("§[^a-f0-9]".toRegex(), "")
}