idle

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 13 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 is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package idle provides the arithmetic and wall-clock primitives idle and incremental games need: a Number that holds values far beyond float64's range, Offline progress earned while the game was closed, wall-clock Meter refills (lives, energy, stamina), real-time Jobs (construction, crops, crafting) that finish offline, a SyncedClock for trusted server time, 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. Meter and Jobs share those wall-clock rules: monotonic readings are dropped, a rewound clock credits nothing and never takes away progress, a Seen high-water mark stops set-back-and-forward abuse, an optional trusted TimeSource (such as a SyncedClock anchored to server time) can be plugged in, and both persist to versioned JSON or YAML state (MeterState, JobsState).

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 JobsStateVersion = 1

JobsStateVersion is the JobsState schema version written by Jobs.State and accepted by Jobs.Restore and strict JSON/YAML decoding.

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.

View Source
const MeterStateVersion = 1

MeterStateVersion is the MeterState schema version written by Meter.State and accepted by Meter.Restore and strict JSON/YAML decoding.

Variables

View Source
var ErrInvalidJob = errors.New("idle: invalid job")

ErrInvalidJob reports invalid arguments to Jobs.Start (such as an empty ID, a negative duration, a zero timestamp, or a nil Jobs receiver).

View Source
var ErrInvalidState = errors.New("idle: invalid state")

ErrInvalidState reports a MeterState or JobsState that fails validation or strict JSON/YAML decoding (such as an unsupported version, an unknown field, trailing data, a negative count or duration, a duplicate job ID, or a Seen high-water timestamp earlier than an anchor or job start).

View Source
var ErrJobExists = errors.New("idle: job already exists")

ErrJobExists reports that Jobs.Start was called with an ID that already has an active (uncollected) job.

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 Job

type Job struct {
	// ID is the job's unique key within a Jobs set.
	ID string `json:"id" yaml:"id"`
	// Start is the UTC wall-clock timestamp when the job began.
	Start time.Time `json:"start" yaml:"start"`
	// Duration is the total wall-clock duration from Start until completion,
	// after any SpeedUp reductions.
	Duration time.Duration `json:"duration" yaml:"duration"`
}

Job describes one real-time job (such as a building under construction, a growing crop, a crafting order or a recharging generator) that advances on the wall clock while the app is closed.

func (Job) FinishedAt

func (j Job) FinishedAt() time.Time

FinishedAt returns the UTC wall-clock instant when j completes, or the zero time when j.Start is zero.

func (Job) MarshalJSON

func (j Job) MarshalJSON() ([]byte, error)

MarshalJSON encodes j as JSON with a UTC Start timestamp and a human-readable Go duration string (such as "30m0s").

func (Job) MarshalYAML

func (j Job) MarshalYAML() (any, error)

MarshalYAML encodes j deterministically with fixed field order, a UTC Start timestamp and a human-readable Go duration string.

func (Job) Remaining

func (j Job) Remaining(now time.Time) time.Duration

Remaining reports how much time remains on j at now, clamped to [0, Duration].

func (*Job) UnmarshalJSON

func (j *Job) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes j strictly from JSON, refusing unknown fields, null values, trailing data, invalid durations and invalid fields.

func (*Job) UnmarshalYAML

func (j *Job) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes j strictly from YAML, refusing unknown fields, null values, missing or invalid durations and invalid fields.

func (Job) Validate

func (j Job) Validate() error

Validate reports whether j has a non-empty ID, a non-zero Start and a non-negative Duration.

type Jobs

type Jobs struct {
	// Seen is the latest UTC wall-clock time observed by Jobs, acting as a
	// high-water mark against clock rewinds.
	Seen time.Time
	// Clock is an optional trusted wall-clock source (such as a server time
	// from the game's backend). Methods use now when non-zero and call Clock
	// when now is zero.
	Clock TimeSource
	// contains filtered or unexported fields
}

Jobs tracks keyed real-time jobs on the wall clock across app kills and background absences.

Like Offline and Meter, Jobs drops monotonic readings, never credits or revokes progress when the clock moves backwards, and keeps a Seen high-water mark so setting the device clock back and forward again cannot complete jobs early. Pass now explicitly for deterministic tests, or set Clock to an optional trusted wall-clock source such as a backend server time. Persist through Jobs.State and Jobs.Restore.

Example
package main

import (
	"fmt"
	"time"

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

func main() {
	t0 := time.Date(2026, time.March, 14, 10, 0, 0, 0, time.UTC)
	var jobs idle.Jobs
	_ = jobs.Start("barn", 2*time.Hour, t0)
	_ = jobs.Start("wheat", 20*time.Minute, t0.Add(5*time.Minute))
	_ = jobs.Start("bread", 10*time.Minute, t0.Add(5*time.Minute))

	for _, done := range jobs.Collect(t0.Add(time.Hour)) {
		fmt.Println(done.ID)
	}
	fmt.Println("barn left:", jobs.Remaining("barn", t0.Add(time.Hour)))
}
Output:
bread
wheat
barn left: 1h0m0s

func (*Jobs) Cancel

func (j *Jobs) Cancel(id string) bool

Cancel removes job id without collecting it and reports whether it existed.

func (*Jobs) Collect

func (j *Jobs) Collect(now time.Time) []Job

Collect removes and returns every job finished at or before now, sorted by completion time (FinishedAt ascending, breaking ties by Start then ID). Each finished job is returned once. A rewound clock never completes jobs early and never revokes jobs already finished at j.Seen.

func (*Jobs) Get

func (j *Jobs) Get(id string) (Job, bool)

Get returns the active job for id and whether it exists.

func (*Jobs) Len

func (j *Jobs) Len() int

Len returns the number of active (uncollected) jobs.

func (*Jobs) List

func (j *Jobs) List() []Job

List returns all active jobs in finish order (FinishedAt ascending, breaking ties by Start then ID).

func (*Jobs) Remaining

func (j *Jobs) Remaining(id string, now time.Time) time.Duration

Remaining reports how much time remains on job id at now, advancing the Seen high-water mark. It returns 0 when id does not exist or has already finished. A rewound clock never increases the remaining duration.

func (*Jobs) Restore

func (j *Jobs) Restore(s JobsState) error

Restore replaces j's active jobs and Seen high-water mark from s, keeping j.Clock. If s is invalid, Restore returns an error wrapping ErrInvalidState and leaves j unchanged.

func (*Jobs) SpeedUp

func (j *Jobs) SpeedUp(id string, d time.Duration) bool

SpeedUp reduces job id's duration by d and reports whether the job was shortened. It returns false when id does not exist, d is non-positive, or the job has already finished at j.Seen (advancing j.Seen from j.Clock when Clock is configured). A speedup that finishes the job clamps its completion time to at least j.Seen so jobs that finished earlier keep their finish order.

func (*Jobs) Start

func (j *Jobs) Start(id string, duration time.Duration, now time.Time) error

Start begins a new keyed job with the given duration at now (or at j.Seen when now is earlier than the high-water mark, preventing set-back-and-forward abuse). It refuses a nil receiver, an empty id, a negative duration, a zero timestamp or an id already tracked by j.

func (*Jobs) State

func (j *Jobs) State() JobsState

State returns j's persisted form (Version, Seen and all active jobs sorted by ID) normalized to UTC without monotonic readings.

type JobsState

type JobsState struct {
	// Version is JobsStateVersion.
	Version int `json:"version" yaml:"version"`
	// Seen is the UTC high-water wall-clock timestamp observed by Jobs.
	Seen time.Time `json:"seen,omitzero" yaml:"seen,omitempty"`
	// Jobs holds every active (uncollected) job, sorted by ID.
	Jobs []Job `json:"jobs,omitempty" yaml:"jobs,omitempty"`
}

JobsState is the persisted state of a Jobs set in a versioned form that encodes deterministically to JSON or YAML. Active jobs are listed sorted by ID. Decoding refuses unknown fields, null values, trailing data and invalid states.

func (JobsState) MarshalJSON

func (s JobsState) MarshalJSON() ([]byte, error)

MarshalJSON encodes s deterministically with UTC timestamps and human-readable job durations. It returns an error if s fails Validate.

func (JobsState) MarshalYAML

func (s JobsState) MarshalYAML() (any, error)

MarshalYAML encodes s deterministically with fixed field order and UTC timestamps. It returns an error if s fails Validate.

func (*JobsState) UnmarshalJSON

func (s *JobsState) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a JobsState strictly from JSON, refusing unknown fields, null values, trailing data and invalid states.

func (*JobsState) UnmarshalYAML

func (s *JobsState) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes a JobsState strictly from YAML, refusing unknown fields, null values and invalid states.

func (JobsState) Validate

func (s JobsState) Validate() error

Validate reports whether s is a well-formed version 1 JobsState.

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 Meter

type Meter struct {
	// Max is the normal capacity at which refilling stops.
	Max int
	// Interval is the elapsed time required for one refill unit.
	Interval time.Duration
	// ValueNow is the persisted current value, including any over-cap grant.
	ValueNow int
	// Anchor is the last persisted point from which refill time is measured.
	Anchor time.Time
	// Seen is the latest wall-clock time observed by the meter. It stays at or
	// above Anchor and acts as a high-water mark against clock rewinds.
	Seen time.Time
	// Clock is an optional trusted wall-clock source (such as a server time
	// from the game's backend). Methods use now when it is non-zero and call
	// Clock when now is zero.
	Clock TimeSource
}

Meter refills whole units at Interval while Value is below Max. Value may exceed Max after Add, which pauses refilling until spending brings it down.

Like Offline, Meter drops monotonic clock readings, credits nothing and never takes units away when the clock moves backwards, and keeps a Seen high-water mark so setting the device clock back and forward again cannot grant extra refills. Pass now explicitly for deterministic tests, or set Clock to an optional trusted wall-clock source such as a backend server time. Persist the meter through Meter.State and Meter.Restore.

Example
package main

import (
	"fmt"
	"time"

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

func main() {
	t0 := time.Date(2026, time.March, 14, 10, 0, 0, 0, time.UTC)
	lives := idle.Meter{Max: 5, Interval: 30 * time.Minute, ValueNow: 2, Anchor: t0}

	// Player returns 47m26s later: one life refilled, 12m34s until the next.
	now := t0.Add(47*time.Minute + 26*time.Second)
	fmt.Println(lives.Value(now), lives.NextIn(now), lives.FullIn(now))

	// A reward over-fills above Max and pauses refilling.
	fmt.Println(lives.Add(4, now), lives.NextIn(now))
}
Output:
3 12m34s 42m34s
7 0s

func (*Meter) Add

func (m *Meter) Add(n int, now time.Time) int

Add grants n units after applying refill through now. It accepts values over Max (which pauses refilling) and returns the resulting value. Non-positive n leaves the value unchanged. Progress toward the next unit is kept while the value stays below Max; reaching or exceeding Max advances Anchor to Seen.

func (Meter) FullIn

func (m Meter) FullIn(now time.Time) time.Duration

FullIn reports the time until the meter reaches Max at now, counting the progress already made toward the next unit.

func (Meter) NextIn

func (m Meter) NextIn(now time.Time) time.Duration

NextIn reports the time until the next refill unit at now, or zero when the meter is not refilling. On a rewound clock it reports the remaining interval from the high-water mark without crediting or regressing progress.

func (*Meter) Restore

func (m *Meter) Restore(s MeterState) error

Restore replaces m's persisted value, anchor and high-water Seen mark from s, keeping m.Max, m.Interval and m.Clock. If s is invalid, Restore returns an error wrapping ErrInvalidState and leaves m unchanged.

func (*Meter) Spend

func (m *Meter) Spend(n int, now time.Time) bool

Spend removes n units after applying refill through now. It returns false when n is negative or exceeds the current value. Progress toward the next unit is kept when the meter was already refilling; spending from full or over-cap to below Max starts refilling from the high-water mark Seen.

func (*Meter) State

func (m *Meter) State() MeterState

State returns m's persisted form (Version, Value, Anchor and, when later than Anchor, Seen) normalized to UTC without monotonic readings.

func (*Meter) Value

func (m *Meter) Value(now time.Time) int

Value returns the meter value at now and advances its saved anchor and Seen high-water mark. While the meter is not refilling (at or above Max) the anchor follows now, so refilling starts when the value drops below Max. A clock rewind credits nothing and keeps both Anchor and Seen unchanged.

type MeterState

type MeterState struct {
	// Version is MeterStateVersion.
	Version int `json:"version" yaml:"version"`
	// Value is the stored meter count at Anchor, including any over-cap grant.
	Value int `json:"value" yaml:"value"`
	// Anchor is the UTC wall-clock timestamp from which the next refill is measured.
	Anchor time.Time `json:"anchor,omitzero" yaml:"anchor,omitempty"`
	// Seen is the UTC high-water wall-clock timestamp observed by the meter.
	// Omitted when zero or equal to Anchor.
	Seen time.Time `json:"seen,omitzero" yaml:"seen,omitempty"`
}

MeterState is the persisted state of a Meter in a versioned form that encodes deterministically to JSON or YAML. Decoding from either format refuses unknown fields, null values, trailing data and invalid states.

func (MeterState) MarshalJSON

func (s MeterState) MarshalJSON() ([]byte, error)

MarshalJSON encodes s deterministically with UTC timestamps and no monotonic readings. It returns an error if s fails Validate.

func (MeterState) MarshalYAML

func (s MeterState) MarshalYAML() (any, error)

MarshalYAML encodes s deterministically with fixed field order and UTC timestamps. It returns an error if s fails Validate.

func (*MeterState) UnmarshalJSON

func (s *MeterState) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a MeterState, refusing unknown fields, null values, trailing data and invalid states.

func (*MeterState) UnmarshalYAML

func (s *MeterState) UnmarshalYAML(n *yaml.Node) error

UnmarshalYAML decodes a MeterState from YAML, refusing unknown fields, null values and invalid states.

func (MeterState) Validate

func (s MeterState) Validate() error

Validate reports whether s is a well-formed version 1 MeterState.

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 SyncedClock

type SyncedClock struct {
	// Local supplies local wall-clock readings for Now. When nil, Now reads
	// time.Now.
	Local func() time.Time
	// Offset is the trusted server time minus the local time at the last Sync.
	Offset time.Duration
	// Seen is the latest UTC wall-clock timestamp returned so far.
	Seen time.Time
	// contains filtered or unexported fields
}

SyncedClock turns a server timestamp synced against a local clock into a rewind-safe wall-clock TimeSource. It applies the synced offset to local readings and clamps to a Seen high-water mark so rewinding the device clock never moves time backwards.

SyncedClock is not safe for concurrent use without external synchronization.

func (*SyncedClock) At

func (c *SyncedClock) At(localNow time.Time) time.Time

At converts localNow into a UTC wall-clock timestamp using Offset and clamps it to Seen so a rewound local clock never moves backwards. A zero localNow returns Seen (or the zero time when Seen is also zero).

func (*SyncedClock) Now

func (c *SyncedClock) Now() time.Time

Now reads Local (or time.Now when Local is nil) and returns At of that reading. *SyncedClock implements TimeSource directly and can be assigned to Meter.Clock and Jobs.Clock.

func (*SyncedClock) Sync

func (c *SyncedClock) Sync(serverNow, localNow time.Time)

Sync anchors the clock to serverNow observed at localNow, updating Offset and advancing Seen to at least serverNow. Monotonic readings are dropped. Zero timestamps are ignored.

func (*SyncedClock) Synced

func (c *SyncedClock) Synced() bool

Synced reports whether Sync has anchored this clock to a server time.

type TimeFunc

type TimeFunc func() time.Time

TimeFunc adapts a func() time.Time (such as cx.WallTime or a test closure) to TimeSource.

func (TimeFunc) Now

func (f TimeFunc) Now() time.Time

Now calls f, or returns the zero time when f is nil.

type TimeSource

type TimeSource interface {
	Now() time.Time
}

TimeSource supplies a wall-clock instant, such as a trusted server time from the game's backend, cx.WallTime in an NSGo app, or a fake clock in tests. Monotonic clock readings are stripped whenever idle reads from a TimeSource.

*SyncedClock implements TimeSource directly; adapt plain functions such as cx.WallTime with TimeFunc.

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