idle

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 12 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

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.

Index

Examples

Constants

View Source
const DefaultDigits = 3

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

View Source
const LocaleVersion = 1

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

View Source
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.

Variables

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

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

View Source
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.

Functions

func EncodeLocale

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.

Types

type Away

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 (Away) Steps

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

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.

Example
package main

import (
	"fmt"

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

func main() {
	n := idle.NewExp(1.2345, 45)
	for _, f := range []idle.Format{
		{},
		{Notation: idle.Scientific},
		{Notation: idle.Engineering},
		{Notation: idle.Letters},
		{Locale: idle.ChineseSimplified()},
		{Digits: 5, Fixed: true},
	} {
		fmt.Println(f.Format(n))
	}
	fmt.Println(idle.Format{Notation: idle.Full}.Format(idle.New(1234567)))
}
Output:
1.23Qad
1.23e45
1.23e45
1.23ak
12.3载
1.2345Qad
1,234,567

func (Format) Append

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 (Format) Format

func (f Format) Format(n Number) string

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

type 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

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

func ChineseTraditional() *Locale

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

func English

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

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

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

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

func (*Locale) Clone

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 (*Locale) Validate

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

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 (Notation) String

func (n Notation) String() string

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

type Number

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

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

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

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

func Seconds(d time.Duration) Number

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

func (Number) Abs

func (n Number) Abs() Number

Abs returns |n|.

func (Number) Add

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 (Number) AppendText

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

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

func (Number) Cmp

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 (Number) Div

func (n Number) Div(o Number) Number

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

func (Number) Exponent

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 (Number) Float64

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 (Number) IsZero

func (n Number) IsZero() bool

IsZero reports whether n is 0.

func (Number) Log10

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 (Number) Mantissa

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 (Number) MarshalText

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 (Number) Max

func (n Number) Max(o Number) Number

Max returns the larger of n and o.

func (Number) Min

func (n Number) Min(o Number) Number

Min returns the smaller of n and o.

func (Number) Mul

func (n Number) Mul(o Number) Number

Mul returns n × o.

func (Number) Neg

func (n Number) Neg() Number

Neg returns -n.

func (Number) Pow

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.

Example
package main

import (
	"fmt"

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

func main() {
	base, growth := idle.New(10), idle.New(1.15)
	cost := base.Mul(growth.Pow(250)) // the 251st building
	fmt.Println(idle.Format{Notation: idle.Scientific}.Format(cost))
}
Output:
1.49e16

func (Number) Scale

func (n Number) Scale(f float64) Number

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

func (Number) Sign

func (n Number) Sign() int

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

func (Number) String

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 (Number) Sub

func (n Number) Sub(o Number) Number

Sub returns n - o.

func (*Number) UnmarshalJSON

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 (*Number) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler with Parse.

type Offline

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 (Offline) Absence

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 (Offline) Earn

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.

Example
package main

import (
	"fmt"
	"time"

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

func main() {
	offline := idle.Offline{Cap: 8 * time.Hour, Min: time.Minute, Efficiency: 0.5}
	last := time.Date(2026, time.March, 14, 21, 30, 0, 0, time.UTC)
	now := last.Add(26 * time.Hour)

	earned, away := offline.Earn(idle.NewExp(1.2, 9), last, now) // 1.2B gold a second online
	fmt.Println(away.Elapsed, away.Credited, away.Capped)
	fmt.Println(idle.Format{}.Format(earned))
	fmt.Println(idle.Format{Locale: idle.LocaleFor("zh-CN")}.Format(earned))
}
Output:
26h0m0s 8h0m0s true
17.3T
17.3兆

type Unit

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL