Skip to content

Commit

Permalink
Use more readonly
Browse files Browse the repository at this point in the history
Close #48.
  • Loading branch information
taylorhansen committed May 31, 2019
1 parent a67ce29 commit e4fa9aa
Show file tree
Hide file tree
Showing 17 changed files with 265 additions and 271 deletions.
4 changes: 2 additions & 2 deletions scripts/train/Experience.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
export interface Experience
{
/** State in which the action was taken. */
state: number[];
state: readonly number[];
/** ID of the Choice that was taken. */
action: number;
/** Reward gained from the action. */
reward: number;
/** Next state after taking the action. */
nextState: number[];
nextState: readonly number[];
/** ID of the best action that will be taken in the next state. */
nextAction: number;
}
2 changes: 1 addition & 1 deletion scripts/train/TrainBattle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { TrainNetwork } from "./TrainNetwork";
export class TrainBattle extends PSBattle
{
/** Buffer of Experience objects. */
public get experiences(): ReadonlyArray<Experience>
public get experiences(): readonly Experience[]
{
return this._experiences;
}
Expand Down
4 changes: 2 additions & 2 deletions scripts/train/TrainNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { Experience } from "./Experience";
export class TrainNetwork extends Network
{
/** Tensor data that generated `lastPrediction`. */
private lastStateData?: number[];
private lastStateData?: readonly number[];
/** Tensor data that generated `prediction`. */
private stateData?: number[];
private stateData?: readonly number[];
/**
* Whether to update `#lastStateData` on `#getPrediction()`. Resets back to
* true once that method is called.
Expand Down
12 changes: 6 additions & 6 deletions scripts/train/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,21 +67,21 @@ logStream.write = function(chunk: any, enc?: string | CB, cb?: CB)
};

/** Models to represent p1 and p2. */
type Models = {[P in PlayerID]: tf.LayersModel};
type Models = {readonly [P in PlayerID]: tf.LayersModel};

interface GameOptions extends Models
{
/** Maximum amount of turns before the game is considered a tie. */
maxTurns: number;
readonly maxTurns: number;
/**
* Whether to emit Experience objects, which will be used for learning
* later.
*/
emitExperiences?: boolean;
readonly emitExperiences?: boolean;
/** Path to the file in which to store debug info. */
logPath?: string;
readonly logPath?: string;
/** Logger object. */
logger?: Logger;
readonly logger?: Logger;
}

/** Result object returned from `play()`. */
Expand Down Expand Up @@ -208,7 +208,7 @@ async function play(options: GameOptions): Promise<GameResult>
* too much.
* @param epochs Number of epochs to run.
*/
async function learn(model: tf.LayersModel, experiences: Experience[],
async function learn(model: tf.LayersModel, experiences: readonly Experience[],
gamma: number, epochs: number): Promise<tf.History>
{
const dataset = datasetFromIteratorFn<tf.TensorContainerObject>(
Expand Down
5 changes: 3 additions & 2 deletions src/ai/Network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,15 @@ to create a new model with an output shape of (null, ${intToChoice.length})`);
}

/** Ensures that a network input shape is valid. */
private static isValidInputShape(shape: (number | null)[]): boolean
private static isValidInputShape(shape: readonly (number | null)[]): boolean
{
return shape.length === 2 && shape[0] === null &&
shape[1] === sizeBattleState;
}

/** Ensures that a network output shape is valid. */
private static isValidOutputShape(shape: (number | null)[]): boolean
private static isValidOutputShape(shape: readonly (number | null)[]):
boolean
{
return shape.length === 2 && shape[0] === null &&
shape[1] === intToChoice.length;
Expand Down
13 changes: 5 additions & 8 deletions src/battle/agent/Choice.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
const choiceIdsInternal =
/** Maps a choice name to its id number. */
export const choiceIds =
{
"move 1": 0, "move 2": 1, "move 3": 2, "move 4": 3, "switch 2": 4,
"switch 3": 5, "switch 4": 6, "switch 5": 7, "switch 6": 8
};

} as const;
/** The types of choices that can be made by the user. */
export type Choice = keyof typeof choiceIdsInternal;

/** Maps a choice name to its id number. */
export const choiceIds: Readonly<typeof choiceIdsInternal> = choiceIdsInternal;
export type Choice = keyof typeof choiceIds;

/** Maps a choice id number to its name. */
export const intToChoice: ReadonlyArray<Choice> = (function()
export const intToChoice: readonly Choice[] = (function()
{
const result: Choice[] = [];
(Object.keys(choiceIds) as Choice[]).forEach(
Expand Down
52 changes: 23 additions & 29 deletions src/battle/dex/dex-types.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/** Names of certain stats. */
export type StatName = "hp" | "atk" | "def" | "spa" | "spd" | "spe";

const typesInternal =
/** Set of Type names. Each type has a 0-based unique index. */
export const types =
{
bug: 0, dark: 1, dragon: 2, fire: 3, flying: 4, ghost: 5, electric: 6,
fighting: 7, grass: 8, ground: 9, ice: 10, normal: 11, poison: 12,
psychic: 13, rock: 14, steel: 15, water: 16, "???": 17
};
/** Set of Type names. Each type has a 0-based unique index. */
export const types: Readonly<typeof typesInternal> = typesInternal;
} as const;
/** The different types a pokemon can have. */
export type Type = keyof typeof typesInternal;
export type Type = keyof typeof types;

/** Set of HPType names. Each type has a 0-based unique index. */
export const hpTypes =
Expand All @@ -31,17 +30,13 @@ export const weatherItems: {readonly [T in WeatherType]: string} =
Sandstorm: "smoothrock", Hail: "icyrock"
};

const majorStatusesInternal =
/** Hold the set of all major status names. Empty string means no status. */
export const majorStatuses =
{
"": 0, brn: 1, par: 2, psn: 3, tox: 4, slp: 5, frz: 6
};
/** Hold the set of all major status names. Empty string means no status. */
export const majorStatuses: Readonly<typeof majorStatusesInternal> =
majorStatusesInternal;

} as const;
/** Major pokemon status conditions. */
export type MajorStatus = keyof typeof majorStatuses;

/**
* Checks if a value matches a major status.
* @param status Value to be checked.
Expand All @@ -52,18 +47,20 @@ export function isMajorStatus(status: any): status is MajorStatus
return majorStatuses.hasOwnProperty(status);
}

const boostNamesInternal =
/** Holds the set of all boostable stat names. */
export const statsExceptHP =
{atk: true, def: true, spa: true, spd: true, spe: true} as const;
/** Names of pokemon stats that can be boosted. */
export type StatExceptHP = keyof typeof statsExceptHP;

/** Holds the set of all boostable stat names. */
export const boostNames =
{
atk: true, def: true, spa: true, spd: true, spe: true, accuracy: true,
evasion: true
};
/** Holds the set of all boostable stat names. */
export const boostNames: Readonly<typeof boostNamesInternal> =
boostNamesInternal;

} as const;
/** Names of pokemon stats that can be boosted. */
export type BoostName = keyof typeof boostNames;

/**
* Checks if a value matches a boost name.
* @param stat Value to be checked.
Expand All @@ -74,16 +71,13 @@ export function isBoostName(stat: any): stat is BoostName
return boostNames.hasOwnProperty(stat);
}

const weatherTypesInternal =
{none: true, SunnyDay: true, RainDance: true, Sandstorm: true, Hail: true};

/** Holds the set of all weather types. */
export const weatherTypes: Readonly<typeof weatherTypesInternal> =
weatherTypesInternal;

export const weatherTypes =
{
none: true, SunnyDay: true, RainDance: true, Sandstorm: true, Hail: true
} as const;
/** Types of weather conditions. */
export type WeatherType = keyof typeof weatherTypes;

/**
* Checks if a value matches a weather type.
* @param type Value to be checked.
Expand Down Expand Up @@ -112,11 +106,11 @@ export interface PokemonData
/** Letter of the alternate form. */
readonly formLetter?: string;
/** Alternate forms of this pokemon. */
readonly otherForms?: ReadonlyArray<string>;
readonly otherForms?: readonly string[];
/** Id names of the abilities this species can have. */
readonly abilities: ReadonlyArray<string>;
readonly abilities: readonly string[];
/** Types of the pokemon. */
readonly types: Readonly<[Type, Type]>;
readonly types: readonly [Type, Type];
/** Base stats. */
readonly baseStats: {readonly [S in StatName]: number};
/** Pokemon's weight in kg. Affected by certain moves. */
Expand Down
9 changes: 5 additions & 4 deletions src/battle/state/Pokemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@ ability ${ability}`);
() => { if (this.active) this.setOverrideAbility(); });

/** The types of this pokemon. */
public get types(): ReadonlyArray<Type>
public get types(): readonly Type[]
{
// uninitialized Pokemon objs should silently fail so toArray() doesn't
// throw
if (!this.species.definiteValue) return [];

let result: ReadonlyArray<Type>;
let result: readonly Type[];
if (this._active)
{
result = this.volatile.overrideTypes
Expand All @@ -92,7 +92,7 @@ ability ${ability}`);
return result.filter(type => type !== "???");
}
/** Temporarily changes primary and secondary types and resets third. */
public changeType(newTypes: [Type, Type]): void
public changeType(newTypes: readonly [Type, Type]): void
{
this.volatile.overrideTypes = newTypes;
// reset added type
Expand Down Expand Up @@ -125,7 +125,8 @@ ability ${ability}`);
* @param targets Targets of the move.
* @param nopp Whether to not consume pp for this move.
*/
public useMove(id: string, targets: Pokemon[], nopp?: boolean): void
public useMove(id: string, targets: readonly Pokemon[], nopp?: boolean):
void
{
// struggle doesn't occupy a moveslot
if (id === "struggle") return;
Expand Down
2 changes: 1 addition & 1 deletion src/battle/state/PossibilityClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class PossibilityClass<TData>
}

/** Removes currently set value names that are not in the given array. */
public narrow(...values: string[]): void
public narrow(...values: readonly string[]): void
{
values.forEach(x => this.check(x));

Expand Down
2 changes: 1 addition & 1 deletion src/battle/state/Team.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { TeamStatus } from "./TeamStatus";
export interface SwitchInOptions
{
/** Whether volatile status should be copied onto the replacing pokemon. */
copyVolatile?: boolean;
readonly copyVolatile?: boolean;
}

/** Team state. */
Expand Down
12 changes: 6 additions & 6 deletions src/battle/state/VolatileStatus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dex, twoTurnMoves } from "../dex/dex";
import { dex, TwoTurnMove, twoTurnMoves } from "../dex/dex";
import { BoostName, Type } from "../dex/dex-types";
import { Moveset } from "./Moveset";
import { pluralTurns } from "./utility";
Expand Down Expand Up @@ -128,7 +128,7 @@ export class VolatileStatus
/** Clears the disabled status. */
public enableMoves(): void { this._disableTurns.fill(0); }
/** Turns for the disable status on each move. */
public get disableTurns(): number[] { return this._disableTurns; }
public get disableTurns(): readonly number[] { return this._disableTurns; }
// ctor will initialize values
private readonly _disableTurns = new Array<number>(Moveset.maxSize);

Expand All @@ -146,17 +146,17 @@ export class VolatileStatus
private _lockedMoveTurns!: number;

/** Two-turn move currently being prepared. */
public get twoTurn(): keyof typeof twoTurnMoves | ""
public get twoTurn(): TwoTurnMove | ""
{
return this._twoTurn;
}
public set twoTurn(twoTurn: keyof typeof twoTurnMoves | "")
public set twoTurn(twoTurn: TwoTurnMove | "")
{
this._twoTurn = twoTurn;
// after this turn this will be 1
this.twoTurnCounter = twoTurn ? 2 : 0;
}
private _twoTurn!: keyof typeof twoTurnMoves | "";
private _twoTurn!: TwoTurnMove | "";
private twoTurnCounter!: number;

/** Whether this pokemon must recharge on the next turn. */
Expand All @@ -182,7 +182,7 @@ export class VolatileStatus
* since the parent Pokemon object should handle that. Should not be
* accessed other than by the parent Pokemon object.
*/
public overrideTypes!: Readonly<[Type, Type]>;
public overrideTypes!: readonly [Type, Type];
/** Temporary third type. */
public addedType!: Type;

Expand Down
6 changes: 3 additions & 3 deletions src/psbot/PSEventHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,8 @@ export class PSEventHandler
const team = this.getTeam(event.id.owner);

// consume pending copyvolatile status flags
const options: SwitchInOptions = {};
options.copyVolatile = team.status.selfSwitch === "copyvolatile";
const options: SwitchInOptions =
{copyVolatile: team.status.selfSwitch === "copyvolatile"};
team.status.selfSwitch = false;

team.switchIn(event.details.species, event.details.level,
Expand Down Expand Up @@ -415,7 +415,7 @@ export class PSEventHandler
* Processes BattleEvents sent from the server to update the internal
* BattleState.
*/
public handleEvents(events: AnyBattleEvent[]): void
public handleEvents(events: readonly AnyBattleEvent[]): void
{
// this field should only stay true if one of these events contains a
// |turn| message
Expand Down
Loading

0 comments on commit e4fa9aa

Please sign in to comment.