/* eslint-disable no-plusplus */ import type { COMPARISON_OPERATORS, FormattingTags, JSONTextComponent, MultipleEntitiesArgument, NBTObject, NBTSerializable, ObjectiveArgument, OPERATORS, Range, } from 'sandstone/arguments' import type { ExecuteCommand, SandstoneCommands } from 'sandstone/commands' import type { NotNode } from 'sandstone/flow' import { nbtResolver, type ConditionClass } from 'sandstone/variables' import * as util from 'util' import { MacroArgument } from '../core/Macro' import type { SandstonePack } from '../pack' import { add, formatDebugString, type NonEmptyString } from '../utils' import type { TextComponentClass } from './abstractClasses' import { SelectorPickClass } from './abstractClasses' import type { DATA_TYPES, DataPointClass } from './Data' import type { ObjectiveClass } from './Objective' import { rangeParser } from './parsers' import type { MCFunctionClass } from 'sandstone/core' type PlayersTarget = number | MultipleEntitiesArgument type OperationArguments = | [amountOrTargetScore: number | Score] | [targets: PlayersTarget, objective?: ObjectiveArgument] let matchers = 0 function createVariable(pack: SandstonePack, amount: number): Score function createVariable( pack: SandstonePack, targets: MultipleEntitiesArgument, objective: ObjectiveArgument, ): Score function createVariable(pack: SandstonePack, score: Score): Score function createVariable( pack: SandstonePack, ...args: [number] | [Score] | [MultipleEntitiesArgument, ObjectiveArgument] ): Score { const anonymousScore = pack.Variable() if (typeof args[0] === 'number' || args[0] instanceof Score) { return anonymousScore.set(args[0]) } return anonymousScore.set(args[0], args[1]) } export type ScoreDisplay = { name?: JSONTextComponent numberformat?: 'blank' | ['styled', FormattingTags] | ['fixed', JSONTextComponent] } type BitFieldSize = 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 type Tuple = ( A['length'] extends N ? A : Tuple ) export class Score extends MacroArgument implements ConditionClass, TextComponentClass, NBTSerializable { declare readonly __textComponentClassBrand: true declare readonly __conditionClassBrand: true commands: SandstoneCommands constructor( public sandstonePack: SandstonePack, public target: MultipleEntitiesArgument, public display: ScoreDisplay | undefined, public objective: ObjectiveClass, ) { super(sandstonePack.core) this.commands = sandstonePack.commands if (display !== undefined) { if (sandstonePack.core.currentMCFunction) { this.setDisplay(display) } else { sandstonePack.initMCFunction.push(() => this.setDisplay(display)) } } } toString(): `${string} ${string}` { return `${this.target} ${this.objective}` } toNBT() { return nbtResolver(this._toChatComponent()).toString() } toJSON() { return this._toChatComponent() } /** * @internal */ _toChatComponent(): JSONTextComponent { return { score: { name: `${this.target}` as NonEmptyString, objective: this.objective }, } } /** * @internal */ _toMinecraftCondition = () => this.sandstonePack._.not( new this.sandstonePack.conditions.Score(this.sandstonePack.core, [ `${this.target}`, `${this.objective}`, 'matches', '0', ]), ) private unaryOperation(operation: 'add' | 'remove' | 'set', operator: OPERATORS, ...args: OperationArguments): this { if (typeof args[0] === 'number') { // scoreboard players add/remove don't support negative numbers, use score operations instead if (args[0] < 0 && operation !== 'set') { return this.binaryOperation(operator, args[0]) } this.commands.scoreboard.players[operation](this, args[0]) } else if (args[0] instanceof Score) { this.commands.scoreboard.players.operation(this, operator, args[0].target, args[0].objective) } else { this.commands.scoreboard.players.operation(this, operator, args[0], args[1] ?? this.objective) } return this } private binaryOperation(operator: OPERATORS, ...args: OperationArguments): this { if (args[0] instanceof Score) { this.commands.scoreboard.players.operation(this, operator, args[0].target, args[0].objective) return this } let objective = args[1] ?? this.objective if (typeof args[0] === 'number') { this.sandstonePack.registerNewConstant(args[0]) objective = '__sandstone' } this.commands.scoreboard.players.operation(this, operator, args[0], objective) return this } setDisplay = (display: ScoreDisplay) => { if (display.name) { this.commands.scoreboard.players.display.name(this, display.name) } if (display.numberformat) { if (display.numberformat === 'blank') { this.commands.scoreboard.players.display.numberformat(this, 'blank') } else if (display.numberformat[0] === 'styled') { this.commands.scoreboard.players.display.numberformat(this, 'styled', display.numberformat[1]) } else { this.commands.scoreboard.players.display.numberformat(this, 'fixed', display.numberformat[1]) } } this.display = display return this } /** INLINE OPERATORS */ /** * Reset the entity's score. */ reset = () => { this.commands.scoreboard.players.reset(this) } /** * Set the current entity's score to other entities's scores. * * @param targets The targets to get the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ set(targets: PlayersTarget, objective?: ObjectiveArgument): Score /** * Set the current entity's score to the given value, or to the other target's score. * * @param amountOrTargetScore A value, or the target's score. */ set(amountOrTargetScore: number | Score): Score /** * Set the current entity's score to the given NBT value, with the given scale. * * @param nbt The Data Point to set the score to. * * @param scale The scale factor. */ set(nbt: DataPointClass, scale?: number): Score set(...args: OperationArguments | [DataPointClass, number?]) { if (typeof args[0] === 'object' && !(args[0] instanceof SelectorPickClass) && !(args[0] instanceof Score)) { const [data, scale] = args as [DataPointClass, number?] /* @ts-ignore */ this.commands.execute.store.result.score(this).run.data.get[data.type](data.currentTarget, data.path, scale) return this } return this.unaryOperation('set', '=', ...(args as OperationArguments)) } '=' = this.set /** * Adds other entities's scores to the current entity's score. * * @param targets The targets to add the scores from. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ add(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Adds the given amount, or the other target's score, to the current entity's score. * * @param amountOrTargetScore The amount to add, or the target to add the scores from. */ add(amountOrTargetScore: number | Score): Score add(...args: OperationArguments) { return this.unaryOperation('add', '+=', ...args) } '+=' = this.add /** * Subtract other target's scores from the current entity's score. * * @param targets The targets to get the scores from. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ remove(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Subtract the given amount, or the other target's score, from the current entity's score. * * @param targetScore The amount to subtract, or the target to get the score from. */ remove(amountOrTargetScore: number | Score): Score remove(...args: OperationArguments) { return this.unaryOperation('remove', '-=', ...args) } '-=' = this.remove /** * Adds one to the current entity's score. */ increase() { return this.add(1) } get '++'() { return this.increase() } /** * Subtracts one from the current entity's score. */ decrease() { return this.remove(1) } get '--'() { return this.decrease() } /** * Multiply the current entity's score by other entities's scores. * * @param targets The targets to get the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ multiply(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Multiply the current entity's score by the given value, or other target's scores. * * @param amountOrTargetScore The value, or the target to get the scores from. */ multiply(amountOrTargetScore: number | Score): Score multiply(...args: OperationArguments) { return this.binaryOperation('*=', ...args) } '*=' = this.multiply /** * Divide the current entity's score by other entities's scores. * * @param targets The targets to get the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ divide(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Divide the current entity's score by the given value, or the other target's scores. * * @param amountOrTargetScore The value, or the target to get the scores from */ divide(amountOrTargetScore: number | Score): Score divide(...args: OperationArguments) { return this.binaryOperation('/=', ...args) } '/=' = this.divide /** * Get the remainder of the division of the current entity's score by other entities's scores. * * @param targets The targets to get the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ modulo(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Divide the current entity's score by other target's scores. * * @param amountOrTargetScore The value, or target's score to modulo the current score with. */ modulo(amountOrTargetScore: number | Score): Score modulo(...args: OperationArguments) { return this.binaryOperation('%=', ...args) } mod = this.modulo '%=' = this.modulo /** * Swap the current score with the other targets' scores. * * @param targets The targets to swap the scores with * * @param objective The related objective. If not specified, default to the same objective as the current target. */ swap(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): void /** * Swap the current entity's score with the other target's scores. * * @param targetScore The target to swap the scores with */ swap(targetScore: Score): void swap(...args: OperationArguments) { this.binaryOperation('><', ...args) } '><' = this.swap /** EFFECT-FREE OPERATORS */ /** * Returns a new anonymous score, equal to the sum of the current score and the given targets' score. * * @param targets The targets to add the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ plus(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Returns a new anonymous score, equal to the sum of the current score and the given amount or target' score. * * @param amountOrTargetScore The value, or the target to add the score from. */ plus(amountOrTargetScore: number | Score): Score plus(...args: OperationArguments): Score { return createVariable(this.sandstonePack, this).unaryOperation('add', '+=', ...args) } '+' = this.plus /** * Returns a new anonymous score, equal to the difference between the current score and the given targets' score. * * @param targets The targets to subtract the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ minus(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Returns a new anonymous score, equal to the difference between the current score and the given amount or target' score. * * @param amountOrTargetScore The amount to subtract, or the target to subtract the score from. */ minus(amountOrTargetScore: number | Score): Score minus(...args: OperationArguments): Score { return createVariable(this.sandstonePack, this).unaryOperation('remove', '-=', ...args) } '-' = this.minus /** * Returns a new anonymous score, equal to the product of the current score and the given targets' score. * * @param targets The targets to multiply the scores from * * @param objective The related objective. If not specified, default to the same objective as the current target. */ multipliedBy(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Returns a new anonymous score, equal to the product of the current score and the given amount or target's score. * * @param amountOrTargetScore The amount, or the target to multiply the scores from */ multipliedBy(amountOrTargetScore: number | Score): Score multipliedBy(...args: OperationArguments): Score { return createVariable(this.sandstonePack, this).binaryOperation('*=', ...args) } times = this.multipliedBy '*' = this.multipliedBy /** * Returns a new anonymous score, equal to the division of the current score and the given targets' score. * * @param targets The targets to divide the scores by * * @param objective The related objective. If not specified, default to the same objective as the current target. */ dividedBy(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Returns a new anonymous score, equal to the division of the current score and the given amount or target's score. * * @param amountOrTargetScore The amount, or target's score to divide the current score by. */ dividedBy(amountOrTargetScore: number | Score): Score dividedBy(...args: OperationArguments): Score { return createVariable(this.sandstonePack, this).binaryOperation('/=', ...args) } '/' = this.dividedBy /** * Returns a new anonymous score, equal to the modulo of the current score and the given targets' score. * * @param targets The targets to modulo the scores by * * @param objective The related objective. If not specified, default to the same objective as the current target. */ moduloBy(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): Score /** * Returns a new anonymous score, equal to the modulo of the current score and the given value, or target's score. * * @param amountOrTargetScore The amount, or target's score to modulo the current score by. */ moduloBy(amountOrTargetScore: number | Score): Score moduloBy(...args: OperationArguments): Score { return createVariable(this.sandstonePack, this).binaryOperation('%=', ...args) } modBy = this.moduloBy '%' = this.moduloBy /** COMPARISONS OPERATORS */ private comparison(operator: COMPARISON_OPERATORS, matchesRange: string, args: OperationArguments): ConditionClass { // oxlint-disable-next-line no-this-alias const playerScore = this if (typeof args[0] === 'number') { return { __conditionClassBrand: true as const, _toMinecraftCondition: () => new this.sandstonePack.conditions.Score(this.sandstonePack.core, [ `${playerScore.target}`, `${playerScore.objective}`, 'matches', matchesRange, ]), } } const endArgs = args[1] ? args : [args[0]] return { __conditionClassBrand: true as const, // eslint-disable-next-line max-len _toMinecraftCondition: () => new this.sandstonePack.conditions.Score(this.sandstonePack.core, [ `${playerScore.target}`, `${playerScore.objective}`, operator, ...endArgs.map((arg) => (arg as any).toString()), ]), } } /** * Check if the current score is strictly greater than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ greaterThan(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): ConditionClass /** * Check if the current score is strictly greater than the given amount or score. * * @param amountOrTargetScore The amount or score to compare the current score against. */ greaterThan(amountOrTargetScore: number | Score): ConditionClass greaterThan(...args: OperationArguments) { return this.comparison('>', `${typeof args[0] === 'number' ? args[0] + 1 : null}..`, args) } '>' = this.greaterThan /** * Check if the current score is greater or equal than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ greaterThanOrEqualTo(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): ConditionClass /** * Check if the current score is greater or equal than the given amount or score. * * @param amountOrTargetScore The amount or score compare the current score against. */ greaterThanOrEqualTo(amountOrTargetScore: number | Score): ConditionClass greaterThanOrEqualTo(...args: OperationArguments) { return this.comparison('>=', `${args[0]}..`, args) } '>=' = this.greaterThanOrEqualTo /** * Check if the current score is strictly lower than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ lessThan(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): ConditionClass /** * Check if the current score is strictly lower than the given amount or score. * * @param amountOrTargetScore The amount or score to compare the current score against. */ lessThan(amountOrTargetScore: number | Score): ConditionClass lessThan(...args: OperationArguments) { return this.comparison('<', `..${typeof args[0] === 'number' ? args[0] - 1 : null}`, args) } '<' = this.lessThan /** * Check if the current score is lower or equal than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ lessThanOrEqualTo(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): ConditionClass /** * Check if the current score is lower or equal than the given amount or score. * * @param amountOrTargetScore The amount or score target to compare the current score against. */ lessThanOrEqualTo(amountOrTargetScore: number | Score): ConditionClass lessThanOrEqualTo(...args: OperationArguments) { return this.comparison('<=', `..${args[0]}`, args) } '<=' = this.lessThanOrEqualTo /** * Check if the current score is equal to than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ equalTo(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): ConditionClass /** * Check if the current score is equal to the given amount or score. * * @param amountOrTargetScore The amount or score to compare the current score against. */ equalTo(amountOrTargetScore: number | Score): ConditionClass equalTo(...args: OperationArguments) { return this.comparison('=', args[0].toString(), args) } equals = this.equalTo '==' = this.equalTo /** * Check if the current score is not equal to than the given score. * * @param targets The target to compare the current score against. * * @param objective The related objective. If not specified, default to the same objective as the current target. */ notEqualTo(targets: MultipleEntitiesArgument, objective?: ObjectiveArgument): NotNode /** * Check if the current score is not equal to the given amount or score. * * @param amountOrTargetScore The amount or score to compare the current score against. */ notEqualTo(amountOrTargetScore: number | Score): NotNode notEqualTo(...args: OperationArguments) { return this.sandstonePack._.not(this.comparison('=', args[0].toString(), args)) } '!=' = this.notEqualTo /** * Check if the current score matches a certain range. * * @param range The range to compare the current score against. */ matches = (range: Range) => ({ __conditionClassBrand: true as const, _toMinecraftCondition: () => new this.sandstonePack.conditions.Score(this.sandstonePack.core, [ `${this.target}`, `${this.objective}`, 'matches', rangeParser(this.sandstoneCore, range), ]), }) match = (minimum: number, maximum: number, callback: (num: number) => any) => { const { MCFunction, Macro, core } = this.sandstonePack const { getCurrentMCFunctionOrThrow } = core if (maximum > 1000) { console.warn( `\nWarning: Score.match() will have to create ${maximum - minimum} mcfunction files, this *will* take a while. ` + 'Consider only compiling this once and saving it to external resources.', ) } const matcher = matchers++ // oxlint-disable-next-line no-this-alias const score = this const parent = getCurrentMCFunctionOrThrow() for (let i = minimum; i <= maximum; i++) { MCFunction(`./score_match/${matcher}/${i}`, () => callback(i)) } return MCFunction(`./score_match/${matcher}`, [score], () => Macro.returnCmd.run.functionCmd(Macro`${parent.resource.name}/score_match/${matcher}/${score}`), ) } getDecomposer>(): { components: ComponentScores, decompose: () => ({ components: ComponentScores, sign: Score, }), sign: Score, } getDecomposer>( size: 'bit', splits?: Set, ): { components: ComponentScores, decompose: () => ({ components: ComponentScores, sign: Score, }), sign: Score, } getDecomposer>( size: 'bit', splits: Set, componentCount: Components, ): { components: ComponentScores, decompose: () => ({ components: ComponentScores, sign: Score, }), sign: Score, } getDecomposer>( size: 'bit', splits: Set, componentCount: Components, includeSign: false, ): { components: ComponentScores, decompose: () => ({ components: ComponentScores, }), } getDecomposer>(size: 'byte'): { components: ComponentScores, decompose: () => ComponentScores, } getDecomposer>( size: 'byte', componentCount: Components, ): { components: ComponentScores, decompose: () => ComponentScores, } getDecomposer(size?: 'bit' | 'byte', splitsOrCount?: Set | 2 | 3 | 4, componentCount: BitFieldSize = 31, includeSign = true) { if (typeof this.target !== 'string' || this.target.search(/-|@/) !== -1) { throw new Error('[Score#getDecomposer] Must use a fake-player Score for decomposition.') } const { MCFunction, _, commands } = this.sandstonePack const { execute, returnCmd } = commands const newScore = this.objective.ScoreHolder const components: Score[] = [] const sign = includeSign ? newScore(`${this.target}._32`) : undefined let decompose: MCFunctionClass if (size === 'bit' || size === undefined) { for (let i = 1; i <= componentCount; i++) { components.push(newScore(`${this.target}._${i}`)) } decompose = MCFunction(`__sandstone:score/decompose_bits/${ componentCount }_${ splitsOrCount === undefined ? 0 : (splitsOrCount as Set).size }/${ this.target.replaceAll('.', '/').toLowerCase() }`, () => { // Reset all bits to 0 const resetBits = execute.store.result(components[0]) for (const component of components.slice(1, -1)) { resetBits.store.result(component) resetBits.nestedExecute(['\\\n '], false) } if (includeSign) { resetBits.store.result(components.at(-1)!) resetBits.nestedExecute(['\\\n '], false) resetBits.run(() => sign!['='](0)) } else { resetBits.run(() => components.at(-1)!['='](0)) } const input = newScore(`${this.target}._bf_iterator`) const splits = (splitsOrCount as Set | undefined) ?? new Set() const bitExecute = (bit: number) => execute.store.success(components[bit - 1]) input['='](this) // Zero check - early return _.if(this['=='](0), () => { returnCmd(1) }) // If negative: set sign = 1, convert to absolute value if (includeSign) { execute.store.success(sign!).if.score(input, 'matches', [null, -1]).run(() => { input['*='](-1) }) } // Decompose absolute value input.decomposeBits(splits, componentCount, bitExecute) }, { creator: 'sandstone', onConflict: 'rename', addToSandstoneCore: true, }) } else { throw new Error('[Score#getDecomposer(byte)] Byte decomposition is not yet supported') // const count = (splitsOrCount as number | undefined) ?? 4 // for (let i = 1; i <= count; i++) { // components.push(newScore(`${this.target}._${i}`)) // } // decompose = MCFunction(`__sandstone:score/decompose_bytes/${ // count // }/${ // this.target.replaceAll('.', '/').toLowerCase() // }`, () => { // }, { // creator: 'sandstone', // onConflict: 'rename', // addToSandstoneCore: true, // }) } const result = { components, ...add({ sign }), } return { ...result, decompose: () => { decompose() return result }, } } decomposeBits( splits: Set, componentCount: Components, bitExecute: (bit: Components, halvedAgain: number) => ExecuteCommand, extra?: (bit: Components, halvedAgain: number) => any, ) { const { _ } = this.sandstonePack const sortedSplits = [...splits] .filter(s => s > 0 && s < componentCount) .sort((a, b) => b - a) // boundaries: [31, 22, 17, 0] for splits={22, 17}, componentCount=31 const boundaries = [componentCount, ...sortedSplits, 0] const processRange = (high: number, low: number) => { let halvedAgain = 2 ** high for (let bit = high; bit >= low; bit--) { halvedAgain /= 2 bitExecute(bit as Components, halvedAgain).if.score( this, 'matches', [halvedAgain, null], ).run(() => { this['-='](halvedAgain) extra?.(bit as Components, halvedAgain) }) } } // Build nested structure from inside out (highest threshold first, then lower) // For boundaries [31, 22, 17, 0]: check 1.., inside check 131072.., inside check 4194304.. const buildNested = (rangeIndex: number) => { const high = boundaries[rangeIndex] const low = boundaries[rangeIndex + 1] + 1 // If there's a higher range, check for it first if (rangeIndex > 0) { const higherMinValue = 2 ** boundaries[rangeIndex] _.if(this.matches([higherMinValue, null]), () => { buildNested(rangeIndex - 1) }) } // Process this range's bits processRange(high, low) } if (splits.size === 0) { // No splits - just process all bits processRange(componentCount, 1) } else { // Start from the lowest range - no need to check >= 1 since we already handled zero const lowestRangeIndex = boundaries.length - 2 buildNested(lowestRangeIndex) } } [util.inspect.custom](_depth: number, options: any) { return formatDebugString( this.constructor.name, { target: this.target, display: this.display, objective: this.objective.name, }, undefined, options.indent, ) } }