GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package idle

import "github.com/nsgo-dev/game/pkg/idle"

Visão geral

Package idle provides the arithmetic idle and incremental games need: a Number that holds values far beyond float64's range, progress earned while the game was closed, and formatting of very large numbers in short (1.23K, 4.5万), letter, scientific (1.23e45), engineering and full forms.

A Number is a plain float64 for magnitudes up to 1e300 and a float64 mantissa with an int64 power of ten beyond, so it reaches 10^MaxExponent instead of float64's 1.8e308 while ordinary values keep exact float64 arithmetic. Its operations are plain IEEE-754 float64 operations with no fused multiply-add, so a given sequence of them gives the same bits on every platform, and it reads and writes itself as text ("1.23e45") for saves and data tables.

Offline credits an absence measured from wall-clock timestamps, with a minimum, a cap, an efficiency and protection against a clock moved backwards. Format renders a Number for a Locale; English and Chinese locales are built in, and a game can describe its own in a versioned YAML file read by ParseLocale.

Índice

Constantes

const DefaultDigits = 3

DefaultDigits is the number of significant digits Format shows when Format.Digits is 0.

const LocaleVersion = 1

LocaleVersion is the locale file schema version this package reads and writes.

const MaxExponent int64 = 1_000_000_000_000_000_000

MaxExponent is the largest power of ten a Number holds. Results beyond it saturate to the largest Number of that sign, and results whose magnitude falls below 10^-MaxExponent become zero.

Variáveis

var ErrRange = errors.New("number out of range")

ErrRange reports text whose power of ten lies beyond ±MaxExponent.

var ErrSyntax = errors.New("invalid number syntax")

ErrSyntax reports text that is not a decimal number, such as an empty string, "inf", "NaN", a hexadecimal float or stray characters.

Funções

func EncodeLocale(l *Locale) ([]byte, error)

EncodeLocale validates l and writes it as deterministic 2-space YAML with fields in a fixed order, so ParseLocale followed by EncodeLocale reproduces the same bytes.

Tipos

type Away struct {
	// Elapsed is the wall-clock time between the last-seen time and now; 0 when there was no last-seen time or the clock moved backwards.
	Elapsed time.Duration
	// Credited is the part of Elapsed that earns progress, after Min and Cap.
	Credited time.Duration
	// Capped reports that Cap cut the absence short.
	Capped bool
	// Rewound reports that now is before the last-seen time: the device clock was set back, so nothing is credited.
	Rewound bool
	// Seen is the later of the last-seen time and now, without a monotonic clock reading. A game stores it as the next last-seen time, so setting the clock back and forward again cannot credit the same hours twice.
	Seen time.Time
}

Away describes one absence as Offline credits it.

func (a Away) Steps(step time.Duration) (n int64, rest time.Duration)

Steps splits the credited time into whole fixed steps and the remainder, for a game that replays its simulation step by step while away instead of multiplying a rate. It panics if step is not positive.

type Format struct {
	// Notation is the notation; the zero value is Short.
	Notation Notation
	// Digits is the number of significant digits, from 1 to 17; 0 means DefaultDigits and larger values are treated as 17.
	Digits int
	// Fixed keeps trailing zeros in the fraction.
	Fixed bool
	// Locale supplies separators and units; nil means English. It must be valid; see Locale.Validate.
	Locale *Locale
}

Format writes Numbers for display in a notation and locale. The zero Format writes Short notation with three significant digits in English: 1234 is "1.23K", 1e45 is "1Qad".

Digits is the number of significant digits shown; integer digits are never dropped, so 123456 is "123K" and 1234 in Full is "1,234" even with Digits 3. Trailing fraction zeros are trimmed unless Fixed is set, which keeps the width steady as a counter climbs: "1.20K" instead of "1.2K".

Rounding happens before the unit is chosen, so 999999 with three digits is "1M", never "1000K". Positional output covers exponents from -6 up; smaller magnitudes are scientific.

func (f Format) Append(dst []byte, n Number) []byte

Append appends n written in f's notation and locale to dst, allocating nothing when dst has room, so a HUD can redraw a counter every frame.

func (f Format) Format(n Number) string

Format returns n written in f's notation and locale.

type Locale struct {
	// Version is the schema version; it must equal LocaleVersion.
	Version int `yaml:"version"`
	// Name is the locale's BCP 47 tag, such as "en" or "zh-Hans".
	Name string `yaml:"name"`
	// Decimal separates the integer and fraction digits.
	Decimal string `yaml:"decimal"`
	// Group separates each three integer digits in positional output; empty means no grouping.
	Group string `yaml:"group"`
	// Exponent marks the power of ten in scientific and engineering output, such as "e" in 1.23e45.
	Exponent string `yaml:"exponent"`
	// Units lists the Short notation's units in ascending Exp order.
	Units []Unit `yaml:"units"`
}

Locale describes how numbers read in one language: the decimal and grouping separators, the exponent marker, and the units the Short notation divides by, such as K and M in English or 万 and 亿 in Chinese.

A Locale is a versioned YAML document, so a game can add a language, or name its own units, without code:

version: 1
name: de
decimal: ","
group: "."
exponent: e
units:
  - exp: 3
    suffix: " Tsd."
  - exp: 6
    suffix: " Mio."

Format reads a Locale without validating it; one from ParseLocale or the built-in constructors is always valid, and one built in code should pass Validate first.

func ChineseSimplified() *Locale

ChineseSimplified returns a new Simplified Chinese locale: "." and ",", and the myriad units 万, 亿, 兆, 京, 垓, 秭, 穰, 沟, 涧, 正 and 载 for 10^4 to 10^44, each 10^4 times the last.

func ChineseTraditional() *Locale

ChineseTraditional returns a new Traditional Chinese locale with the myriad units 萬, 億, 兆, 京, 垓, 秭, 穰, 溝, 澗, 正 and 載 for 10^4 to 10^44.

func English() *Locale

English returns a new English locale: "." and ",", and the units K, M, B, T, Qa, Qi, Sx, Sp, Oc, No, Dc, Ud, Dd, Td, Qad, Qid, Sxd, Spd, Ocd, Nod and Vg for 10^3 to 10^63.

func LocaleFor(tag string) *Locale

LocaleFor returns a new built-in locale for a BCP 47 tag: Traditional Chinese for zh with the Hant script or the TW, HK or MO region, Simplified Chinese for other zh tags, and English for everything else. Case and "_" or "-" separators do not matter.

func ParseLocale(data []byte) (*Locale, error)

ParseLocale decodes a YAML locale document and validates it. Unknown fields and trailing documents are refused.

func (l *Locale) Clone() *Locale

Clone returns a deep copy of l, so a built-in locale can be adjusted without affecting other users.

func (l *Locale) Validate() error

Validate reports whether l is a well-formed version 1 locale: separators and suffixes that are non-empty where required, valid UTF-8 and free of ASCII digits and signs, a decimal separator that differs from the group separator, an exponent marker that differs from both, unit suffixes that are neither separator and do not start with the exponent marker, and unit exponents from 1 to 1000000 in strictly ascending order with distinct suffixes.

type Notation uint8

Notation selects how Format writes a number.

const (
	// Short divides by the locale's largest unit at or below the value: 1.23K and 4.5B in English, 1.23万 and 4.5亿 in Chinese. Values below the first unit are positional, and values past the last unit's range, or that would need more than 21 integer digits, as in a gap between two units of a custom locale, switch to Scientific.
	Short Notation = iota
	// Scientific writes one integer digit and a power of ten, such as 1.23e45. Values below 1000 are positional.
	Scientific
	// Engineering writes a power of ten that is a multiple of three and one to three integer digits, such as 12.3e45. Values below 1000 are positional.
	Engineering
	// Letters uses K, M, B and T, then aa, ab, … zz, aaa and so on for each further factor of 1000, so it never runs out. Values below 1000 are positional; only the locale's decimal separator applies.
	Letters
	// Full writes every integer digit with grouping separators, such as 1,234,567, up to 10^21, and Scientific beyond.
	Full
)
func (n Notation) String() string

String returns the notation's name, such as "short".

type Number struct {
	// contains filtered or unexported fields
}

Number is a signed number that reaches far beyond float64: its value is Mantissa() × 10^Exponent() with an int64 exponent up to MaxExponent. The zero value is 0.

A magnitude from 1e-300 up to 1e300 is held as a plain float64, so arithmetic there is exactly float64 arithmetic (2^10 is 1024, integers up to 2^53 are exact) and only values past that range pay for a separate exponent. Every value has one representation, so two equal Numbers compare equal with ==. A Number is a small value type; its methods never modify it and return a new Number.

func New(f float64) Number

New returns the Number nearest f: f itself for magnitudes from 1e-300 up to 1e300, and within one unit in the last place of f beyond, where the decimal mantissa's precision does not line up with float64's. It panics if f is NaN or infinite.

func NewExp(mantissa float64, exp int64) Number

NewExp returns the Number equal to mantissa × 10^exp; the mantissa need not be normalized. It panics if mantissa is NaN or infinite.

func Parse(s string) (Number, error)

Parse reads a decimal number: an optional sign, digits with an optional point, and an optional exponent, such as "42", "-0.5", "1.23e45" or "7E+400". The exponent may exceed float64's range up to ±MaxExponent. Spaces, underscores, hexadecimal, "inf" and "NaN" are refused with ErrSyntax; a value whose power of ten lies beyond the range returns ErrRange, and zero is 0 whatever its exponent.

func Seconds(d time.Duration) Number

Seconds returns d in seconds as a Number, to float64 precision.

func (n Number) Abs() Number

Abs returns |n|.

func (n Number) Add(o Number) Number

Add returns n + o. Past the plain range, when the exponents differ by 17 or more the smaller operand lies below the larger's precision and the larger is returned unchanged.

func (n Number) AppendText(dst []byte) []byte

AppendText appends n's canonical text, as String returns it, to dst.

func (n Number) Cmp(o Number) int

Cmp compares n and o and returns -1, 0 or +1 as n is less than, equal to or greater than o.

func (n Number) Div(o Number) Number

Div returns n / o. It panics if o is zero.

func (n Number) Exponent() int64

Exponent returns n's decimal exponent, the power of ten of its leading digit; it is 0 for zero.

func (n Number) Float64() float64

Float64 returns the float64 nearest n: n itself for magnitudes from 1e-300 up to 1e300, ±Inf when |n| exceeds float64's range, and 0 or a subnormal when it is below the smallest normal float64.

func (n Number) IsZero() bool

IsZero reports whether n is 0.

func (n Number) Log10() float64

Log10 returns log10(|n|), -Inf for zero. It is meant for display, such as progress bars over many orders of magnitude; its last bits may differ between platforms, so game state should not depend on it.

func (n Number) Mantissa() float64

Mantissa returns n's decimal mantissa: 0 for zero, otherwise a value with 1 ≤ |m| < 10 carrying n's sign.

func (n Number) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler with n's canonical text, so a Number is a string in JSON saves and YAML data.

func (n Number) Max(o Number) Number

Max returns the larger of n and o.

func (n Number) Min(o Number) Number

Min returns the smaller of n and o.

func (n Number) Mul(o Number) Number

Mul returns n × o.

func (n Number) Neg() Number

Neg returns -n.

func (n Number) Pow(k int64) Number

Pow returns n raised to the integer power k by repeated squaring, so geometric costs such as base × growth^owned come out the same on every platform. Pow(0) is 1; a negative k returns 1 / n^-k and panics if n is zero.

func (n Number) Scale(f float64) Number

Scale returns n × f. It panics if f is NaN or infinite.

func (n Number) Sign() int

Sign returns -1, 0 or +1 as n is negative, zero or positive.

func (n Number) String() string

String returns n's canonical text: positional for exponents from -6 to 20 ("1500", "0.25"), otherwise scientific with the shortest mantissa that reads back exactly ("1.23e45", "-4e-9"). Parse of the text returns n.

func (n Number) Sub(o Number) Number

Sub returns n - o.

func (n *Number) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It accepts the string MarshalText writes and also a JSON number, so a person can type 1500 for a Number field in a JSON data file; null leaves n unchanged, as encoding/json does for other types.

func (n *Number) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler with Parse.

type Offline struct {
	// Cap is the longest absence credited; 0 means no cap.
	Cap time.Duration
	// Min is the shortest absence credited; a shorter one credits nothing. It must not exceed a non-zero Cap, since an absence between Cap and Min would then credit nothing while a longer one credits Cap.
	Min time.Duration
	// Efficiency is the fraction of the online rate earned while away, such as 0.5 for half; 0 means 1, the full rate.
	Efficiency float64
}

Offline credits the time a player spent away from the game, measured between two wall-clock timestamps: the last-seen time a game stores in its save and the time it starts again or returns from the background.

The zero Offline credits every absence in full. A game usually sets Cap, so returning after a month pays no more than, say, eight hours, and Min, so a quick app switch is not an "offline" event.

func (o Offline) Absence(last, now time.Time) Away

Absence measures the time between last and now and applies Min and Cap. A zero last, as on a first launch, credits nothing. Monotonic clock readings are dropped so the difference is wall-clock time, which keeps running while the device sleeps and is what a saved timestamp holds. It panics if Cap or Min is negative, Min is above a non-zero Cap, or Efficiency is negative or not finite.

func (o Offline) Earn(rate Number, last, now time.Time) (Number, Away)

Earn returns what rate, an amount per second, yields over the absence between last and now: rate × the credited seconds × Efficiency. It panics if Cap or Min is negative, Min is above a non-zero Cap, or Efficiency is negative or not finite.

type Unit struct {
	// Exp is the unit's power of ten, such as 3 for K or 4 for 万.
	Exp int `yaml:"exp"`
	// Suffix follows the scaled digits, such as "K", "万" or " million".
	Suffix string `yaml:"suffix"`
}

Unit is one Short notation unit: a value of at least 10^Exp is shown divided by 10^Exp and followed by Suffix.