1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-06-13 13:04:03 +00:00

Replace enumColors with string literals

This commit is contained in:
Bjorn Stromberg 2020-08-17 17:44:20 +09:00
parent 1ff76e0b2e
commit 0a5cfbf84c
11 changed files with 247 additions and 194 deletions

View File

@ -1,163 +1,206 @@
/** @enum {string} */
export const enumColors = {
red: "red",
green: "green",
blue: "blue",
/** @typedef {"r" | "g" | "b" | "y" | "p" | "c" | "w" | "u" | "0"} ColorShortcode **/
yellow: "yellow",
purple: "purple",
cyan: "cyan",
/** @type {Color[]} **/
export const colors = ["red", "green", "blue", "yellow", "purple", "cyan", "white", "uncolored", "black"];
white: "white",
uncolored: "uncolored",
};
/** @type {ColorShortcode[]} **/
export const colorShortcodes = ["r", "g", "b", "y", "p", "c", "w", "u", "0"];
/** @enum {string} */
export const enumColorToShortcode = {
[enumColors.red]: "r",
[enumColors.green]: "g",
[enumColors.blue]: "b",
[enumColors.yellow]: "y",
[enumColors.purple]: "p",
[enumColors.cyan]: "c",
[enumColors.white]: "w",
[enumColors.uncolored]: "u",
};
/** @enum {enumColors} */
export const enumShortcodeToColor = {};
for (const key in enumColorToShortcode) {
enumShortcodeToColor[enumColorToShortcode[key]] = key;
/**
* @param {unknown} value
* @returns {value is Color}
**/
export function isColor(value) {
return colors.includes(/** @type {Color} **/ (value));
}
/** @enum {string} */
export const enumColorsToHexCode = {
[enumColors.red]: "#ff666a",
[enumColors.green]: "#78ff66",
[enumColors.blue]: "#66a7ff",
// red + green
[enumColors.yellow]: "#fcf52a",
// red + blue
[enumColors.purple]: "#dd66ff",
// blue + green
[enumColors.cyan]: "#00fcff",
// blue + green + red
[enumColors.white]: "#ffffff",
[enumColors.uncolored]: "#aaaaaa",
/** @type {Record<Color, ColorShortcode>} **/
export const colorShortcodeMap = {
red: "r",
green: "g",
blue: "b",
yellow: "y",
purple: "p",
cyan: "c",
white: "w",
uncolored: "u",
black: "0",
};
const c = enumColors;
/** @enum {Object.<string, string>} */
export const enumColorMixingResults = {
/** @type {Record<ColorShortcode, Color>} **/
export const shortcodeColorMap = {
"r": "red",
"g": "green",
"b": "blue",
"y": "yellow",
"p": "purple",
"c": "cyan",
"w": "white",
"u": "uncolored",
"0": "black",
};
/** @type {Record<Color, HexColor>} **/
export const colorHexColorMap = {
red: "#ff666a",
green: "#78ff66",
blue: "#66a7ff",
yellow: "#fcf52a",
purple: "#dd66ff",
cyan: "#00fcff",
white: "#ffffff",
uncolored: "#aaaaaa",
black: "#31383a",
};
/** @type {Record<Color, Record<Color, Color>>} **/
export const colorMixingMap = {
// 255, 0, 0
[c.red]: {
[c.green]: c.yellow,
[c.blue]: c.purple,
[c.yellow]: c.yellow,
[c.purple]: c.purple,
[c.cyan]: c.white,
[c.white]: c.white,
red: {
red: "red",
green: "yellow",
blue: "purple",
yellow: "yellow",
purple: "purple",
cyan: "white",
white: "white",
uncolored: "red",
black: "red",
},
// 0, 255, 0
[c.green]: {
[c.blue]: c.cyan,
[c.yellow]: c.yellow,
[c.purple]: c.white,
[c.cyan]: c.cyan,
[c.white]: c.white,
green: {
red: "yellow",
blue: "cyan",
green: "green",
yellow: "yellow",
purple: "white",
cyan: "cyan",
white: "white",
uncolored: "green",
black: "green",
},
// 0, 255, 0
[c.blue]: {
[c.yellow]: c.white,
[c.purple]: c.purple,
[c.cyan]: c.cyan,
[c.white]: c.white,
blue: {
red: "purple",
green: "cyan",
blue: "blue",
yellow: "white",
purple: "purple",
cyan: "cyan",
white: "white",
uncolored: "blue",
black: "blue",
},
// 255, 255, 0
[c.yellow]: {
[c.purple]: c.white,
[c.cyan]: c.white,
yellow: {
red: "yellow",
green: "yellow",
blue: "white",
purple: "white",
cyan: "white",
yellow: "yellow",
white: "white",
uncolored: "yellow",
black: "yellow",
},
// 255, 0, 255
[c.purple]: {
[c.cyan]: c.white,
purple: {
red: "purple",
green: "white",
blue: "purple",
cyan: "white",
yellow: "white",
purple: "purple",
white: "white",
uncolored: "purple",
black: "purple",
},
// 0, 255, 255
[c.cyan]: {},
cyan: {
red: "white",
green: "cyan",
blue: "cyan",
cyan: "cyan",
yellow: "white",
purple: "white",
white: "white",
uncolored: "cyan",
black: "cyan",
},
//// SPECIAL COLORS
// 255, 255, 255
[c.white]: {
// auto
white: {
red: "white",
green: "white",
blue: "white",
cyan: "white",
yellow: "white",
purple: "white",
white: "white",
uncolored: "white",
black: "uncolored",
},
// X, X, X
[c.uncolored]: {
// auto
uncolored: {
red: "red",
green: "green",
blue: "blue",
cyan: "cyan",
yellow: "yellow",
purple: "purple",
white: "white",
uncolored: "uncolored",
black: "black",
},
black: {
red: "red",
green: "green",
blue: "blue",
cyan: "cyan",
yellow: "yellow",
purple: "purple",
white: "uncolored",
uncolored: "black",
black: "black",
},
};
// Create same color lookups
for (const color in enumColors) {
enumColorMixingResults[color][color] = color;
enumColorMixingResults[color][c.white] = c.white;
// Anything with uncolored is the same color
enumColorMixingResults[color][c.uncolored] = color;
}
// Create reverse lookup and check color mixing lookups
for (const colorA in enumColorMixingResults) {
for (const colorB in enumColorMixingResults[colorA]) {
const resultColor = enumColorMixingResults[colorA][colorB];
if (!enumColorMixingResults[colorB]) {
enumColorMixingResults[colorB] = {
[colorA]: resultColor,
};
} else {
const existingResult = enumColorMixingResults[colorB][colorA];
if (existingResult && existingResult !== resultColor) {
assertAlways(
false,
"invalid color mixing configuration, " +
colorA +
" + " +
colorB +
" is " +
resultColor +
" but " +
colorB +
" + " +
colorA +
" is " +
existingResult
);
}
enumColorMixingResults[colorB][colorA] = resultColor;
for (const colorA in colorMixingMap) {
for (const colorB in colorMixingMap[colorA]) {
const resultColor = colorMixingMap[colorA][colorB];
const existingResult = colorMixingMap[colorB][colorA];
if (existingResult && existingResult !== resultColor) {
assertAlways(
false,
"invalid color mixing configuration, " +
colorA +
" + " +
colorB +
" is " +
resultColor +
" but " +
colorB +
" + " +
colorA +
" is " +
existingResult
);
}
}
}
for (const colorA in enumColorMixingResults) {
for (const colorB in enumColorMixingResults) {
if (!enumColorMixingResults[colorA][colorB]) {
for (const colorA in colorMixingMap) {
for (const colorB in colorMixingMap) {
if (!colorMixingMap[colorA][colorB]) {
assertAlways(false, "Color mixing of", colorA, "with", colorB, "is not defined");
}
}

View File

@ -1,7 +1,7 @@
import { globalConfig } from "../core/config";
import { clamp, findNiceIntegerValue, randomChoice, randomInt } from "../core/utils";
import { BasicSerializableObject, types } from "../savegame/serialization";
import { enumColors } from "./colors";
import { colors } from "./colors";
import { enumItemProcessorTypes } from "./components/item_processor";
import { GameRoot } from "./root";
import { enumSubShape, ShapeDefinition } from "./shape_definition";
@ -327,7 +327,7 @@ export class HubGoals extends BasicSerializableObject {
/** @type {Array<import("./shape_definition").ShapeLayer>} */
let layers = [];
const randomColor = () => randomChoice(Object.values(enumColors));
const randomColor = () => randomChoice(colors);
const randomShape = () => randomChoice(Object.values(enumSubShape));
let anyIsMissingTwo = false;

View File

@ -1,7 +1,6 @@
import { BaseHUDPart } from "../base_hud_part";
import { makeDiv } from "../../../core/utils";
import { TrackedState } from "../../../core/tracked_state";
import { enumColors } from "../../colors";
import { ColorItem } from "../../items/color_item";
import { DrawParameters } from "../../../core/draw_parameters";
import { THEME } from "../../theme";
@ -19,7 +18,7 @@ export class HUDColorBlindHelper extends BaseHUDPart {
/**
* Called when the color below the current tile changed
* @param {enumColors|null} color
* @param {Color|null} color
*/
onColorBelowTileChanged(color) {
this.belowTileIndicator.classList.toggle("visible", !!color);
@ -30,7 +29,7 @@ export class HUDColorBlindHelper extends BaseHUDPart {
/**
* Computes the color below the current tile
* @returns {enumColors}
* @returns {Color}
*/
computeColorBelowTile() {
const mousePosition = this.root.app.mousePosition;

View File

@ -3,7 +3,7 @@ import { smoothenDpi } from "../../core/dpi_manager";
import { DrawParameters } from "../../core/draw_parameters";
import { types } from "../../savegame/serialization";
import { BaseItem } from "../base_item";
import { enumColors, enumColorsToHexCode } from "../colors";
import { colors, colorHexColorMap } from "../colors";
import { THEME } from "../theme";
import { drawSpriteClipped } from "../../core/draw_utils";
@ -13,7 +13,7 @@ export class ColorItem extends BaseItem {
}
static getSchema() {
return types.enum(enumColors);
return types.enum(colors);
}
serialize() {
@ -37,7 +37,7 @@ export class ColorItem extends BaseItem {
}
/**
* @param {enumColors} color
* @param {Color} color
*/
constructor(color) {
super();
@ -45,6 +45,9 @@ export class ColorItem extends BaseItem {
this.bufferGenerator = null;
}
/**
* @returns {HexColor}
*/
getBackgroundColorAsResource() {
return THEME.map.resources[this.color];
}
@ -95,7 +98,7 @@ export class ColorItem extends BaseItem {
context.translate((w * dpi) / 2, (h * dpi) / 2);
context.scale((dpi * w) / 12, (dpi * h) / 12);
context.fillStyle = enumColorsToHexCode[this.color];
context.fillStyle = colorHexColorMap[this.color];
context.strokeStyle = THEME.items.outline;
context.lineWidth = 2 * THEME.items.outlineWidth;
context.beginCircle(2, -1, 3);
@ -111,12 +114,14 @@ export class ColorItem extends BaseItem {
}
}
/**
* Singleton instances
* @type {Object<enumColors, ColorItem>}
*/
export const COLOR_ITEM_SINGLETONS = {};
for (const color in enumColors) {
COLOR_ITEM_SINGLETONS[color] = new ColorItem(color);
}
export const COLOR_ITEM_SINGLETONS = {
red: new ColorItem("red"),
green: new ColorItem("green"),
blue: new ColorItem("blue"),
yellow: new ColorItem("yellow"),
purple: new ColorItem("purple"),
cyan: new ColorItem("cyan"),
white: new ColorItem("white"),
black: new ColorItem("black"),
uncolored: new ColorItem("uncolored"),
};

View File

@ -4,7 +4,6 @@ import { RandomNumberGenerator } from "../core/rng";
import { clamp, fastArrayDeleteValueIfContained, make2DUndefinedArray } from "../core/utils";
import { Vector } from "../core/vector";
import { BaseItem } from "./base_item";
import { enumColors } from "./colors";
import { Entity } from "./entity";
import { COLOR_ITEM_SINGLETONS } from "./items/color_item";
import { GameRoot } from "./root";
@ -165,9 +164,10 @@ export class MapChunk {
*/
internalGenerateColorPatch(rng, colorPatchSize, distanceToOriginInChunks) {
// First, determine available colors
let availableColors = [enumColors.red, enumColors.green];
/** @type {Color[]} */
const availableColors = ["red", "green"];
if (distanceToOriginInChunks > 2) {
availableColors.push(enumColors.blue);
availableColors.push("blue");
}
this.internalGeneratePatch(rng, colorPatchSize, COLOR_ITEM_SINGLETONS[rng.choice(availableColors)]);
}
@ -298,7 +298,7 @@ export class MapChunk {
*/
generatePredefined(rng) {
if (this.x === 0 && this.y === 0) {
this.internalGeneratePatch(rng, 2, COLOR_ITEM_SINGLETONS[enumColors.red], 7, 7);
this.internalGeneratePatch(rng, 2, COLOR_ITEM_SINGLETONS.red, 7, 7);
return true;
}
if (this.x === -1 && this.y === 0) {
@ -313,7 +313,7 @@ export class MapChunk {
}
if (this.x === -1 && this.y === -1) {
this.internalGeneratePatch(rng, 2, COLOR_ITEM_SINGLETONS[enumColors.green]);
this.internalGeneratePatch(rng, 2, COLOR_ITEM_SINGLETONS.green);
return true;
}

View File

@ -4,17 +4,12 @@ import { smoothenDpi } from "../core/dpi_manager";
import { DrawParameters } from "../core/draw_parameters";
import { Vector } from "../core/vector";
import { BasicSerializableObject, types } from "../savegame/serialization";
import { enumColors, enumColorsToHexCode, enumColorToShortcode, enumShortcodeToColor } from "./colors";
import { colorHexColorMap, colorShortcodeMap, shortcodeColorMap } from "./colors";
import { THEME } from "./theme";
/**
* @typedef {{
* subShape: enumSubShape,
* color: enumColors,
* }} ShapeLayerItem
*/
/**
* @typedef {{ subShape: enumSubShape, color: Color }} ShapeLayerItem
*
* Order is Q1 (tr), Q2(br), Q3(bl), Q4(tl)
* @typedef {[ShapeLayerItem?, ShapeLayerItem?, ShapeLayerItem?, ShapeLayerItem?]} ShapeLayer
*/
@ -51,13 +46,13 @@ for (const key in enumSubShapeToShortcode) {
/**
* Converts the given parameters to a valid shape definition
* @param {*} layers
* @returns {Array<import("./shape_definition").ShapeLayer>}
* @returns {Array<ShapeLayer>}
*/
export function createSimpleShape(layers) {
layers.forEach(layer => {
layer.forEach(item => {
if (item) {
item.color = item.color || enumColors.uncolored;
item.color = item.color || "uncolored";
}
});
});
@ -129,7 +124,7 @@ export class ShapeDefinition extends BasicSerializableObject {
for (let quad = 0; quad < 4; ++quad) {
const shapeText = text[quad * 2 + 0];
const subShape = enumShortcodeToSubShape[shapeText];
const color = enumShortcodeToColor[text[quad * 2 + 1]];
const color = shortcodeColorMap[text[quad * 2 + 1]];
if (subShape) {
assert(color, "Invalid shape short key:", key);
quads[quad] = {
@ -186,7 +181,7 @@ export class ShapeDefinition extends BasicSerializableObject {
const shapeText = text[quad * 2 + 0];
const colorText = text[quad * 2 + 1];
const subShape = enumShortcodeToSubShape[shapeText];
const color = enumShortcodeToColor[colorText];
const color = shortcodeColorMap[colorText];
// Valid shape
if (subShape) {
@ -256,7 +251,7 @@ export class ShapeDefinition extends BasicSerializableObject {
for (let quadrant = 0; quadrant < layer.length; ++quadrant) {
const item = layer[quadrant];
if (item) {
id += enumSubShapeToShortcode[item.subShape] + enumColorToShortcode[item.color];
id += enumSubShapeToShortcode[item.subShape] + colorShortcodeMap[item.color];
} else {
id += "--";
}
@ -352,7 +347,7 @@ export class ShapeDefinition extends BasicSerializableObject {
context.translate(centerQuadrantX, centerQuadrantY);
context.rotate(rotation);
context.fillStyle = enumColorsToHexCode[color];
context.fillStyle = colorHexColorMap[color];
context.strokeStyle = THEME.items.outline;
context.lineWidth = THEME.items.outlineWidth;
@ -571,7 +566,7 @@ export class ShapeDefinition extends BasicSerializableObject {
/**
* Clones the shape and colors everything in the given color
* @param {enumColors} color
* @param {Color} color
*/
cloneAndPaintWith(color) {
const newLayers = this.internalCloneLayers();
@ -590,7 +585,7 @@ export class ShapeDefinition extends BasicSerializableObject {
/**
* Clones the shape and colors everything in the given colors
* @param {[enumColors, enumColors, enumColors, enumColors]} colors
* @param {[Color, Color, Color, Color]} colors
*/
cloneAndPaintWith4Colors(colors) {
const newLayers = this.internalCloneLayers();

View File

@ -1,9 +1,8 @@
import { createLogger } from "../core/logging";
import { BasicSerializableObject } from "../savegame/serialization";
import { enumColors } from "./colors";
import { ShapeItem } from "./items/shape_item";
import { GameRoot } from "./root";
import { enumSubShape, ShapeDefinition } from "./shape_definition";
import { enumSubShape, ShapeDefinition, ShapeLayer } from "./shape_definition";
const logger = createLogger("shape_definition_manager");
@ -198,7 +197,7 @@ export class ShapeDefinitionManager extends BasicSerializableObject {
/**
* Generates a definition for painting it with the given color
* @param {ShapeDefinition} definition
* @param {enumColors} color
* @param {Color} color
* @returns {ShapeDefinition}
*/
shapeActionPaintWith(definition, color) {
@ -215,7 +214,7 @@ export class ShapeDefinitionManager extends BasicSerializableObject {
/**
* Generates a definition for painting it with the 4 colors
* @param {ShapeDefinition} definition
* @param {[enumColors, enumColors, enumColors, enumColors]} colors
* @param {[Color, Color, Color, Color]} colors
* @returns {ShapeDefinition}
*/
shapeActionPaintWith4Colors(definition, colors) {
@ -249,10 +248,8 @@ export class ShapeDefinitionManager extends BasicSerializableObject {
* @param {[enumSubShape, enumSubShape, enumSubShape, enumSubShape]} subShapes
* @returns {ShapeDefinition}
*/
getDefinitionFromSimpleShapes(subShapes, color = enumColors.uncolored) {
const shapeLayer = /** @type {import("./shape_definition").ShapeLayer} */ (subShapes.map(
subShape => ({ subShape, color })
));
getDefinitionFromSimpleShapes(subShapes, color = "uncolored") {
const shapeLayer = /** @type {ShapeLayer} */ (subShapes.map(subShape => ({ subShape, color })));
return this.registerOrReturnHandle(new ShapeDefinition({ layers: [shapeLayer] }));
}

View File

@ -2,7 +2,7 @@ import trim from "trim";
import { DialogWithForm } from "../../core/modal_dialog_elements";
import { FormElementInput } from "../../core/modal_dialog_forms";
import { BaseItem } from "../base_item";
import { enumColors } from "../colors";
import { isColor } from "../colors";
import { ConstantSignalComponent } from "../components/constant_signal";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
@ -109,7 +109,7 @@ export class ConstantSignalSystem extends GameSystemWithFilter {
code = trim(code);
const codeLower = code.toLowerCase();
if (enumColors[codeLower]) {
if (isColor(codeLower)) {
return COLOR_ITEM_SINGLETONS[codeLower];
}
if (code === "1" || codeLower === "true") {

View File

@ -1,7 +1,8 @@
import { globalConfig } from "../../core/config";
import { AtlasSprite, DrawParameters } from "../../core/draw_utils";
import { Loader } from "../../core/loader";
import { BaseItem } from "../base_item";
import { enumColors } from "../colors";
import { colors } from "../colors";
import { DisplayComponent } from "../components/display";
import { GameSystemWithFilter } from "../game_system_with_filter";
import { ColorItem, COLOR_ITEM_SINGLETONS } from "../items/color_item";
@ -12,15 +13,12 @@ export class DisplaySystem extends GameSystemWithFilter {
constructor(root) {
super(root, [DisplayComponent]);
/** @type {Object<string, import("../../core/draw_utils").AtlasSprite>} */
this.displaySprites = {};
for (const colorId in enumColors) {
if (colorId === enumColors.uncolored) {
continue;
}
this.displaySprites[colorId] = Loader.getSprite("sprites/wires/display/" + colorId + ".png");
}
this.displaySprites = colors
.filter(color => !["black", "uncolored"].includes(color))
.reduce((sprites, color) => {
sprites[color] = Loader.getSprite(`sprites/wires/display/${color}.png`);
return sprites;
}, /** @type {Record<Exclude<Color, "black" | "uncolored">, AtlasSprite>} */ ({}));
}
/**
@ -35,14 +33,12 @@ export class DisplaySystem extends GameSystemWithFilter {
switch (value.getItemType()) {
case "boolean": {
return /** @type {BooleanItem} */ (value).value
? COLOR_ITEM_SINGLETONS[enumColors.white]
: null;
return /** @type {BooleanItem} */ (value).value ? COLOR_ITEM_SINGLETONS.white : null;
}
case "color": {
const item = /**@type {ColorItem} */ (value);
return item.color === enumColors.uncolored ? null : item;
return item.color === "uncolored" ? null : item;
}
case "shape": {
@ -56,7 +52,7 @@ export class DisplaySystem extends GameSystemWithFilter {
/**
* Draws a given chunk
* @param {import("../../core/draw_utils").DrawParameters} parameters
* @param {DrawParameters} parameters
* @param {MapChunkView} chunk
*/
drawChunk(parameters, chunk) {

View File

@ -1,6 +1,6 @@
import { globalConfig } from "../../core/config";
import { BaseItem } from "../base_item";
import { enumColorMixingResults } from "../colors";
import { colorMixingMap } from "../colors";
import { enumItemProcessorTypes, ItemProcessorComponent } from "../components/item_processor";
import { Entity } from "../entity";
import { GameSystemWithFilter } from "../game_system_with_filter";
@ -241,12 +241,8 @@ export class ItemProcessorSystem extends GameSystemWithFilter {
const color1 = item1.color;
const color2 = item2.color;
// Try finding mixer color, and if we can't mix it we simply return the same color
const mixedColor = enumColorMixingResults[color1][color2];
let resultColor = color1;
if (mixedColor) {
resultColor = mixedColor;
}
const resultColor = colorMixingMap[color1][color2];
outItems.push({
item: COLOR_ITEM_SINGLETONS[resultColor],
});

22
src/js/globals.d.ts vendored
View File

@ -203,3 +203,25 @@ declare module "worker-loader?inline=true&fallback=false!*" {
export default WebpackWorker;
}
declare type Color =
| "red"
| "green"
| "blue"
| "yellow"
| "purple"
| "cyan"
| "white"
| "uncolored"
| "black";
declare type HexColor =
| "#ff666a"
| "#78ff66"
| "#66a7ff"
| "#fcf52a"
| "#dd66ff"
| "#00fcff"
| "#ffffff"
| "#aaaaaa"
| "#31383a";