agentscape
Version:
Agentscape is a library for creating agent-based simulations. It provides a simple API for defining agents and their behavior, and for defining the environment in which the agents interact. Agentscape is designed to be flexible and extensible, allowing
101 lines (88 loc) • 2.88 kB
text/typescript
import RandomGenerator from './RandomGenerator'
export type ColorName = 'red' | 'green' | 'blue' | 'yellow' | 'orange' | 'purple' | 'pink' | 'black' | 'white' | 'gray' | 'brown'
export default class Color {
public r: number
public g: number
public b: number
public a: number
public static fromName(name: ColorName) {
switch (name) {
case 'red':
return Color.fromRGB(255, 0, 0)
case 'green':
return Color.fromRGB(57, 201, 0)
case 'blue':
return Color.fromRGB(0, 0, 255)
case 'yellow':
return Color.fromRGB(255, 255, 0)
case 'orange':
return Color.fromRGB(255, 165, 0)
case 'purple':
return Color.fromRGB(128, 0, 128)
case 'pink':
return Color.fromRGB(255, 192, 203)
case 'black':
return Color.fromRGB(0, 0, 0)
case 'white':
return Color.fromRGB(255, 255, 255)
case 'gray':
return Color.fromRGB(128, 128, 128)
case 'brown':
return Color.fromRGB(165, 42, 42)
}
}
public static fromRGB(r: number, g: number, b: number, a: number = 1) {
const color = new Color()
color.r = r
color.g = g
color.b = b
color.a = a
return color
}
public static fromHex(hex: string) {
const color = new Color()
color.r = parseInt(hex.slice(1, 3), 16)
color.g = parseInt(hex.slice(3, 5), 16)
color.b = parseInt(hex.slice(5, 7), 16)
color.a = 1
return color
}
public static random(rng: RandomGenerator) {
return Color.fromRGB(
rng.uniformInt(0,255),
rng.uniformInt(0,255),
rng.uniformInt(0,255),
1
)
}
public toRGB() {
return `rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`
}
public toHex() {
return `#${this.r.toString(16)}${this.g.toString(16)}${this.b.toString(16)}`
}
/**
* Returns a new color that is the result of blending this color with another color.
*/
public blend(color: Color, amount: number): Color {
const r = this.r + (color.r - this.r) * amount
const g = this.g + (color.g - this.g) * amount
const b = this.b + (color.b - this.b) * amount
return Color.fromRGB(r, g, b)
}
/**
* Lightens a color by a given percentage.
*/
public lighten(amount: number): Color {
return this.blend(Color.fromRGB(255, 255, 255), amount)
}
/**
* Darkens a color by a given percentage.
*/
public darken(amount: number): Color {
return this.blend(Color.fromRGB(0, 0, 0), amount)
}
public setOpacity(a: number): Color {
return Color.fromRGB(this.r, this.g, this.b, Math.max(0, Math.min(1, a)))
}
}