world

package
v0.0.0-...-b6f29c3 Latest Latest
Warning

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

Go to latest
Published: Dec 22, 2020 License: ISC Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (
	//ClipNorth Bitmask to represent a wall to the north.
	ClipNorth = 1 << iota
	//ClipEast Bitmask to represent a wall to the west.
	ClipEast
	//ClipSouth Bitmask to represent a wall to the south.
	ClipSouth
	//ClipWest Bitmask to represent a wall to the east.
	ClipWest
	ClipCanProjectile
	//ClipDiag1 Bitmask to represent a diagonal wall.
	ClipSwNe
	//ClipDiag2 Bitmask to represent a diagonal wall facing the opposite way.
	ClipSeNw
	//ClipFullBlock Bitmask to represent an object blocking an entire tile.
	ClipFullBlock
)
View Source
const (
	//StateIdle The default MobState, means doing nothing.
	StateIdle MobState = 0
	//StateChatting The mob is chatting with another mob.
	StateChatting = 1 << iota
	//StateFighting The mob is fighting.
	StateFighting
	//StateBanking The mob is banking.
	StateBanking
	//StateMenu The mob is in an option menu.  The option menu handling routines will remove this state as soon
	// as they end, so if this is activated, there is an option menu waiting for a reply.
	StateMenu
	//StateTrading The mob is negotiating a trade.
	StateTrading
	//StateDueling The mob is negotiating a duel.
	StateDueling
	//MSBatching The mob is performing a skill that repeats itself an arbitrary number of times.
	MSBatching
	//StateSleeping The mob is using a bed or sleeping bag, and trying to solve a CAPTCHA
	StateSleeping
	//StateChangingLooks Indicates that the mob in this state is in the player aooearance changing screen
	StateChangingLooks
	//StateShopping Indicates that the mob in this state is using a shop interface
	StateShopping
	//MSItemAction Indicates that the mob in this state is doing an inventory action
	MSItemAction
	// StateAction generic doing-a-thing state
	StateAction

	StateFightingDuel   = StateDueling | StateFighting
	StateChatChoosing   = StateMenu | StateChatting
	StateItemChoosing   = StateMenu | MSItemAction
	StateObjectChoosing = StateMenu | MSBatching

	StatePanelActive = StateBanking | StateShopping | StateChangingLooks | StateSleeping | StateTrading | StateDueling

	StateBusy      = StatePanelActive | StateChatting | MSItemAction | MSBatching | StateAction
	StateWaitEvent = StateMenu | StateChatting | MSItemAction | MSBatching
)

StateIdle The default MobState, means doing nothing.

View Source
const (
	SyncInit   = 0
	SyncSprite = 1 << iota
	SyncMoved
	SyncRemoved
	SyncAppearance

	SyncNeedsPosition = SyncRemoved | SyncMoved | SyncSprite
)
View Source
const (
	// The percentage to increase or decrease the price of an item by as players use it.
	//
	// For every item the shop buys, the asking price decreases by ShopNormalDeltaRate% of the items base price.
	// However, for every item the shop sells, the asking price increases by ShopNormalDeltaRate% of the items base price.
	ShopNormalDeltaRate = 3
	// Defines the base selling price for buying items from players in the general store.
	ShopBuyPriceBasePercent = 40
	// Defines the base asking price for selling items to players in the general store.
	ShopSellPriceBasePercent = 130
	// Defines how often to normalize most general stores inventorys.  Might be an exception to this rule later.
	ShopGeneralRespawnTime = 50
)
View Source
const (
	TicksDay         = 135000
	TicksHour        = 5625
	TicksTwentyMin   = 1875
	TicksMinute      = 100
	TickMinute       = TicksMinute * TickMillis
	TickHour         = TicksHour * TickMillis
	TickDay          = TicksDay * TickMillis
	TickMillis       = 640 * time.Millisecond
	ClientTickMillis = TickMillis >> 5

	//MaxX Width of the game
	MaxX = 944
	// MaxX = 960
	//MaxY Height of the game
	// MaxY = 944 * 4 - 16 // View area for player is 16 tiles wide
	MaxY = 944 * 4 // 4 planes, 944 tiles per plane

)
View Source
const (
	//RegionSize Represents the size of the region
	RegionSize = 48
	//HorizontalPlanes Represents how many columns of regions there are
	HorizontalPlanes = MaxX/RegionSize + 1
	//VerticalPlanes Represents how many rows of regions there are
	VerticalPlanes = MaxY/RegionSize + 1
	//LowerBound Represents a dividing line in the exact middle of a region
	LowerBound = RegionSize / 2
)
View Source
const DefaultDrop = 20

DefaultDrop returns the default item ID all mobs should drop on death

Variables

View Source
var (
	//DeathSpot The spot where NPCs go to be dead.
	DeathPoint = NewLocation(0, 0)
	//SpawnPoint The default spawn point, where new players start and dead players respawn.
	SpawnPoint = Lumbridge.Clone()
	//Lumbridge Lumbridge teleport point
	Lumbridge = NewLocation(122, 647)
	//Varrock Varrock teleport point
	Varrock = NewLocation(122, 647)
	//Edgeville Edgeville teleport point
	Edgeville = NewLocation(220, 445)
)
View Source
var AppearanceKeepalive = net.NewEmptyPacket(213)
View Source
var BankClose = net.NewEmptyPacket(203)
View Source
var BoundaryTriggers []ObjectTrigger

BoundaryTriggers List of script callbacks to run for boundary actions

View Source
var CannotLogout = net.NewEmptyPacket(183)

CannotLogout Message that you can not logout right now.

View Source
var CommandHandlers = make(map[string]func(*Player, []string))

CommandHandlers A map to assign in-game commands to the functions they should execute.

View Source
var Death = net.NewEmptyPacket(83)

Death The 'Oh dear...You are dead' fade-to-black graphic effect when you die.

View Source
var DefaultActionMessage = ServerMessage("Nothing interesting happens.")

DefaultActionMessage This is a message to inform the player that the action they were trying to perform didn't do anything.

View Source
var DuelClose = net.NewEmptyPacket(225)
View Source
var Handlers = make(map[string]HandlerFunc)

handlers A map with descriptive names for the keys, and functions to run for the value.

View Source
var InvOnBoundaryTriggers []func(player *Player, object *Object, item *Item) bool

InvOnBoundaryTriggers a list of actions to run when a player uses an inventory item on a boundary object

View Source
var InvOnObjectTriggers []func(player *Player, object *Object, item *Item) bool

InvOnObjectTriggers a list of actions to run when a player uses an inventory item on a object

View Source
var InvOnPlayerTriggers []ItemOnPlayerTrigger

InvOnPlayerTriggers a list of actions to run when a player uses an inventory item on another player object

View Source
var ItemIndexer = atomic.NewUint32(0)

ItemIndexer Ensures unique indexes for ground items.

TODO: Proper indexing
View Source
var ItemTriggers []ItemTrigger

ItemTriggers List of script callbacks to run for inventory item actions

View Source
var LoginTriggers []func(player *Player)

LoginTriggers a list of actions to run when a player logs in.

View Source
var Logout = net.NewEmptyPacket(4)

Logout Resets client to login welcome screen

View Source
var NpcAtkTriggers []NpcBlockingTrigger

NpcAtkTriggers List of script callbacks to run when you attack an NPC

View Source
var NpcDeathTriggers []NpcBlockingTrigger

NpcDeathTriggers List of script callbacks to run when you kill an NPC

View Source
var NpcTalkList = make([]Callback, 0, 800)

NpcTriggers List of script callbacks to run for NPC talking actions

View Source
var Npcs = NewMobList()

Npcs A collection of every NPC in the game, sorted by index

View Source
var ObjectCounter = atomic.NewUint32(0)
View Source
var ObjectTriggers []ObjectTrigger

ObjectTriggers List of script callbacks to run for object actions

View Source
var OpenChangeAppearance = net.NewEmptyPacket(59)

OpenChangeAppearance The appearance changing window.

View Source
var OptionMenuClose = net.NewEmptyPacket(252)

OrderedDirections This is an array containing all of the directions a mob can walk in, ordered by path finder precedent. West, East, North, South, SouthWest, SouthEast, NorthWest, NorthEast

View Source
var PacketTriggers = make(map[byte]Trigger)
View Source
var Players = &PlayerList{free: make(indexQueue, 0, 1250), PlayersList: make(PlayersList)}

Players Collection containing all of the active client, by index and username hash, guarded by a mutex

View Source
var ResponsePong = net.NewEmptyPacket(9)

ResponsePong Response to a RSC protocol ping net

View Source
var Sectors = make(map[int]*Sector)

Sectors A map to store landscape sectors by their hashed file name.

View Source
var SectorsLock sync.RWMutex
View Source
var ShopClose = net.NewEmptyPacket(137)

ShopClose A net to tell the client to close any open shop interface.

View Source
var (
	//Shops contains all shop instances in the game world mapped to identifying names.
	//
	// No Shops need to be loaded until a player requests one, in my opinion.  From that point on, Shops are active for
	// the entire runtime of the game, unless a system admin does something to stop them.  The structures use so
	// little memory in practice, that I can't imagine a shop ever needing unset for performance or resource usage issues.
	Shops = &ShopContainer{
		set: make(map[string]*Shop),
	}
)
View Source
var SleepClose = net.NewEmptyPacket(84)
View Source
var SleepWrong = net.NewEmptyPacket(194)
View Source
var SpellTriggers = make(map[int]Trigger)
View Source
var TradeClose = net.NewEmptyPacket(128)

TradeClose Closes a trade window

View Source
var UpdateTime time.Time

UpdateTime a point in time in the future to log all active players out and shut down the game for updates. Before the command is issued to set this time, it is initialized to time.Time{} zero value.

View Source
var WelcomeMessage = ServerMessage("Welcome to RuneScape")

WelcomeMessage Welcome to the game on login

Functions

func AddHandler

func AddHandler(name string, h HandlerFunc)

AddHandler Adds and assigns the packethandler to the handlers with the specified name.

func AddItem

func AddItem(i *GroundItem)

AddItem Add a ground item to the region.

func AddNpc

func AddNpc(n *NPC)

AddNpc Add a NPC to the region.

func AddObject

func AddObject(o *Object)

AddObject Add an object to the region.

func AddPlayer

func AddPlayer(p *Player)

AddPlayer Add a player to a region of the game world.

func BankOpen

func BankOpen(player *Player) (p *net.Packet)

func BankUpdateItem

func BankUpdateItem(index, id, amount int) (p *net.Packet)

func BigInformationBox

func BigInformationBox(msg string) (p *net.Packet)

BigInformationBox Builds a packet to trigger the opening of a large black text window with msg as its contents

func BoundaryLocations

func BoundaryLocations(player *Player) (p *net.Packet)

BoundaryLocations Builds a packet with the view-area boundary positions in it, relative to the player. If no new objects are available and no existing local boundarys are removed from area, returns nil.

func BoundedChance

func BoundedChance(percent float64, minPercent, maxPercent float64) bool

BoundedChance is a statistically random function that should return true percent/maxPercent% of the time. This should return true approximately percent/maxPercent of the time, and false (maxPercent-percent)/maxPercent of the time. percent defines the percentage of chance for this check to pass, clamped to the provided boundaries. minPercent is the minimum allowed value of percent. If percent is larger than minPercent, then minPercent is used in its place. maxPercent is the maximum allowed value of percent, and also the denominator used when scaling the percentage to a 1-byte value Returns: randByte <= max(min(percent, maxPercent), minPercent)/maxPercent*256.0, (with uniform randomness)

func Chance

func Chance(percent float64) bool

Chance should return true (percent)% of the time, and false (100-percent)% of the time. It uses ISAAC64+ to provide randomness.

percent defines the percentage of chance for this check to pass.

func ChanceByte

func ChanceByte(threshold int) bool

ChanceByte Grabs a single 8-bit unsigned byte out of the rscgo/rand pkg, and returns true if it's less than or equals the provided threshold.

func Clear

func Clear()

Clear clears all of the lists of triggers.

func ClearDistantChunks

func ClearDistantChunks(player *Player) (p *net.Packet)

ClearDistantChunks iterates through a players transient `distantChunks` attribute and sends them to the client to signal a removal of all stationary entities within an 8x8 chunk of tiles surrounding the cached location.

func ClientSettings

func ClientSettings(player *Player) (p *net.Packet)

ClientSettings Builds a packet containing the players client settings, e.g camera mode, mouse mode, sound fx...

func ClipBit

func ClipBit(direction int) int

func CurrentTick

func CurrentTick() int

func DuelConfirmationOpen

func DuelConfirmationOpen(player, other *Player) (p *net.Packet)

DuelConfirmationOpen Builds a packet to open the duel confirmation page

func DuelOpen

func DuelOpen(targetIndex int) (p *net.Packet)

DuelOpen Builds a packet to open a duel negotiation window

func DuelOptions

func DuelOptions(player *Player) (p *net.Packet)

DuelOptions Builds a packet to update duel fight options

func DuelTargetAccept

func DuelTargetAccept(accepted bool) (p *net.Packet)

DuelTargetAccept Builds a packet to change duel targets accepted status

func DuelUpdate

func DuelUpdate(player *Player) (p *net.Packet)

DuelUpdate Builds a packet to update a duel offer

func EquipmentStats

func EquipmentStats(player *Player) (p *net.Packet)

EquipmentStats Builds a packet with the players equipment statistics in it.

func Fatigue

func Fatigue(player *Player) (p *net.Packet)

Fatigue Builds a packet with the players fatigue percentage in it.

func FightMode

func FightMode(player *Player) (p *net.Packet)

FightMode Builds a packet with the players fight mode information in it.

func FriendList

func FriendList(player *Player) (p *net.Packet)

FriendList Builds a packet with the players friend entityList information in it.

func FriendUpdate

func FriendUpdate(hash uint64, online bool) (p *net.Packet)

FriendUpdate Builds a packet with an online status update for the player with the specified hash

func GetAllObjects

func GetAllObjects() (list []entity.Entity)

GetAllObjects Returns a slice containing all objects in the game

func HandlerCount

func HandlerCount() int

HandlerCount returns the number of pDefinitions that are handled

func HandshakeResponse

func HandshakeResponse(v int) (p *net.Packet)

HandshakeResponse Builds a bare net with the login response code.

func IgnoreList

func IgnoreList(player *Player) (p *net.Packet)

IgnoreList Builds a packet with the players ignore entityList information in it.

func InformationBox

func InformationBox(msg string) (p *net.Packet)

InformationBox Builds a packet to trigger the opening of a small black text window with msg as its contents

func InventoryItems

func InventoryItems(player *Player) (p *net.Packet)

InventoryItems Builds a packet containing the players inventory items.

func IsTileBlocking

func IsTileBlocking(x, y int, bit byte, current bool) bool

var blockedOverlays = [...]int{OverlayWater, definitions.OverlayDarkWater, definitions.OverlayBlack, definitions.OverlayWhite, definitions.OverlayLava, definitions.OverlayBlack2, definitions.OverlayBlack3, definitions.OverlayBlack4}

func isOverlayBlocked(overlay int) bool {
	for _, v := range blockedOverlays {
		if v == definitions.Overlay {
			return true
		}
	}
	return false
}

func ItemLocations

func ItemLocations(player *Player) (p *net.Packet)

ItemLocations Builds a packet with the view-area item positions in it, relative to the player. If no new items are available and no existing items are removed from area, returns nil.

func LoadCollisionData

func LoadCollisionData()

LoadCollisionData Loads the JAG archive './data/landscape.jag', decodes it, and stores the map sectors it holds in memory for quick access.

func LoginBox

func LoginBox(inactiveDays int, lastIP string) (p *net.Packet)

LoginBox Builds a packet to create a welcome box on the client with the inactiveDays since login, and lastIP connected from.

func NPCPositions

func NPCPositions(player *Player) (p *net.Packet)

NPCPositions Builds a packet containing view area NPC position and sprite information

func NewHitsplat

func NewHitsplat(target entity.MobileEntity, damage int) interface{}

func NpcEvents

func NpcEvents(player *Player) (p *net.Packet)

func ObjectLocations

func ObjectLocations(player *Player) (p *net.Packet)

ObjectLocations Builds a packet with the view-area object positions in it, relative to the player. If no new objects are available and no existing local objects are removed from area, returns nil.

func OptionMenuOpen

func OptionMenuOpen(questions ...string) (p *net.Packet)

func PacketCount

func PacketCount() int

PacketCount returns the number of handlers pDefinitions

func ParseDirection

func ParseDirection(s string) int

ParseDirection Tries to parse the direction indicated in s. If it can not match any direction, returns the zero-value for direction: north.

func PlaneInfo

func PlaneInfo(player *Player) (p *net.Packet)

PlaneInfo Builds a packet to update information about the client environment, e.g height, player index...

func PlayerAppearances

func PlayerAppearances(ourPlayer *Player) (p *net.Packet)

PlayerAppearances Builds a packet with the view-area player appearance profiles in it.

func PlayerExperience

func PlayerExperience(player *Player, idx int) (p *net.Packet)

PlayerStat Builds a packet containing player's stat information for skill at idx and returns it.

func PlayerPositions

func PlayerPositions(player *Player) (p *net.Packet)

PlayerPositions Builds a packet containing view area player position and sprite information, including ones own information, and returns it. If no players need to be updated, returns nil.

func PlayerStat

func PlayerStat(player *Player, idx int) (p *net.Packet)

PlayerStat Builds a packet containing player's stat information for skill at idx and returns it.

func PlayerStats

func PlayerStats(player *Player) (p *net.Packet)

PlayerStats Builds a packet containing all the player's stat information and returns it.

func PrayerStatus

func PrayerStatus(player *Player) (p *net.Packet)

func PrivacySettings

func PrivacySettings(player *Player) (p *net.Packet)

PrivacySettings Builds a packet containing the players privacy settings for display in the settings menu.

func PrivateMessage

func PrivateMessage(hash uint64, msg string) (p *net.Packet)

PrivateMessage Builds a packet with a private message from hash with content msg.

func QuestStatus

func QuestStatus(player *Player) (p *net.Packet)

func Region

func Region(x, y int) *region

Region Returns the region that corresponds with the given coordinates. If it does not exist yet, it will allocate a new onr and store it for the lifetime of the application in the regions map.

func RemoveItem

func RemoveItem(i *GroundItem)

RemoveItem SetRegionRemoved a ground item to the region.

func RemoveNpc

func RemoveNpc(n *NPC)

RemoveNpc SetRegionRemoved a NPC from the region.

func RemoveObject

func RemoveObject(o *Object)

RemoveObject SetRegionRemoved an object from the region.

func RemovePlayer

func RemovePlayer(p *Player)

RemovePlayer Remove a player from the game world.

func RunScripts

func RunScripts()

RunScripts Loads all of the scripts in ./scripts. This will ignore any folders named definitions or lib.

func ScriptEnv

func ScriptEnv() *env.Env

func ServerMessage

func ServerMessage(msg string) (p *net.Packet)

ServerMessage Builds a packet containing a game message to display in the chat box.

func ShopOpen

func ShopOpen(shop *Shop) (p *net.Packet)

ShopOpen Builds a packet to open a shop interface with the data about this shop.

func SleepFatigue

func SleepFatigue(player *Player) (p *net.Packet)

func SleepWord

func SleepWord(player *Player) (p *net.Packet)

func Sound

func Sound(name string) (p *net.Packet)

func StartCombat

func StartCombat(attacker, defender entity.MobileEntity)

func Statistical

func Statistical(rng *isaac.ISAAC, options IntProbabilitys) int

Statistical

func SystemUpdate

func SystemUpdate(t int64) (p *net.Packet)

SystemUpdate A packet with the time until servers next system update, measured in server ticks (640ms intervals)

func TeleBubble

func TeleBubble(offsetX, offsetY int) (p *net.Packet)

TeleBubble Builds a packet to draw a teleport bubble at the specified offsets.

func TradeAccept

func TradeAccept(accepted bool) (p *net.Packet)

TradeAccept Builds a packet to change trade targets accepted status

func TradeConfirmationOpen

func TradeConfirmationOpen(player, other *Player) (p *net.Packet)

TradeConfirmationOpen Builds a packet to open the trade confirmation page

func TradeOpen

func TradeOpen(targetIndex int) (p *net.Packet)

TradeOpen Builds a packet to open a trade window

func TradeTargetAccept

func TradeTargetAccept(accepted bool) (p *net.Packet)

TradeTargetAccept Builds a packet to change trade targets accepted status

func TradeUpdate

func TradeUpdate(player *Player) (p *net.Packet)

TradeUpdate Builds a packet to update a trade offer

func UnmarshalPackets

func UnmarshalPackets()

UnmarshalPackets Loads the handlers pDefinitions into memory from the configured TOML file

func UpdateRegions

func UpdateRegions(m entity.MobileEntity, x, y int)

func VisibleRegions

func VisibleRegions(x, y int) (regions [4]*region)

VisibleRegions Returns the regions surrounding the given coordinates.

func VisibleRegionsFrom

func VisibleRegionsFrom(l entity.Location) (regions [4]*region)

func WeightedChoice

func WeightedChoice(choices IntProbabilitys) int

WeightedChoice Awesome API call takes map[retVal]probability as input and returns a statistically weighted randomized retVal as output.

The input's mapped value assigned to each key is its return probability, out of the total sum of all return probabilities. You can determine the percentage chance of any given input entry being returned by: probability/sumOfAllProbabilities*100 E.g, if the sum of all probabilities is 100, and you have a total probability of 100, where the first retVal maps to 25.0, the chance it will be returned is 25%

You can make the total anything. Useful for anything that needs to return certain values deterministically more often than others, but randomly.

func WithinWorld

func WithinWorld(x, y int) bool

IsValid Returns true if the tile at x,y is within world boundaries, false otherwise.

Types

type Callback

type Callback interface{}

type ChatMessage

type ChatMessage struct {
	Owner  entity.MobileEntity
	Target entity.MobileEntity
	// contains filtered or unexported fields
}

func NewChatMessage

func NewChatMessage(owner entity.MobileEntity, content string) ChatMessage

func NewTargetedMessage

func NewTargetedMessage(owner entity.MobileEntity, target entity.MobileEntity, content string) ChatMessage

type CollisionMask

type CollisionMask int16

CollisionMask Represents a single tile in the game's landscape.

func CollisionData

func CollisionData(x, y int) CollisionMask

type Direction

type Direction = int

Direction represents directions that mobs can face within the game world. Ranges from 1-8

const (
	North Direction = iota
	NorthWest
	West
	SouthWest
	South
	SouthEast
	East
	NorthEast
	LeftFighting
	RightFighting
)

type Entity

type Entity struct {
	entity.Location
	Index int
}

Entity A stationary scene entity within the game world.

func (*Entity) AtLocation

func (e *Entity) AtLocation(location Location) bool

AtLocation Returns true if the entity is at the specified location, otherwise returns false

func (*Entity) Point

func (e *Entity) Point() entity.Location

func (*Entity) ServerIndex

func (e *Entity) ServerIndex() int

func (*Entity) SetServerIndex

func (e *Entity) SetServerIndex(i int)

func (*Entity) Type

func (e *Entity) Type() entity.Type

type GroundItem

type GroundItem struct {
	ID, Amount int
	Owner      string
	*entity.AttributeList
	Entity
}

GroundItem Represents a single ground item within the game.

func GetItem

func GetItem(x, y, id int) *GroundItem

GetItem Returns the item at x,y with the specified id. Returns nil if it can not find the item.

func NewGroundItem

func NewGroundItem(id, amount, x, y int) *GroundItem

NewGroundItem Creates a new ground item in the game world and returns a reference to it.

func NewGroundItemFor

func NewGroundItemFor(owner uint64, id, amount, x, y int) *GroundItem

NewGroundItemFor Creates a new ground item with an Owner in the game world and returns a reference to it.

func NewPersistentGroundItem

func NewPersistentGroundItem(id, amount, x, y, respawn int) *GroundItem

NewPersistentGroundItem Returns a new ground item that respawns at a set rate after pickup.

func (*GroundItem) Command

func (i *GroundItem) Command() string

Command Returns the command for this item, or nil if none.

func (*GroundItem) DeltaAmount

func (i *GroundItem) DeltaAmount(o *Item) int

DeltaAmount returns the difference between the amount of o and the amount of the receiver

func (*GroundItem) Name

func (i *GroundItem) Name() string

Name returns the receivers name

func (*GroundItem) Price

func (i *GroundItem) Price() Price

Price returns the receivers base price

func (*GroundItem) Remove

func (i *GroundItem) Remove()

Remove removes the ground item from the world.

func (*GroundItem) ScalePrice

func (i *GroundItem) ScalePrice(percent int) int

ScalePrice returns the receivers base price, scaled by percent%.

func (*GroundItem) SpawnedTime

func (i *GroundItem) SpawnedTime() time.Time

SpawnedTime Returns: the time this item was spawned into the game world.

func (*GroundItem) Stackable

func (i *GroundItem) Stackable() bool

Stackable returns true if the items stackable, otherwise returns false.

func (*GroundItem) Visibility

func (i *GroundItem) Visibility() int

Visibility This is a special state attribute to indicate who the receiver item is visible to. Value 0 means the item has expired and is no longer visible to anybody.

Value 1 means the item is visible to only the Owner of it and game administrators(rank=2), e.g if you kill someone or something, this will be the value for the first minute or two after it is created, and then will change to value 2. NOTE: If this is the current value, but the belongsTo attribute is not set e.g nobody owns this item, it will update itself to value 2 prior to when it normally would.

Value 2 means the item is visible to all players. This is the value when e.g the game starts and makes the worlds default item spawns, or an NPC kills a player and they drop their items and/or bones...This is the state that most transient ground items will likely spend the most time in before unsetting the visibility attribute(same as value=0) and thus disappearing.

func (*GroundItem) VisibleTo

func (i *GroundItem) VisibleTo(p *Player) bool

VisibleTo Returns true if the ground item is visible to this player, otherwise returns false.

func (*GroundItem) WieldPos

func (i *GroundItem) WieldPos() int

WieldPos Returns the equip slot for this item, or -1 if none.

type HandlerFunc

type HandlerFunc = func(*Player, *net.Packet)

HandlerFunc Represents a func that is to be called whenever a connected client receives a specific incoming handlers.

func Handler

func Handler(opcode byte) HandlerFunc

Handler Returns the handlers handler function assigned to this opcode. If it can't be found, returns nil.

type HitSplat

type HitSplat struct {
	Owner  entity.MobileEntity
	Damage int
}

type IntProbabilitys

type IntProbabilitys = map[int]float64

probWeights

type Inventory

type Inventory struct {
	List     []*Item
	Owner    *Player
	Capacity int

	Lock sync.RWMutex
	// contains filtered or unexported fields
}

Inventory Represents an inventory of items in the game.

func (*Inventory) Add

func (i *Inventory) Add(id int, qty int) int

Add Puts an item into the inventory with the specified id and quantity, and returns its index.

func (*Inventory) CanHold

func (i *Inventory) CanHold(id, amount int) bool

CanHold returns true if this inventory can hold the specified amount of the item with the specified ID

func (*Inventory) Clear

func (i *Inventory) Clear()

Clear Clears all items out of the inventory.

func (*Inventory) Clone

func (i *Inventory) Clone() *Inventory

Clone returns a copy of this inventory in a new inventory.

func (*Inventory) CountID

func (i *Inventory) CountID(id int) int

CountID Returns the total amount of all the items with this ID in this inventory.

func (*Inventory) DeathDrops

func (i *Inventory) DeathDrops(keep int) []*GroundItem

DeathDrops returns a list of items to drop upon dying. It decides what to keep using a few simple rules: If the item is stackable, it gets dropped no matter what, even if it is the only item and keep is 3. If the item isn't stackable, the inventory is first sorted by descending BasePrice, and the first `keep` items are sliced off of the top of this sorted list which leaves us with the 30-keep least valuable items.

func (*Inventory) Equipped

func (i *Inventory) Equipped(id int) bool

Equipped Returns true if the item with the given ID exists and is wielded in this inventory

func (*Inventory) Get

func (i *Inventory) Get(index int) *Item

Get Returns a reference to the item at index if it exists, otherwise returns nil.

func (*Inventory) GetByID

func (i *Inventory) GetByID(ID int) *Item

GetByID Returns a reference to the item at index if it exists, otherwise returns nil.

func (*Inventory) GetIndex

func (i *Inventory) GetIndex(ID int) int

GetIndex returns the index of the first item with the provided ID.

func (*Inventory) Range

func (i *Inventory) Range(fn func(*Item) bool) int

Range Calls fn for each item in the inventory list.

func (*Inventory) RangeRev

func (i *Inventory) RangeRev(fn func(*Item) bool) int

RangeRev Calls fn for each item in the inventory list, in reverse.

func (*Inventory) Remove

func (i *Inventory) Remove(index int) bool

Remove Removes item at index from this inventory.

func (*Inventory) RemoveAll

func (i *Inventory) RemoveAll(offer *Inventory) int

RemoveAll Removes all of the items in offer from this inventory, returns count of items removed.

func (*Inventory) RemoveByID

func (i *Inventory) RemoveByID(id, amt int) int

RemoveByID Removes amt items from this inventory by ID, returns the items index if successful, otherwise returns -1

func (*Inventory) Size

func (i *Inventory) Size() int

Size Returns the number of items currently in this inventory.

type Item

type Item struct {
	ID     int
	Amount int
	Worn   bool
	Index  int
}

Item Represents a single item in the game.

func NewItem

func NewItem(id, amt, idx int, worn bool) *Item

func (*Item) Command

func (i *Item) Command() string

Command Returns the item command, or nil if none

func (*Item) DeltaAmount

func (i *Item) DeltaAmount(o *Item) int

DeltaAmount returns the difference between the amount of o and the amount of the receiver

func (*Item) Name

func (i *Item) Name() string

Name returns the receivers name

func (*Item) Price

func (i *Item) Price() Price

Price returns the receivers base price

func (*Item) ScalePrice

func (i *Item) ScalePrice(percent int) int

ScalePrice returns the receivers base price, scaled by percent%.

func (*Item) Stackable

func (i *Item) Stackable() bool

Stackable Returns true if the item is stackable, false otherwise.

func (*Item) String

func (i *Item) String() string

func (*Item) WieldPos

func (i *Item) WieldPos() int

WieldPos Returns the item equip slot, or -1 if none

type ItemBubble

type ItemBubble struct {
	Owner *Player
	Item  int
}

type ItemOnPlayerTrigger

type ItemOnPlayerTrigger struct {
	// Check returns true if this handler should run.
	Check func(*Item) bool
	// Action is the function that will run if Check returned true.
	Action func(*Player, *Player, *Item)
}

ItemOnPlayerTrigger A type that defines a callback to run when certain item are used on players, and a predicate to decide whether or not the callback should run

type ItemTrigger

type ItemTrigger struct {
	// Check returns true if this handler should run.
	Check func(*Item) bool
	// Action is the function that will run if Check returned true.
	Action func(*Player, *Item)
}

ItemTrigger A type that defines a callback to run when certain item actions are performed, and a predicate to decide whether or not the callback should run

type Location

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

Location A tile in the game world.

func NewLocation

func NewLocation(x, y int) Location

NewLocation Returns a reference to a new instance of the Location data structure.

func NewRandomLocation

func NewRandomLocation(bounds [2]Location) Location

NewRandomLocation Returns a new random location within the specified bounds. bounds[0] should be lowest corner, and bounds[1] should be the highest corner.

func (Location) Above

func (l Location) Above() entity.Location

Above Returns the location directly above this one, if any. Otherwise, if we are on the top floor, returns itself.

func (Location) Below

func (l Location) Below() entity.Location

Below Returns the location directly below this one, if any. Otherwise, if we are on the bottom floor, returns itself.

func (Location) CanReach

func (l Location) CanReach(bounds [2]entity.Location) bool

func (Location) Clone

func (l Location) Clone() entity.Location

func (Location) Collides

func (l Location) Collides(dst entity.Location) bool

func (Location) Delta

func (l Location) Delta(other entity.Location) (delta int)

func (Location) DeltaX

func (l Location) DeltaX(other entity.Location) (deltaX int)

DeltaX Returns the difference between this locations x coord and the other locations x coord

func (Location) DeltaY

func (l Location) DeltaY(other entity.Location) (deltaY int)

DeltaY Returns the difference between this locations y coord and the other locations y coord

func (Location) DirectionTo

func (l Location) DirectionTo(destX, destY int) int

func (Location) DirectionToward

func (l Location) DirectionToward(end entity.Location) int

func (Location) Equals

func (l Location) Equals(o interface{}) bool

Equals Returns true if this location points to the same location as o

func (Location) EuclideanDistance

func (l Location) EuclideanDistance(other entity.Location) float64

func (Location) Hash

func (l Location) Hash() int

This produces a unique hash for each tile possible within the current game world; in this sense, it is a perfect hashing algorithm. If the world ever expands a great deal, this may need to change to accomodate larger values.

func (Location) IsValid

func (l Location) IsValid() bool

IsValid Returns true if the tile at x,y is within world boundaries, false otherwise.

func (Location) LongestDelta

func (l Location) LongestDelta(other entity.Location) int

LongestDelta Returns the largest difference in coordinates between receiver and other

func (Location) LongestDeltaCoords

func (l Location) LongestDeltaCoords(x, y int) int

LongestDeltaCoords returns the number of tiles the coordinates provided

func (Location) Mask

func (l Location) Mask(toward entity.Location) byte

func (Location) Masks

func (l Location) Masks(x, y int) (masks [2]byte)

Masks returns appropriate collision bitmasks to check for obstacles on when traversing from this location toward the given x,y coordinates. Returns: [2]byte {verticalMasks, horizontalMasks}

func (Location) Near

func (l Location) Near(other entity.Location, radius int) bool

EntityWithin Returns true if the other location is within radius tiles of the receiver location, otherwise false.

func (Location) NextStep

func (l Location) NextStep(d entity.Location) entity.Location

func (Location) NextTileToward

func (l Location) NextTileToward(dst entity.Location) entity.Location

NextTileToward Returns the next tile toward the final destination of this pathway from currentLocation

func (Location) NextTo

func (l Location) NextTo(target entity.Location) bool

NextTo returns true if we can walk a straight line to target without colliding with any walls or objects, otherwise returns false.

func (Location) PivotTo

func (l Location) PivotTo(loc entity.Location) (deltas [2][]int)

func (Location) Plane

func (l Location) Plane() int

Plane Calculates and returns the plane that this location is on.

func (Location) PlaneY

func (l Location) PlaneY(up bool) int

PlaneY Updates the location's y coordinate, going up by one plane if up is true, else going down by one plane. Valid planes: ground=0, 2nd story=1, 3rd story=2, basement=3

func (Location) Point

func (l Location) Point() entity.Location

func (Location) Reachable

func (l Location) Reachable(other entity.Location) bool

func (Location) ReachableCoords

func (l Location) ReachableCoords(x, y int) bool

func (Location) SetX

func (l Location) SetX(x int)

func (Location) SetY

func (l Location) SetY(y int)

func (Location) Step

func (l Location) Step(dir int) entity.Location

func (Location) String

func (l Location) String() string

String Returns a string representation of the location

func (Location) Targetable

func (l Location) Targetable(other Location) bool

Targetable returns true if you are able to see the other location from the receiever location without hitting any obstacles, and you are within range. Otherwise returns false.

func (Location) TheirDeltaX

func (l Location) TheirDeltaX(other entity.Location) (deltaY int)

DeltaY Returns the difference between this locations y coord and the other locations y coord

func (Location) TheirDeltaY

func (l Location) TheirDeltaY(other entity.Location) (deltaY int)

DeltaY Returns the difference between this locations y coord and the other locations y coord

func (Location) Wilderness

func (l Location) Wilderness() int

func (Location) Within

func (l Location) Within(minX, maxX, minY, maxY int) bool

func (Location) WithinArea

func (l Location) WithinArea(area [2]entity.Location) bool

func (Location) WithinRange

func (l Location) WithinRange(other entity.Location, radius int) bool

WithinRange Returns true if the other location is within radius tiles of the receiver location, otherwise false.

func (Location) WithinReach

func (l Location) WithinReach(other entity.Location) bool

WithinReach returns true if you are able to physically touch the other person you are so close without obstacles Otherwise returns false.

func (Location) X

func (l Location) X() int

func (Location) Y

func (l Location) Y() int

type Mob

type Mob struct {
	SyncMask int

	Prayers [15]bool
	entity.Entity
	*entity.AttributeList
	sync.RWMutex
	// contains filtered or unexported fields
}

Mob Represents a mobile entity within the game world.

func (*Mob) AddState

func (m *Mob) AddState(state int)

func (*Mob) AimPoints

func (m *Mob) AimPoints() int

AimPoints Returns the players aim points

func (*Mob) ArmourPoints

func (m *Mob) ArmourPoints() int

ArmourPoints Returns the players armour points.

func (*Mob) AttackPoints

func (m *Mob) AttackPoints() float64

AttackPoints Calculates and returns the accuracy capability of this mob, based on many variables, as a single variable.

func (*Mob) Busy

func (m *Mob) Busy() bool

Busy Returns true if this mobs state is anything other than idle. otherwise returns false.

func (*Mob) BusyInput

func (m *Mob) BusyInput() bool

func (*Mob) CombatRng

func (m *Mob) CombatRng() *rand.Rand

func (*Mob) CombatRngSrc

func (m *Mob) CombatRngSrc() *isaac.ISAAC

func (*Mob) DefensePoints

func (m *Mob) DefensePoints() float64

DefensePoints Calculates and returns the defensive capability of this mob, based on many variables, as a single variable.

func (*Mob) Direction

func (m *Mob) Direction() int

Direction Returns the mobs direction.

func (*Mob) ExperienceReward

func (m *Mob) ExperienceReward() float64

ExperienceReward returns the total rewarded experience upon killing a mob.

func (*Mob) FightMode

func (m *Mob) FightMode() int

FightMode Returns the players current fight mode.

func (*Mob) FightRound

func (m *Mob) FightRound() int

func (*Mob) FightTarget

func (m *Mob) FightTarget() entity.MobileEntity

func (*Mob) FinishedPath

func (m *Mob) FinishedPath() bool

FinishedPath Returns true if the mobs path is nil, the paths current waypoint exceeds the number of waypoints available, or the next tile in the path is not a valid location, implying that we have reached our destination.

func (*Mob) GenerateHit

func (m *Mob) GenerateHit(max float64) int

GenerateHit returns a normally distributed random number from this mobs PRNG instance, between 1 and max, inclusive. This is widely believed to be how Jagex generated damage hits, and it feels accurate while playing.

func (*Mob) HasState

func (m *Mob) HasState(state ...int) bool

HasState Returns true if the mob has any of these states

func (*Mob) IncAimPoints

func (m *Mob) IncAimPoints(i int)

func (*Mob) IncArmourPoints

func (m *Mob) IncArmourPoints(i int)

func (*Mob) IncMagicPoints

func (m *Mob) IncMagicPoints(i int)

func (*Mob) IncPoints

func (m *Mob) IncPoints(id string, amt int)

func (*Mob) IncPowerPoints

func (m *Mob) IncPowerPoints(i int)

func (*Mob) IncPrayerPoints

func (m *Mob) IncPrayerPoints(i int)

func (*Mob) IncRangedPoints

func (m *Mob) IncRangedPoints(i int)

func (*Mob) IsFighting

func (m *Mob) IsFighting() bool

func (*Mob) Isaac

func (m *Mob) Isaac() *rand.Rand

func (*Mob) LastFight

func (m *Mob) LastFight() time.Time

func (*Mob) LastRetreat

func (m *Mob) LastRetreat() time.Time

func (*Mob) MagicDamage

func (m *Mob) MagicDamage(target entity.MobileEntity, maximum float64) int

MagicDamage Calculates and returns a combat spells damage from the receiver mob cast unto the target MobileEntity. This basically wraps a statistically random percentage check around a call to GenerateHit.

func (*Mob) MagicPoints

func (m *Mob) MagicPoints() int

MagicPoints Returns the players magic points

func (*Mob) MaxMeleeDamage

func (m *Mob) MaxMeleeDamage() float64

MaxMeleeDamage Calculates and returns the current max hit for this mob, based on many variables.

func (*Mob) MeleeDamage

func (m *Mob) MeleeDamage(target entity.MobileEntity) int

MeleeDamage Calculates and returns a melee damage from the receiver mob onto the target mob. This basically wraps a statistically random percentage check around a call to GenerateHit. Generally believed to be a near-perfect approximation of canonical Jagex RSClassic melee damage formula. Kenix mentioned running monte-carlo sims when coming up with it, so presumably this formula matched up statistically fairly well to the real game. I can not say for sure as I didn't do these things myself, though.

func (*Mob) Path

func (m *Mob) Path() *Pathway

Path returns the path that this mob is trying to traverse.

func (*Mob) PowerPoints

func (m *Mob) PowerPoints() int

PowerPoints Returns the players power points.

func (*Mob) PrayerActivated

func (m *Mob) PrayerActivated(i int) bool

func (*Mob) PrayerModifiers

func (m *Mob) PrayerModifiers() (modifiers [3]int)

func (*Mob) PrayerPoints

func (m *Mob) PrayerPoints() int

PrayerPoints Returns the players prayer points

func (*Mob) Random

func (m *Mob) Random(low, high int) int

Random This generates a pseudo-random integer using a member instance of ISAAC. Note: Generated integers are high-exclusive and low-inclusive.

func (*Mob) RandomIncl

func (m *Mob) RandomIncl(low, high int) int

RandomIncl This generates a pseudo-random integer using a member instance of ISAAC. Note: Generated integers are high and low inclusive.

func (*Mob) RangedPoints

func (m *Mob) RangedPoints() int

RangedPoints Returns the players ranged points.

func (*Mob) RemoveState

func (m *Mob) RemoveState(state int)

func (*Mob) ResetAppearanceChanged

func (m *Mob) ResetAppearanceChanged()

func (*Mob) ResetFighting

func (m *Mob) ResetFighting()

ResetFighting Resets melee fight related variables

func (*Mob) ResetPath

func (m *Mob) ResetPath()

ResetPath Sets the mobs path to nil, to stop the traversal of the path instantly

func (*Mob) ResetRegionMoved

func (m *Mob) ResetRegionMoved()

func (*Mob) ResetRegionRemoved

func (m *Mob) ResetRegionRemoved()

func (*Mob) ResetSpriteUpdated

func (m *Mob) ResetSpriteUpdated()

func (*Mob) ResetState

func (m *Mob) ResetState()

func (*Mob) SessionCache

func (m *Mob) SessionCache() *entity.AttributeList

func (*Mob) SetAimPoints

func (m *Mob) SetAimPoints(i int)

SetAimPoints Sets the players aim points to i.

func (*Mob) SetAppearanceChanged

func (m *Mob) SetAppearanceChanged()

func (*Mob) SetArmourPoints

func (m *Mob) SetArmourPoints(i int)

SetArmourPoints Sets the players armour points to i.

func (*Mob) SetCoords

func (m *Mob) SetCoords(x, y int, teleport bool)

SetCoords Sets the mobs locations coordinates.

func (*Mob) SetDirection

func (m *Mob) SetDirection(direction int)

SetDirection Sets the mobs direction.

func (*Mob) SetFightMode

func (m *Mob) SetFightMode(i int)

SetFightMode Sets the players fightmode to i. 0=all,1=attack,2=defense,3=strength

func (*Mob) SetFightRound

func (m *Mob) SetFightRound(i int)

func (*Mob) SetFightTarget

func (m *Mob) SetFightTarget(m2 entity.MobileEntity)

func (*Mob) SetMagicPoints

func (m *Mob) SetMagicPoints(i int)

SetMagicPoints Sets the players magic points to i

func (*Mob) SetPath

func (m *Mob) SetPath(path *Pathway)

SetPath Sets the mob's current pathway to path. If path is nil, effectively resets the mobs path.

func (*Mob) SetPowerPoints

func (m *Mob) SetPowerPoints(i int)

SetPowerPoints Sets the players power points to i

func (*Mob) SetPrayerPoints

func (m *Mob) SetPrayerPoints(i int)

SetPrayerPoints Sets the players prayer points to i

func (*Mob) SetRangedPoints

func (m *Mob) SetRangedPoints(i int)

SetRangedPoints Sets the players ranged points tp i.

func (*Mob) SetRegionMoved

func (m *Mob) SetRegionMoved()

UpdateSelf Sets the synchronization flag for whether this mob has moved to true.

func (*Mob) SetRegionRemoved

func (m *Mob) SetRegionRemoved()

SetRegionRemoved Sets the synchronization flag for whether this mob needs to be removed to true.

func (*Mob) SetSpriteUpdated

func (m *Mob) SetSpriteUpdated()

SetSpriteUpdated Sets the synchronization flag for whether this mob changed directions to true.

func (*Mob) Skills

func (m *Mob) Skills() *entity.SkillTable

func (*Mob) Skulls

func (m *Mob) Skulls() map[uint64]time.Time

func (*Mob) State

func (m *Mob) State() int

func (*Mob) StyleBonus

func (m *Mob) StyleBonus(stat int) int

func (*Mob) TargetMob

func (m *Mob) TargetMob() entity.MobileEntity

func (*Mob) TargetNpc

func (m *Mob) TargetNpc() *NPC

func (*Mob) TargetPlayer

func (m *Mob) TargetPlayer() *Player

func (*Mob) UpdateLastFight

func (m *Mob) UpdateLastFight()

func (*Mob) UpdateLastRetreat

func (m *Mob) UpdateLastRetreat()

func (*Mob) WalkTo

func (m *Mob) WalkTo(end entity.Location) bool

type MobList

type MobList struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MobList a container type for holding entity.MobileEntitys

func NewMobList

func NewMobList() *MobList

NewMobList returns a pointer to a newly pre-allocated MobList, with an initial capacity of 255.

func (*MobList) Add

func (l *MobList) Add(m entity.MobileEntity) int

Add Adds a entity.MobileEntity to this MobList

func (*MobList) Contains

func (l *MobList) Contains(mob entity.MobileEntity) bool

Size returns the number of mobile entitys entered into this list.

func (*MobList) Get

func (l *MobList) Get(idx int) entity.MobileEntity

func (*MobList) Range

func (l *MobList) Range(action func(entity.MobileEntity) bool) int

Range Runs action(entity.MobileEntity) for each entity.MobileEntity in the lists collection, until either running out of entries, or action returns true.

func (*MobList) RangeNpcs

func (l *MobList) RangeNpcs(action func(*NPC) bool) int

func (*MobList) RangePlayers

func (l *MobList) RangePlayers(action func(*Player) bool) int

func (*MobList) Remove

func (l *MobList) Remove(m entity.MobileEntity) bool

Remove removes a entity.MobileEntity from this list and reslices the collection.

func (*MobList) Size

func (l *MobList) Size() int

Size returns the number of mobile entitys entered into this list.

type MobState

type MobState = int

type NPC

type NPC struct {
	Mob
	ID           int
	StartPoint   entity.Location
	Boundaries   [2]entity.Location
	Steps, Ticks int
	// contains filtered or unexported fields
}

NPC Represents a single non-playable character within the game world.

func AsNpc

func AsNpc(m entity.Entity) *NPC

func GetNpc

func GetNpc(index int) *NPC

GetNpc Returns the NPC with the specified game index.

func NewNpc

func NewNpc(id, startX, startY, minX, maxX, minY, maxY int) *NPC

NewNpc Creates a new NPC and returns a reference to it

func NpcNearest

func NpcNearest(id, x, y int) *NPC

NpcNearest looks for the NPC with the given ID, that is the closest to the given coordinates and then returns it. Returns nil if it can not find an NPC to fit the given description.

func NpcVisibleFrom

func NpcVisibleFrom(id, x, y int) *NPC

NpcVisibleFrom looks for any NPC with the given ID, that is within a 16x16 square surrounding the given coordinates, and then returns it. Returns nil if it can not find an NPC to fit the given parameters.

func (*NPC) Aggressive

func (n *NPC) Aggressive() bool

Returns true if this NPCs definition has the aggressive hostility bit set.

func (*NPC) Attackable

func (n *NPC) Attackable() bool

Returns true if this NPCs definition has the attackable hostility bit set.

func (*NPC) CacheDamage

func (n *NPC) CacheDamage(hash uint64, dmg int)

func (*NPC) Chat

func (n *NPC) Chat(target *Player, msgs ...string)

Chat sends chat messages to target and all of target's view area players, with a 1800ms(3 tick) delay between each message.

func (*NPC) ChatIndirect

func (n *NPC) ChatIndirect(target *Player, msg string)

ChatIndirect sends a chat message to target and all of target's view area players, without any delay.

func (*NPC) Command

func (n *NPC) Command() string

func (*NPC) DamageFrom

func (n *NPC) DamageFrom(m entity.MobileEntity, damage int, kind int) bool

func (*NPC) Enqueue

func (n *NPC) Enqueue(handle string, e interface{})

func (*NPC) IsNpc

func (n *NPC) IsNpc() bool

func (*NPC) IsPlayer

func (n *NPC) IsPlayer() bool

func (*NPC) Killed

func (n *NPC) Killed(killer entity.MobileEntity)

func (*NPC) MeleeDamage

func (n *NPC) MeleeDamage(target entity.MobileEntity) int

func (*NPC) Name

func (n *NPC) Name() string

func (*NPC) Remove

func (n *NPC) Remove()

func (*NPC) Respawn

func (n *NPC) Respawn()

func (*NPC) Retreats

func (n *NPC) Retreats() bool

Returns true if this NPCs definition has the retreat near death hostility bit set.

func (*NPC) SetLocation

func (n *NPC) SetLocation(l entity.Location, teleport bool)

func (*NPC) Teleport

func (n *NPC) Teleport(x, y int)

func (*NPC) TraversePath

func (n *NPC) TraversePath()

TraversePath If the mob has a path, calling this method will change the mobs location to the next location described by said Path data structure. This should be called no more than once per game tick.

func (*NPC) Type

func (n *NPC) Type() entity.Type

type NpcAction

type NpcAction = func(*Player, *NPC)

NpcAction A type alias for an NPC related action.

type NpcActionPredicate

type NpcActionPredicate = func(*Player, *NPC) bool

NpcActionPredicate A type alias for an NPC related action predicate.

type NpcBlockingTrigger

type NpcBlockingTrigger struct {
	Check  func(*Player, *NPC) bool
	Action func(*Player, *NPC)
}

type NpcTrigger

type NpcTrigger struct {
	// Check returns true if this handler should run.
	Check func(*NPC) bool
	// Action is the function that will run if Check returned true.
	Action func(*Player, *NPC)
}

NpcTrigger A type that defines a callback to run when certain NPC actions are performed, and a predicate to decide whether or not the callback should run

type Object

type Object struct {
	Entity
	ID        int
	Direction byte
	Boundary  bool
}

Object Represents a game object in the world.

func GetObject

func GetObject(x, y int) *Object

GetObject If there is an object at these coordinates, returns it. Otherwise, returns nil.

func NewObject

func NewObject(id, direction, x, y int, boundary bool) *Object

NewObject Returns a reference to a new instance of a game object.

func ReplaceObject

func ReplaceObject(old *Object, newID int) *Object

ReplaceObject Replaces old with a new game object with all of the same characteristics, except it's ID set to newID.

func (*Object) Boundaries

func (o *Object) Boundaries() [2]entity.Location

func (*Object) ClipType

func (o *Object) ClipType() int

ClipType returns a unique identifier representing what kind of collisions with other entities to account for when it is used in-game.

Doors (incl. gates) cause directional blocking only, while open doors do not block, similar to how ferns and signs and portraits and etc; these type of objects cause no blocking of any directions. doors are types 2 for shut and 3 for open

The only other type is a solid object, e.g a chest or a stall or a table, which causes the entire tile(s) this object stands on to be blocked regardless of the origin of the other entity! solid objects are type 1

TODO: type 0 do anything or just a nil-like value?

func (*Object) Command

func (o *Object) Command(click int) string

func (*Object) Command1

func (o *Object) Command1() string

Name checks if an object definition exists for this object, and if so returns the name associated with it.

func (*Object) Command2

func (o *Object) Command2() string

func (*Object) Defined

func (o *Object) Defined() bool

func (*Object) Height

func (o *Object) Height() int

Height The height measured in game tiles that this object takes up in the game world.

func (*Object) Name

func (o *Object) Name() string

Name checks if an object definition exists for this object, and if so returns the name associated with it.

func (*Object) String

func (o *Object) String() string

func (*Object) TypeData

func (o *Object) TypeData() mapBarrier

func (*Object) Width

func (o *Object) Width() int

Width The width measured in game tiles that this object takes up in the game world.

type ObjectTrigger

type ObjectTrigger struct {
	// Check returns true if this handler should run.
	Check func(*Object, int) bool
	// Action is the function that will run if Check returned true.
	Action func(*Player, *Object, int)
}

ObjectTrigger A type that defines a callback to run when certain object actions are performed, and a predicate to decide whether or not the callback should run

type Pathfinder

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

func NewPathfinder

func NewPathfinder(start, end entity.Location) *Pathfinder

NewPathfinder Returns a new A* pathfinder instance to derive an optimal path from start to end.

func (Pathfinder) Len

func (q Pathfinder) Len() int

func (Pathfinder) Less

func (q Pathfinder) Less(i, j int) bool

func (*Pathfinder) MakePath

func (p *Pathfinder) MakePath() *Pathway

func (*Pathfinder) Pop

func (q *Pathfinder) Pop() interface{}

func (*Pathfinder) Push

func (q *Pathfinder) Push(x interface{})

func (Pathfinder) Swap

func (q Pathfinder) Swap(i, j int)

type Pathway

type Pathway struct {
	sync.RWMutex
	StartX, StartY  int
	WaypointsX      []int
	WaypointsY      []int
	CurrentWaypoint int
}

Pathway Represents a path for a mobile entity to traverse across the virtual world.

func MakePath

func MakePath(start, end Location) (*Pathway, bool)

Returns an optimal path from start location to end location as decided by way of the AStar pathfinding algorithm. If a path isn't found within a certain constrained number of steps, the algorithm returns nil to free up the CPU.

func NewPathway

func NewPathway(destX, destY int, waypointsX, waypointsY []int) *Pathway

NewPathway returns a new Pathway with the specified variables. destX and destY are a straight line, and waypoints define turns from that point.

func NewPathwayToCoords

func NewPathwayToCoords(destX, destY int) *Pathway

NewPathwayToCoords returns a new Pathway pointing to the specified location. Will attempt traversal to l via a simple algorithm: if curX < destX then increase, if curX > destX then decrease, same for y, until equal.

func NewPathwayToLocation

func NewPathwayToLocation(l entity.Location) *Pathway

NewPathwayToLocation returns a new Pathway pointing to the specified location. Will attempt traversal to l via a simple algorithm: if curX < destX then increase, if curX > destX then decrease, same for y, until equal.

type Plane

type Plane = int

Direction represents directions that mobs can face within the game world. Ranges from 1-8

const (
	//PlaneGround Represents the value for the ground-level plane
	PlaneGround Plane = iota
	//PlaneSecond Represents the value for the second-story plane
	PlaneSecond
	//PlaneThird Represents the value for the third-story plane
	PlaneThird
	//PlaneBasement Represents the value for the basement plane
	PlaneBasement
)

type Player

type Player struct {
	context.Context
	LocalPlayers     *MobList
	LocalNPCs        *MobList
	LocalObjects     *entityList
	LocalItems       *entityList
	FriendList       *social.FriendsList
	IgnoreList       []uint64
	Appearance       entity.AppearanceTable
	KnownAppearances map[int]int
	AppearanceReq    []*Player
	Socket           stdnet.Conn
	Attributes       *entity.AttributeList
	Inventory        *Inventory

	TradeOffer *Inventory
	DuelOffer  *Inventory
	Duel       struct {
		Rules    [4]bool
		Accepted [2]bool
		Target   *Player
		Inventory
	}

	ActionLock sync.RWMutex
	ReplyMenuC chan int8

	Cancel func()

	Websocket         bool
	InQueue, OutQueue chan *net.Packet
	Reader            *bufio.Reader

	Writer        net.WriteFlusher
	DatabaseIndex int
	OpCiphers     [2]*isaac.ISAAC
	Mob
	// contains filtered or unexported fields
}

Player A player in our game world.

func AsPlayer

func AsPlayer(m entity.Entity) *Player

func NewPlayer

func NewPlayer(socket stdnet.Conn) *Player

NewPlayer Returns a reference to a new player, with context.Background as parent

func NewPlayerCtx

func NewPlayerCtx(server context.Context, socket stdnet.Conn) *Player

NewPlayerCtx Returns a reference to a new player with a parent context.

func (*Player) ActivatePrayer

func (p *Player) ActivatePrayer(idx int)

func (*Player) AddItem

func (p *Player) AddItem(id, amount int)

AddItem Adds amount of the item with specified id to the players inventory, if possible, and updates the client about it.

func (*Player) AddSkull

func (p *Player) AddSkull(user uint64)

func (*Player) AppearanceTicket

func (p *Player) AppearanceTicket() int

func (*Player) AtObject

func (p *Player) AtObject(object *Object) bool

func (*Player) Attribute

func (p *Player) Attribute(id string) interface{}

func (*Player) Bank

func (p *Player) Bank() *Inventory

func (*Player) BoolAttribute

func (p *Player) BoolAttribute(id string) bool

func (*Player) Cache

func (p *Player) Cache(name string) interface{}

func (*Player) CanAttack

func (p *Player) CanAttack(target entity.MobileEntity) bool

func (*Player) CanReachDiag

func (p *Player) CanReachDiag(bounds [2]entity.Location) bool

func (*Player) CanWalk

func (p *Player) CanWalk() bool

CanWalk returns true if this player is in a state that allows walking.

func (*Player) Chat

func (p *Player) Chat(msgs ...string)

Chat sends a player NPC chat message packet to the player and all other players around it. If multiple msgs are provided, will sleep the goroutine for 3-4 ticks between each message, depending on length of message.

func (*Player) ChatBlocked

func (p *Player) ChatBlocked() bool

ChatBlocked returns true if public chat is blocked for this player.

func (*Player) CloseBank

func (p *Player) CloseBank()

CloseBank closes the bank screen for this player and sets the appropriate state variables

func (*Player) CloseDuel

func (p *Player) CloseDuel()

func (*Player) CloseOptionMenu

func (p *Player) CloseOptionMenu()

CloseOptionMenu closes any open option menus.

func (*Player) CloseShop

func (p *Player) CloseShop()

CloseBank closes the bank screen for this player and sets the appropriate state variables

func (*Player) CloseTradeScreens

func (p *Player) CloseTradeScreens()

func (*Player) CombatDelta

func (p *Player) CombatDelta(other entity.MobileEntity) int

CombatDelta returns the difference between our combat level and the other mobs combat level

func (*Player) Connected

func (p *Player) Connected() bool

Connected returns true if the player is connected, false otherwise.

func (*Player) CurrentIP

func (p *Player) CurrentIP() string

CurrentIP returns the remote IP address this player connected from

func (*Player) CurrentShop

func (p *Player) CurrentShop() *Shop

func (*Player) Damage

func (p *Player) Damage(amt int)

Damage sends a player damage bubble for this player to itself and any nearby players.

func (*Player) DamageFrom

func (p *Player) DamageFrom(m entity.MobileEntity, damage int, kind int) bool

func (*Player) DeactivatePrayer

func (p *Player) DeactivatePrayer(idx int)

func (*Player) DequipItem

func (p *Player) DequipItem(item *Item)

DequipItem removes an item from this players equips, and sends inventory and equipment bonuses.

func (*Player) Destroy

func (p *Player) Destroy()

Destroy sends a kill signal to the underlying client to tear down all of the I/O routines and save the player. Note: This should probably be ran in its own goroutine as it saves the player to the database.

func (*Player) DistributeMeleeExp

func (p *Player) DistributeMeleeExp(experience float64)

DistributeMeleeExp This is a helper method to distribute experience amongst the players melee stats according to its current fight stance.

If the player is in controlled stance, each melee skill gets (experience). Otherwise, whatever fight stance the player was in will get (experience)*3, and hits will get (experience).

func (*Player) DuelAccepted

func (p *Player) DuelAccepted(screen int) bool

DuelAccepted returns the status of the specified duel negotiation screens accepted button for this player. Valid screens are 1 and 2.

func (*Player) DuelBlocked

func (p *Player) DuelBlocked() bool

DuelBlocked returns true if duel requests are blocked for this player.

func (*Player) DuelEquipment

func (p *Player) DuelEquipment() bool

func (*Player) DuelMagic

func (p *Player) DuelMagic() bool

func (*Player) DuelPrayer

func (p *Player) DuelPrayer() bool

func (*Player) DuelRetreating

func (p *Player) DuelRetreating() bool

func (*Player) DuelRules

func (p *Player) DuelRules() [4]bool

func (*Player) Enqueue

func (p *Player) Enqueue(id string, e interface{})

func (*Player) EquipItem

func (p *Player) EquipItem(item *Item)

EquipItem equips an item to this player, and sends inventory and equipment bonuses.

func (*Player) Equips

func (p *Player) Equips() []int

func (*Player) Fatigue

func (p *Player) Fatigue() int

Fatigue Returns the players current fatigue.

func (*Player) FirstLogin

func (p *Player) FirstLogin() bool

FirstLogin returns true if this player has never logged in before, otherwise false.

func (*Player) FriendBlocked

func (p *Player) FriendBlocked() bool

FriendBlocked returns true if private chat is blocked for this player.

func (*Player) FriendsWith

func (p *Player) FriendsWith(other uint64) bool

FriendsWith returns true if specified username is in our friend entityList.

func (*Player) GetClientSetting

func (p *Player) GetClientSetting(id int) bool

GetClientSetting looks up the client setting with the specified ID, and returns it. If it can't be found, returns false.

func (*Player) Ignoring

func (p *Player) Ignoring(hash uint64) bool

Ignoring returns true if specified username is in our ignore entityList.

func (*Player) IncCurStat

func (p *Player) IncCurStat(idx int, lvl int)

IncCurStat sets this players current stat at idx to Current(idx)+lvl and updates the client about it.

func (*Player) IncExp

func (p *Player) IncExp(idx int, amt int)

SetCurStat sets this players current stat at idx to lvl and updates the client about it.

func (*Player) Initialize

func (p *Player) Initialize()

Initialize informs the client of all of the various attributes of this player, and starts the stat normalization routine.

func (*Player) IsDueling

func (p *Player) IsDueling() bool

IsDueling returns true if this player is negotiating a duel, otherwise returns false.

func (*Player) IsNpc

func (p *Player) IsNpc() bool

func (*Player) IsPanelOpened

func (p *Player) IsPanelOpened() bool

func (*Player) IsPlayer

func (p *Player) IsPlayer() bool

func (*Player) IsTrading

func (p *Player) IsTrading() bool

IsTrading returns true if this player is in a trade, otherwise returns false.

func (*Player) IsWebsocket

func (p *Player) IsWebsocket() bool

func (*Player) ItemBubble

func (p *Player) ItemBubble(id int)

ItemBubble sends an item action bubble for this player to itself and any nearby players.

func (*Player) Killed

func (p *Player) Killed(killer entity.MobileEntity)

Killed kills this player, dropping all of its items where it stands.

func (*Player) Message

func (p *Player) Message(msg string)

Message sends a message to the player.

func (*Player) NearbyNpcs

func (p *Player) NearbyNpcs() (npcs []*NPC)

NearbyNpcs Returns nearby NPCs.

func (*Player) NearbyObjects

func (p *Player) NearbyObjects() (objects []entity.Entity)

NearbyObjects Returns nearby objects.

func (*Player) NearbyPlayers

func (p *Player) NearbyPlayers() (players []*Player)

NearbyPlayers Returns nearby players.

func (*Player) NewItems

func (p *Player) NewItems() (items []*GroundItem)

NewItems Returns nearby ground items that this player is unaware of.

func (*Player) NewNPCs

func (p *Player) NewNPCs() (npcs *MobList)

NewNPCs Returns nearby NPCs that this player is unaware of.

func (*Player) NewObjects

func (p *Player) NewObjects() (objects []*Object)

NewObjects Returns nearby objects that this player is unaware of.

func (*Player) NewPlayers

func (p *Player) NewPlayers() (players *MobList)

NewPlayers Returns nearby players that this player is unaware of.

func (*Player) NextToCoords

func (p *Player) NextToCoords(x, y int) bool

func (*Player) OpenAppearanceChanger

func (p *Player) OpenAppearanceChanger()

OpenAppearanceChanger If the player is not fighting or trading, opens the appearance window.

func (*Player) OpenBank

func (p *Player) OpenBank()

OpenBank opens a bank screen for the player and sets the appropriate state variables.

func (*Player) OpenDuelConfirm

func (p *Player) OpenDuelConfirm(target *Player)

func (*Player) OpenDuelScreen

func (p *Player) OpenDuelScreen(target *Player)

func (*Player) OpenOptionMenu

func (p *Player) OpenOptionMenu(options ...string) int

func (*Player) OpenShop

func (p *Player) OpenShop(shop *Shop)

OpenBank opens a shop screen for the player and sets the appropriate state variables.

func (*Player) OpenSleepScreen

func (p *Player) OpenSleepScreen()

func (*Player) OpenTradeConfirmation

func (p *Player) OpenTradeConfirmation(target *Player)

func (*Player) OpenTradeScreen

func (p *Player) OpenTradeScreen(target *Player)

func (*Player) PlaySound

func (p *Player) PlaySound(soundName string)

PlaySound sends a command to the client to play a sound by its file name.

func (*Player) PrayerOff

func (p *Player) PrayerOff(idx int)

func (*Player) PrayerOn

func (p *Player) PrayerOn(idx int)

func (*Player) ProcPacketsIn

func (p *Player) ProcPacketsIn()

func (*Player) ProcPacketsOut

func (p *Player) ProcPacketsOut()

func (*Player) QuestBroadcast

func (p *Player) QuestBroadcast(owner, target entity.MobileEntity, message string)

QuestBroadcast Broadcasts a string as a message posted into the players quest chat history to the player and any nearby players.

func (*Player) QueueHitsplat

func (p *Player) QueueHitsplat(owner entity.MobileEntity, dmg int)

QueueHitsplat Adds a hit splat to a locked hit-splat queue

func (*Player) QueueItemBubble

func (p *Player) QueueItemBubble(owner *Player, id int)

QueueItemBubble Adds an action item bubble to a locked item bubble queue

func (*Player) QueueNpcChat

func (p *Player) QueueNpcChat(owner, target entity.MobileEntity, message string)

QueueNpcChat Adds a message to a locked quest-chat queue

func (*Player) QueueNpcSplat

func (p *Player) QueueNpcSplat(owner *NPC, dmg int)

QueueNpcSplat Adds a message to a locked quest-chat queue

func (*Player) QueueProjectile

func (p *Player) QueueProjectile(owner, target entity.MobileEntity, kind int)

QueueProjectile Adds a missile to a locked projectile queue

func (*Player) QueuePublicChat

func (p *Player) QueuePublicChat(owner entity.MobileEntity, message string)

QueuePublicChat Adds a message to a locked public-chat queue

func (*Player) QueueQuestChat

func (p *Player) QueueQuestChat(owner, _ entity.MobileEntity, message string)

QueueQuestChat Adds a message to a locked quest-chat queue Second arg reserved as target for message

func (*Player) Rank

func (p *Player) Rank() int

func (*Player) Read

func (p *Player) Read(data []byte) (n int, err error)

Read implements an io.Reader that detects what type of connection the underlying socket is using, and interprets the network byte stream accordingly. Websockets require a lot of extra book-keeping to be used like this, and as such

func (*Player) ReadPacket

func (p *Player) ReadPacket() (*net.Packet, error)

func (*Player) Reconnecting

func (p *Player) Reconnecting() bool

Reconnecting returns true if the player is reconnecting, false otherwise.

func (*Player) RemoteAddress

func (p *Player) RemoteAddress() string

LocalAddress Returns the remote IP:port that this player connected from, or N/A if this player never connected somehow

func (*Player) RemoveCache

func (p *Player) RemoveCache(name string)

func (*Player) ResetAll

func (p *Player) ResetAll()

ResetAll in order, calls ResetFighting, ResetTrade, ResetTickAction, ResetFollowing, and CloseOptionMenu.

func (*Player) ResetAllExceptDueling

func (p *Player) ResetAllExceptDueling()

func (*Player) ResetDuel

func (p *Player) ResetDuel()

ResetDuel resets duel-related variables.

func (*Player) ResetDuelAccepted

func (p *Player) ResetDuelAccepted()

ResetDuelAccepted Resets receivers duel negotiation settings to indicate that neither screens are accepted.

func (*Player) ResetDuelRules

func (p *Player) ResetDuelRules()

func (*Player) ResetDuelTarget

func (p *Player) ResetDuelTarget()

ResetDuelTarget Removes receivers duel target, if any.

func (*Player) ResetFighting

func (p *Player) ResetFighting()

func (*Player) ResetTickAction

func (p *Player) ResetTickAction()

ResetTickAction clears the distanced action, if any is queued. Should be called any time the player is deliberately performing an action.

func (*Player) ResetTrade

func (p *Player) ResetTrade()

ResetTrade resets trade-related variables.

func (*Player) SendEquipBonuses

func (p *Player) SendEquipBonuses()

SendEquipBonuses sends the current equipment bonuses of this player.

func (*Player) SendInventory

func (p *Player) SendInventory()

SendInventory sends inventory information to this player.

func (*Player) SendMessageBox

func (p *Player) SendMessageBox(msg string, big bool)

func (*Player) SendPlane

func (p *Player) SendPlane()

SendPlane sends the current plane of this player.

func (*Player) SendPrayers

func (p *Player) SendPrayers()

func (*Player) SendStat

func (p *Player) SendStat(idx int)

SendStat sends the information for the stat at idx to the player.

func (*Player) SendStatExp

func (p *Player) SendStatExp(idx int)

SendStatExp sends the experience information for the stat at idx to the player.

func (*Player) SendStats

func (p *Player) SendStats()

SendStats sends all stat information to this player.

func (*Player) SendUpdateTimer

func (p *Player) SendUpdateTimer()

SendUpdateTimer sends a system update countdown timer to the client.

func (*Player) Server

func (p *Player) Server() Server

func (*Player) ServerSeed

func (p *Player) ServerSeed() uint64

ServerSeed returns the seed for the ISAAC cipher provided by the game for this player, if set, otherwise returns 0

func (*Player) SetCache

func (p *Player) SetCache(name string, val interface{})

func (*Player) SetClientSetting

func (p *Player) SetClientSetting(id int, flag bool)

SetClientSetting sets the specified client setting to flag.

func (*Player) SetConnected

func (p *Player) SetConnected(flag bool)

SetConnected sets the player's connected status to flag.

func (*Player) SetCurStat

func (p *Player) SetCurStat(idx int, lvl int)

SetCurStat sets this players current stat at idx to lvl and updates the client about it.

func (*Player) SetDuelAccepted

func (p *Player) SetDuelAccepted(screen int, b bool)

DuelAccepted returns the status of the specified duel negotiation screens accepted button for this player. Valid screens are 1 and 2.

func (*Player) SetDuelRule

func (p *Player) SetDuelRule(index int, b bool)

SetDuelRule sets the duel rule associated with the specified index to b. Valid rule indices are 0 through 3.

func (*Player) SetDuelTarget

func (p *Player) SetDuelTarget(p1 *Player)

SetDuelTarget Sets p1 as the receivers dueling target.

func (*Player) SetFatigue

func (p *Player) SetFatigue(i int)

SetFatigue Sets the players current fatigue to i.

func (*Player) SetFirstLogin

func (p *Player) SetFirstLogin(flag bool)

SetFirstLogin sets the player's persistent logged in before status to flag.

func (*Player) SetLocation

func (p *Player) SetLocation(l entity.Location, teleport bool)

func (*Player) SetMaxStat

func (p *Player) SetMaxStat(idx int, lvl int)

SetMaxStat sets this players maximum stat at idx to lvl and updates the client about it.

func (*Player) SetPrivacySettings

func (p *Player) SetPrivacySettings(chatBlocked, friendBlocked, tradeBlocked, duelBlocked bool)

SetPrivacySettings sets privacy settings to specified values.

func (*Player) SetReconnecting

func (p *Player) SetReconnecting(flag bool)

SetReconnecting sets the player's reconnection status to flag.

func (*Player) SetServerSeed

func (p *Player) SetServerSeed(seed uint64)

SetServerSeed sets the player's stored game seed to seed for later comparison to ensure we decrypted the login block properly and the player received the proper seed.

func (*Player) SetSkulled

func (p *Player) SetSkulled(val bool)

func (*Player) SetStat

func (p *Player) SetStat(idx, lvl int)

SetStat sets the current, maximum, and experience levels of the skill at idx to lvl, and updates the client about it.

func (*Player) SetTickAction

func (p *Player) SetTickAction(action func() bool)

SetTickAction queues a distanced action to run every game engine tick before path traversal, if action returns true, it will be reset.

func (*Player) SetTradeTarget

func (p *Player) SetTradeTarget(index int)

SetTradeTarget Sets the variable for the index of the player we are trying to trade

func (*Player) SetTradeTargetAccepted

func (p *Player) SetTradeTargetAccepted()

func (*Player) SkullOn

func (p *Player) SkullOn(p1 *Player)

func (*Player) Skulled

func (p *Player) Skulled() bool

func (*Player) SkulledOn

func (p *Player) SkulledOn(user uint64) bool

func (*Player) Skulls

func (p *Player) Skulls() map[uint64]time.Time

func (*Player) StartCombat

func (p *Player) StartCombat(defender entity.MobileEntity)

func (*Player) String

func (p *Player) String() string

String returns a string populated with the more identifying features of this player.

func (*Player) Teleport

func (p *Player) Teleport(x, y int)

func (*Player) TickAction

func (p *Player) TickAction() func() bool

func (*Player) TogglePrayer

func (p *Player) TogglePrayer(idx int) bool

func (*Player) TradeBlocked

func (p *Player) TradeBlocked() bool

TradeBlocked returns true if trade requests are blocked for this player.

func (*Player) TradeTarget

func (p *Player) TradeTarget() int

TradeTarget returns the game index of the player we are trying to trade with, or -1 if we have not made a trade request.

func (*Player) TraversePath

func (p *Player) TraversePath()

TraversePath if the mob has a path, calling this method will change the mobs location to the next location described by said Path data structure. This should be called no more than once per game tick.

func (*Player) Type

func (p *Player) Type() entity.Type

func (*Player) Unregister

func (p *Player) Unregister()

func (*Player) UpdateAppearance

func (p *Player) UpdateAppearance()

func (*Player) UpdateDuel

func (p *Player) UpdateDuel()

func (*Player) UpdateDuelAccept

func (p *Player) UpdateDuelAccept(accept bool)

func (*Player) UpdateDuelSettings

func (p *Player) UpdateDuelSettings()

func (*Player) UpdateRegion

func (p *Player) UpdateRegion(x, y int)

UpdateRegion if this player is currently in a region, removes it from that region, and adds it to the region at x,y

func (*Player) UpdateStatus

func (p *Player) UpdateStatus(status bool)

func (*Player) UpdateTradeOffer

func (p *Player) UpdateTradeOffer(target *Player)

func (*Player) UpdatedRegions

func (p *Player) UpdatedRegions()

func (*Player) Username

func (p *Player) Username() string

func (*Player) UsernameHash

func (p *Player) UsernameHash() uint64

func (*Player) ViewRadius

func (p *Player) ViewRadius() int

func (*Player) WalkingArrivalAction

func (p *Player) WalkingArrivalAction(t entity.MobileEntity, dist int, action func())

WalkingArrivalAction Runs `action` once arriving within dist (min 1 max 2 tiles) of `target` mob, with a straight line of sight, e.g no intersecting boundaries, large objects, walls, etc. Runs everything on game engine ticks, retries until catastrophic failure or success.

func (*Player) WalkingRangedAction

func (p *Player) WalkingRangedAction(t entity.MobileEntity, fn func())

WalkingRangedAction Runs `fn` once arriving anywhere within 5 tiles in any direction of `t`, with a straight line of sight, e.g no intersecting boundaries, large objects, walls, etc. Runs everything on game engine ticks, retries until catastrophic failure or success.

func (*Player) WriteNow

func (p *Player) WriteNow(packet net.Packet)

func (*Player) WritePacket

func (p *Player) WritePacket(packet *net.Packet)

WritePacket sends a net to the client.

type PlayerList

type PlayerList struct {
	sync.RWMutex
	PlayersList
	// contains filtered or unexported fields
}

func (*PlayerList) AsyncRange

func (m *PlayerList) AsyncRange(fn func(*Player))

func (*PlayerList) Contains

func (m *PlayerList) Contains(player *Player) bool

Contains Returns true if this player is assigned to a slot in the set, otherwise returns false.

func (*PlayerList) ContainsHash

func (m *PlayerList) ContainsHash(hash uint64) bool

ContainsHash Returns true if there is a client mapped to this username hash is in this collection, otherwise returns false.

func (*PlayerList) Find

func (m *PlayerList) Find(player *Player) int

Find Returns the slot that this player occupies in the set.

func (*PlayerList) FindHash

func (m *PlayerList) FindHash(hash uint64) (*Player, bool)

FindHash Returns the client with the base37 username `hash` if it exists and true, otherwise returns nil and false.

func (*PlayerList) FindIndex

func (m *PlayerList) FindIndex(index int) (*Player, bool)

FromIndex Returns the client with the index `index` if it exists and true, otherwise returns nil and false.

func (*PlayerList) ForEach

func (m *PlayerList) ForEach(action func(*Player) bool) int

Range Calls action for every active client in the collection.

func (*PlayerList) Put

func (m *PlayerList) Put(player *Player)

Put Finds the lowest available empty slot in the list, and puts the player there. This will also assign the players server index variable (*Player.Index) to the assigned slot.

func (*PlayerList) Range

func (m *PlayerList) Range(action func(*Player))

Range Calls action for every active client in the collection.

func (*PlayerList) Remove

func (m *PlayerList) Remove(player *Player)

Remove Removes a client from the set.

func (*PlayerList) Set

func (m *PlayerList) Set() []*Player

func (*PlayerList) Size

func (m *PlayerList) Size() int

Size Returns the size of the active client collection.

type PlayerService

type PlayerService interface {
	PlayerSave(*Player)
}
var DefaultPlayerService PlayerService

type PlayersList

type PlayersList map[*Player]struct{}

type Price

type Price int

Price type alias for item prices

func (Price) Scale

func (p Price) Scale(percent int) Price

Scale Calculates and returns the value for the requested percentage of the receiver price.

In other words, for sleeping bag with basePrice=30

player.Inventory.GetByID(1263).PriceScaled(100)

would be 30 and is the same as calling Price(). Any percent that is higher than 100 will scale the price up. E.g:

player.Inventory.GetByID(1263).PriceScaled(130)

would be 39; since 130%(??) of the base price is the value we want, to reach that from the base price(100%(30)), we can add 30%(9) to the base price(100%(30)), which gives us 130%(39), the value we want.

This is the same way RSC general stores priced items they sold. Additionally, though,

Any percent that is lower than 100 will scale the price down. E.g:

player.Inventory.GetByID(1263).PriceScaled(40)

would be 12. Since 40%(??) of the base price is our target, to reach that from 100%(30), we subtract 60%(18) from it. This is the same percentage used for RSC general stores initial sale prices. , we'd. is how we mimic canonical RSClassic general store pricing.

Upper bound for percent intended to basically not exist; in practice it's limited by the data type of the argument. Lower bound for percent is 10, anything lower will be treated as if it were 10%.

type Projectile

type Projectile struct {
	Kind   int
	Owner  entity.MobileEntity
	Target entity.MobileEntity
}

func NewProjectile

func NewProjectile(owner, target entity.MobileEntity, kind int) Projectile

type Sector

type Sector struct {
	Tiles [2304]CollisionMask
}

Sector Represents a sector of 48x48(2304) tiles in the game's landscape.

type Server

type Server interface {
	SubmitLogin(*Player)
	SubmitLogout(*Player)
	DebugTicks()
}

type Shop

type Shop struct {

	// True if this shop deals in unstocked items the player wants to sell, otherwise false.
	BuysUnstocked bool
	// The shop's base percentage at which it buys items from players.
	BasePurchasePercent int
	// The shop's base percentage at which it sells items to players.
	BaseSalePercent int
	// Contains all of the initial shop items that are always restocked and available, and their initial amounts.
	// Never change the contents of this unless you want to add permanently restocking items to a shop or something like that.
	Stock *ShopItems
	// Contains all of the active shop items and may differ greatly from Stock, but it can never remove things that are
	// in Stock entirely from itself(they will remain with Amount=0), and occasionally it normalizes itself, referencing
	// Stock for the normal amounts to replenish toward, and the default IDs of what items to replenish.
	Inventory *ShopItems
	// Descriptive name for this shop.
	Name string
	// List of players actively using the shop
	Players *MobList
}

func NewGeneralShop

func NewGeneralShop(name string) *Shop

Creates a new general shop, and adds it automatically to the world-local ShopContainer instance before returning it

Returns: Shops.get(name), after building and adding a new general shop to it, using a generic general shop definition.

func NewShop

func NewShop(percentPurchasesPrice, percentSalesPrice int, stock shopItemSet, name string) *Shop

NewShop creates a new Shop instance using the arguments provided, and returns it.

Returns: a new Shop instance, made with the given arguments

func (*Shop) AppraiseItem

func (s *Shop) AppraiseItem(id int) int

func (*Shop) Clone

func (s *Shop) Clone() *Shop

Clone makes a clone of the receiver shop and returns it.

func (*Shop) DeltaPercentMod

func (s *Shop) DeltaPercentMod(item *Item) int

DeltaPercentMod calculates the percentage to scale the item's price up or down from its respective base percentage. The formula simply subtracts the shop's base stocked amount of item from item's amount, and multiplies the difference by ShopNormalDeltaRate.

func (*Shop) DeltaPercentModID

func (s *Shop) DeltaPercentModID(id int) int

func (*Shop) Remove

func (s *Shop) Remove(id int, amount int) bool

type ShopContainer

type ShopContainer struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*ShopContainer) Add

func (s *ShopContainer) Add(name string, shop *Shop)

func (*ShopContainer) Contains

func (s *ShopContainer) Contains(name string) bool

func (*ShopContainer) Get

func (s *ShopContainer) Get(name string) *Shop

func (*ShopContainer) Range

func (s *ShopContainer) Range(fn func(*Shop))

func (*ShopContainer) Remove

func (s *ShopContainer) Remove(name string)

type ShopItems

type ShopItems struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*ShopItems) Add

func (s *ShopItems) Add(item *Item)

func (*ShopItems) AddItem

func (s *ShopItems) AddItem(id, amt int)

func (*ShopItems) Clone

func (s *ShopItems) Clone() *ShopItems

Clone will make a new ShopItems collection populated with clones of the values in the existing collection set. Very useful to easily define an initial inventory and stock when defining a shop.

func (*ShopItems) Contains

func (s *ShopItems) Contains(id int) bool

Ensures safe access when requesting whether this collection contains a specific item by ID.

Returns: true if this shop items collection has any items with the provided ID, otherwise returns false.

func (*ShopItems) Count

func (s *ShopItems) Count(id int) int

Ensures safe access when requesting the current count of a specific item by ID in this shops inventory.

Returns: the inventorys amount of the specified item id, or 0 is no items matched this ID.

func (*ShopItems) Get

func (s *ShopItems) Get(id int) *Item

Returns: the shop item in this collection with the given ID, or if it can't find one, creates a new one with Amount=0, adds it to the collection for later usage, and returns it

func (*ShopItems) Range

func (s *ShopItems) Range(fn func(*Item) bool)

func (*ShopItems) Remove

func (s *ShopItems) Remove(removingItem *Item)

func (*ShopItems) RemoveID

func (s *ShopItems) RemoveID(id, amount int, remove bool)

func (*ShopItems) Size

func (s *ShopItems) Size() int

type SpellDef

type SpellDef map[string]interface{}

type Trigger

type Trigger func(*Player, interface{})

Jump to

Keyboard shortcuts

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