prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { getAccessibleName } from "../getAccessibleName";
import { getAccessibleValue } from "../getAccessibleValue";
import { getItemText } from "../../getItemText";
import { getNodeByIdRef } from "../../getNodeByIdRef";
enum State {
BUSY = "busy",
CHECKED = "checked",
CURRENT = "current item",
DISABLED = "disabled",
EXPANDED = "expanded",
INVALID = "invalid",
MODAL = "modal",
MULTI_SELECTABLE = "multi-selectable",
PARTIALLY_CHECKED = "partially checked",
PARTIALLY_PRESSED = "partially pressed",
PRESSED = "pressed",
READ_ONLY = "read only",
REQUIRED = "required",
SELECTED = "selected",
}
// https://w3c.github.io/aria/#state_prop_def
const ariaPropertyToVirtualLabelMap: Record<
string,
((...args: unknown[]) => string) | null
> = {
"aria-activedescendant": idRef("active descendant"),
"aria-atomic": null, // Handled by live region logic
"aria-autocomplete": token({
inline: "autocomplete inlined",
list: "autocomplete in list",
both: "autocomplete inlined and in list",
none: "no autocomplete",
}),
"aria-braillelabel": null, // Currently won't do - not implementing a braille screen reader
"aria-brailleroledescription": null, // Currently won't do - not implementing a braille screen reader
"aria-busy": state(State.BUSY),
"aria-checked": tristate(State.CHECKED, State.PARTIALLY_CHECKED),
"aria-colcount": integer("column count"),
"aria-colindex": integer("column index"),
"aria-colindextext": string("column index"),
"aria-colspan": integer("column span"),
"aria-controls": idRefs("control", "controls"), // Handled by virtual.perform()
"aria-current": token({
page: "current page",
step: "current step",
location: "current location",
date: "current date",
time: "current time",
true: State.CURRENT,
false: `not ${State.CURRENT}`,
}),
"aria-describedby": null, // Handled by accessible description
"aria-description": null, // Handled by accessible description
"aria-details": idRefs("linked details", "linked details", false),
"aria-disabled": state(State.DISABLED),
"aria-dropeffect": null, // Deprecated in WAI-ARIA 1.1
"aria-errormessage": null, // TODO: decide what to announce here
"aria-expanded": state(State.EXPANDED),
"aria-flowto": idRefs("alternate reading order", "alternate reading orders"), // Handled by virtual.perform()
"aria-grabbed": null, // Deprecated in WAI-ARIA 1.1
"aria-haspopup": token({
/**
* Assistive technologies SHOULD NOT expose the aria-haspopup property if
* it has a value of false.
*
* REF: // https://w3c.github.io/aria/#aria-haspopup
*/
false: null,
true: "has popup menu",
menu: "has popup menu",
listbox: "has popup listbox",
tree: "has popup tree",
grid: "has popup grid",
dialog: "has popup dialog",
}),
"aria-hidden": null, // Excluded from accessibility tree
"aria-invalid": token({
grammar: "grammatical error detected",
false: `not ${State.INVALID}`,
spelling: "spelling error detected",
true: State.INVALID,
}),
"aria-keyshortcuts": string("key shortcuts"),
"aria-label": null, // Handled by accessible name
"aria-labelledby": null, // Handled by accessible name
"aria-level": integer("level"),
"aria-live": null, // Handled by live region logic
"aria-modal": state(State.MODAL),
"aria-multiselectable": state(State.MULTI_SELECTABLE),
"aria-orientation": token({
horizontal: "orientated horizontally",
vertical: "orientated vertically",
}),
"aria-owns": null, // Handled by accessibility tree construction
"aria-placeholder": string("placeholder"),
"aria-posinset": integer("item set position"),
"aria-pressed": tristate(State.PRESSED, State.PARTIALLY_PRESSED),
"aria-readonly": state(State.READ_ONLY),
"aria-relevant": null, // Handled by live region logic
"aria-required": state(State.REQUIRED),
"aria-roledescription": null, // Handled by accessible description
"aria-rowcount": integer("row count"),
"aria-rowindex": integer("row index"),
"aria-rowindextext": string("row index"),
"aria-rowspan": integer("row span"),
"aria-selected": state(State.SELECTED),
"aria-setsize": integer("item set size"),
"aria-sort": token({
ascending: "sorted in ascending order",
descending: "sorted in descending order",
none: "no defined sort order",
other: "non ascending / descending sort order applied",
}),
"aria-valuemax": number("max value"),
"aria-valuemin": number("min value"),
"aria-valuenow": number("current value"),
"aria-valuetext": string("current value"),
};
interface MapperArgs {
attributeValue: string;
container?: Node;
negative?: boolean;
}
function state(stateValue: State) {
return function stateMapper({ attributeValue, negative }: MapperArgs) {
if (negative) {
return attributeValue !== "false" ? `not ${stateValue}` : stateValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function idRefs(
propertyDescriptionSuffixSingular: string,
propertyDescriptionSuffixPlural: string,
printCount = true
) {
return function mapper({ attributeValue, container }: MapperArgs) {
const idRefsCount = attributeValue
.trim()
.split(" ")
.filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;
if (idRefsCount === 0) {
return "";
}
return `${printCount ? `${idRefsCount} ` : ""}${
idRefsCount === 1
? propertyDescriptionSuffixSingular
: propertyDescriptionSuffixPlural
}`;
};
}
function idRef(propertyName: string) {
return function mapper({ attributeValue: idRef, container }: MapperArgs) {
const node = getNodeByIdRef({ container, idRef });
if (!node) {
return "";
}
const accessibleName = getAccessibleName(node);
|
const accessibleValue = getAccessibleValue(node);
|
const itemText = getItemText({ accessibleName, accessibleValue });
return concat(propertyName)({ attributeValue: itemText });
};
}
function tristate(stateValue: State, mixedValue: State) {
return function stateMapper({ attributeValue }: MapperArgs) {
if (attributeValue === "mixed") {
return mixedValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function token(tokenMap: Record<string, string>) {
return function tokenMapper({ attributeValue }: MapperArgs) {
return tokenMap[attributeValue];
};
}
function concat(propertyName: string) {
return function mapper({ attributeValue }: MapperArgs) {
return attributeValue ? `${propertyName} ${attributeValue}` : "";
};
}
function integer(propertyName: string) {
return concat(propertyName);
}
function number(propertyName: string) {
return concat(propertyName);
}
function string(propertyName: string) {
return concat(propertyName);
}
export const mapAttributeNameAndValueToLabel = ({
attributeName,
attributeValue,
container,
negative = false,
}: {
attributeName: string;
attributeValue: string | null;
container: Node;
negative?: boolean;
}) => {
if (typeof attributeValue !== "string") {
return null;
}
const mapper = ariaPropertyToVirtualLabelMap[attributeName];
return mapper?.({ attributeValue, container, negative }) ?? null;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getIdRefsByAttribute.ts",
"retrieved_chunk": "export function getIdRefsByAttribute({ attributeName, node }) {\n return (node.getAttribute(attributeName) ?? \"\")\n .trim()\n .split(\" \")\n .filter(Boolean);\n}",
"score": 0.8490917682647705
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8385242223739624
},
{
"filename": "src/getNodeByIdRef.ts",
"retrieved_chunk": "import { isElement } from \"./isElement\";\nexport function getNodeByIdRef({ container, idRef }) {\n if (!isElement(container) || !idRef) {\n return null;\n }\n return container.querySelector(`#${idRef}`);\n}",
"score": 0.836785078048706
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8346355557441711
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8333762288093567
}
] |
typescript
|
const accessibleValue = getAccessibleValue(node);
|
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
const
|
childNode = getNodeByIdRef({ container, idRef });
|
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
|
src/createAccessibilityTree.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": "export function moveToNextAlternateReadingOrderElement({\n index,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-flowto\",\n index,\n container,",
"score": 0.8772094249725342
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8685691356658936
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8489970564842224
},
{
"filename": "src/commands/jumpToDetailsElement.ts",
"retrieved_chunk": " attributeName: \"aria-details\",\n index: 0,\n container,\n currentIndex,\n tree,\n });\n}",
"score": 0.8408833742141724
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.8374590873718262
}
] |
typescript
|
childNode = getNodeByIdRef({ container, idRef });
|
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
const childNode = getNodeByIdRef({ container, idRef });
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
|
} = getNodeAccessibilityData({
|
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
|
src/createAccessibilityTree.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " const { explicitRole, implicitRole, role } = getRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node,\n });\n const accessibleAttributeLabels = getAccessibleAttributeLabels({\n accessibleValue,\n alternateReadingOrderParents,\n container,",
"score": 0.9132878184318542
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " accessibleAttributeLabels,\n accessibleDescription: amendedAccessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n };\n}",
"score": 0.9006959199905396
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": "}: {\n allowedAccessibilityRoles: string[][];\n alternateReadingOrderParents: Node[];\n container: Node;\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n const accessibleDescription = getAccessibleDescription(node);\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);",
"score": 0.8966271281242371
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " }\n }\n return role;\n};\nexport function getNodeAccessibilityData({\n allowedAccessibilityRoles,\n alternateReadingOrderParents,\n container,\n inheritedImplicitPresentational,\n node,",
"score": 0.891822099685669
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " node,\n role,\n });\n const amendedAccessibleDescription =\n accessibleDescription === accessibleName ? \"\" : accessibleDescription;\n const isExplicitPresentational = presentationRoles.includes(explicitRole);\n const isPresentational = presentationRoles.includes(role);\n const isGeneric = role === \"generic\";\n const spokenRole = getSpokenRole({\n isGeneric,",
"score": 0.8872461318969727
}
] |
typescript
|
} = getNodeAccessibilityData({
|
import { getAccessibleName } from "../getAccessibleName";
import { getAccessibleValue } from "../getAccessibleValue";
import { getItemText } from "../../getItemText";
import { getNodeByIdRef } from "../../getNodeByIdRef";
enum State {
BUSY = "busy",
CHECKED = "checked",
CURRENT = "current item",
DISABLED = "disabled",
EXPANDED = "expanded",
INVALID = "invalid",
MODAL = "modal",
MULTI_SELECTABLE = "multi-selectable",
PARTIALLY_CHECKED = "partially checked",
PARTIALLY_PRESSED = "partially pressed",
PRESSED = "pressed",
READ_ONLY = "read only",
REQUIRED = "required",
SELECTED = "selected",
}
// https://w3c.github.io/aria/#state_prop_def
const ariaPropertyToVirtualLabelMap: Record<
string,
((...args: unknown[]) => string) | null
> = {
"aria-activedescendant": idRef("active descendant"),
"aria-atomic": null, // Handled by live region logic
"aria-autocomplete": token({
inline: "autocomplete inlined",
list: "autocomplete in list",
both: "autocomplete inlined and in list",
none: "no autocomplete",
}),
"aria-braillelabel": null, // Currently won't do - not implementing a braille screen reader
"aria-brailleroledescription": null, // Currently won't do - not implementing a braille screen reader
"aria-busy": state(State.BUSY),
"aria-checked": tristate(State.CHECKED, State.PARTIALLY_CHECKED),
"aria-colcount": integer("column count"),
"aria-colindex": integer("column index"),
"aria-colindextext": string("column index"),
"aria-colspan": integer("column span"),
"aria-controls": idRefs("control", "controls"), // Handled by virtual.perform()
"aria-current": token({
page: "current page",
step: "current step",
location: "current location",
date: "current date",
time: "current time",
true: State.CURRENT,
false: `not ${State.CURRENT}`,
}),
"aria-describedby": null, // Handled by accessible description
"aria-description": null, // Handled by accessible description
"aria-details": idRefs("linked details", "linked details", false),
"aria-disabled": state(State.DISABLED),
"aria-dropeffect": null, // Deprecated in WAI-ARIA 1.1
"aria-errormessage": null, // TODO: decide what to announce here
"aria-expanded": state(State.EXPANDED),
"aria-flowto": idRefs("alternate reading order", "alternate reading orders"), // Handled by virtual.perform()
"aria-grabbed": null, // Deprecated in WAI-ARIA 1.1
"aria-haspopup": token({
/**
* Assistive technologies SHOULD NOT expose the aria-haspopup property if
* it has a value of false.
*
* REF: // https://w3c.github.io/aria/#aria-haspopup
*/
false: null,
true: "has popup menu",
menu: "has popup menu",
listbox: "has popup listbox",
tree: "has popup tree",
grid: "has popup grid",
dialog: "has popup dialog",
}),
"aria-hidden": null, // Excluded from accessibility tree
"aria-invalid": token({
grammar: "grammatical error detected",
false: `not ${State.INVALID}`,
spelling: "spelling error detected",
true: State.INVALID,
}),
"aria-keyshortcuts": string("key shortcuts"),
"aria-label": null, // Handled by accessible name
"aria-labelledby": null, // Handled by accessible name
"aria-level": integer("level"),
"aria-live": null, // Handled by live region logic
"aria-modal": state(State.MODAL),
"aria-multiselectable": state(State.MULTI_SELECTABLE),
"aria-orientation": token({
horizontal: "orientated horizontally",
vertical: "orientated vertically",
}),
"aria-owns": null, // Handled by accessibility tree construction
"aria-placeholder": string("placeholder"),
"aria-posinset": integer("item set position"),
"aria-pressed": tristate(State.PRESSED, State.PARTIALLY_PRESSED),
"aria-readonly": state(State.READ_ONLY),
"aria-relevant": null, // Handled by live region logic
"aria-required": state(State.REQUIRED),
"aria-roledescription": null, // Handled by accessible description
"aria-rowcount": integer("row count"),
"aria-rowindex": integer("row index"),
"aria-rowindextext": string("row index"),
"aria-rowspan": integer("row span"),
"aria-selected": state(State.SELECTED),
"aria-setsize": integer("item set size"),
"aria-sort": token({
ascending: "sorted in ascending order",
descending: "sorted in descending order",
none: "no defined sort order",
other: "non ascending / descending sort order applied",
}),
"aria-valuemax": number("max value"),
"aria-valuemin": number("min value"),
"aria-valuenow": number("current value"),
"aria-valuetext": string("current value"),
};
interface MapperArgs {
attributeValue: string;
container?: Node;
negative?: boolean;
}
function state(stateValue: State) {
return function stateMapper({ attributeValue, negative }: MapperArgs) {
if (negative) {
return attributeValue !== "false" ? `not ${stateValue}` : stateValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function idRefs(
propertyDescriptionSuffixSingular: string,
propertyDescriptionSuffixPlural: string,
printCount = true
) {
return function mapper({ attributeValue, container }: MapperArgs) {
const idRefsCount = attributeValue
.trim()
.split(" ")
.filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;
if (idRefsCount === 0) {
return "";
}
return `${printCount ? `${idRefsCount} ` : ""}${
idRefsCount === 1
? propertyDescriptionSuffixSingular
: propertyDescriptionSuffixPlural
}`;
};
}
function idRef(propertyName: string) {
return function mapper({ attributeValue: idRef, container }: MapperArgs) {
const node = getNodeByIdRef({ container, idRef });
if (!node) {
return "";
}
|
const accessibleName = getAccessibleName(node);
|
const accessibleValue = getAccessibleValue(node);
const itemText = getItemText({ accessibleName, accessibleValue });
return concat(propertyName)({ attributeValue: itemText });
};
}
function tristate(stateValue: State, mixedValue: State) {
return function stateMapper({ attributeValue }: MapperArgs) {
if (attributeValue === "mixed") {
return mixedValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function token(tokenMap: Record<string, string>) {
return function tokenMapper({ attributeValue }: MapperArgs) {
return tokenMap[attributeValue];
};
}
function concat(propertyName: string) {
return function mapper({ attributeValue }: MapperArgs) {
return attributeValue ? `${propertyName} ${attributeValue}` : "";
};
}
function integer(propertyName: string) {
return concat(propertyName);
}
function number(propertyName: string) {
return concat(propertyName);
}
function string(propertyName: string) {
return concat(propertyName);
}
export const mapAttributeNameAndValueToLabel = ({
attributeName,
attributeValue,
container,
negative = false,
}: {
attributeName: string;
attributeValue: string | null;
container: Node;
negative?: boolean;
}) => {
if (typeof attributeValue !== "string") {
return null;
}
const mapper = ariaPropertyToVirtualLabelMap[attributeName];
return mapper?.({ attributeValue, container, negative }) ?? null;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getIdRefsByAttribute.ts",
"retrieved_chunk": "export function getIdRefsByAttribute({ attributeName, node }) {\n return (node.getAttribute(attributeName) ?? \"\")\n .trim()\n .split(\" \")\n .filter(Boolean);\n}",
"score": 0.8516898155212402
},
{
"filename": "src/getNodeByIdRef.ts",
"retrieved_chunk": "import { isElement } from \"./isElement\";\nexport function getNodeByIdRef({ container, idRef }) {\n if (!isElement(container) || !idRef) {\n return null;\n }\n return container.querySelector(`#${idRef}`);\n}",
"score": 0.8378938436508179
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8354436755180359
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8345332145690918
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8338524103164673
}
] |
typescript
|
const accessibleName = getAccessibleName(node);
|
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
if (!isElement(node)) {
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
|
const spokenPhrase = getSpokenPhrase(accessibilityNode);
|
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = commands[command]?.({
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
|
src/Virtual.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8272031545639038
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "].join(\", \");\nfunction isFocusable(node: HTMLElement) {\n return node.matches(FOCUSABLE_SELECTOR);\n}\nfunction hasGlobalStateOrProperty(node: HTMLElement) {\n return globalStatesAndProperties.some((global) => node.hasAttribute(global));\n}\nfunction getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,",
"score": 0.8159084320068359
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8150363564491272
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " role,\n spokenRole,\n },\n { alternateReadingOrderMap, container, ownedNodes, visitedNodes }\n )\n );\n });\n return tree;\n}\nexport function createAccessibilityTree(node: Node) {",
"score": 0.8042770028114319
},
{
"filename": "src/commands/getElementNode.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nimport { isElement } from \"../isElement\";\nexport function getElementNode(accessibilityNode: AccessibilityNode) {\n const { node } = accessibilityNode;\n if (node && isElement(node)) {\n return node;\n }\n return accessibilityNode.parent;\n}",
"score": 0.8009719252586365
}
] |
typescript
|
const spokenPhrase = getSpokenPhrase(accessibilityNode);
|
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
// REF: https://www.w3.org/TR/html-aria/#docconformance-attr
const ariaToHTMLAttributeMapping: Record<
string,
Array<{ name: string; negative?: boolean }>
> = {
"aria-checked": [{ name: "checked" }],
"aria-disabled": [{ name: "disabled" }],
// "aria-hidden": [{ name: "hidden" }],
"aria-placeholder": [{ name: "placeholder" }],
"aria-valuemax": [{ name: "max" }],
"aria-valuemin": [{ name: "min" }],
"aria-readonly": [
{ name: "readonly" },
{ name: "contenteditable", negative: true },
],
"aria-required": [{ name: "required" }],
"aria-colspan": [{ name: "colspan" }],
"aria-rowspan": [{ name: "rowspan" }],
};
export const getLabelFromHtmlEquivalentAttribute = ({
attributeName,
container,
node,
}: {
attributeName: string;
container: Node;
node: HTMLElement;
}) => {
const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];
if (!htmlAttribute?.length) {
return { label: "", value: "" };
}
for (const { name, negative = false } of htmlAttribute) {
const attributeValue = node.getAttribute(name);
const label
|
= mapAttributeNameAndValueToLabel({
|
attributeName,
attributeValue,
container,
negative,
});
if (label) {
return { label, value: attributeValue };
}
}
return { label: "", value: "" };
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " node,\n });\n if (labelFromImplicitHtmlElementValue) {\n labels[attributeName] = {\n label: labelFromImplicitHtmlElementValue,\n value: valueFromImplicitHtmlElementValue,\n };\n return;\n }\n const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(",
"score": 0.9228953123092651
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.9101090431213379
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.9072076678276062
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.9022612571716309
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " }\n const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =\n getLabelFromAriaAttribute({\n attributeName,\n container,\n node,\n });\n if (labelFromAriaAttribute) {\n labels[attributeName] = {\n label: labelFromAriaAttribute,",
"score": 0.8997558355331421
}
] |
typescript
|
= mapAttributeNameAndValueToLabel({
|
import { getAttributesByRole } from "./getAttributesByRole";
import { getLabelFromAriaAttribute } from "./getLabelFromAriaAttribute";
import { getLabelFromHtmlEquivalentAttribute } from "./getLabelFromHtmlEquivalentAttribute";
import { getLabelFromImplicitHtmlElementValue } from "./getLabelFromImplicitHtmlElementValue";
import { isElement } from "../../isElement";
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
import { postProcessLabels } from "./postProcessLabels";
export const getAccessibleAttributeLabels = ({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
}: {
accessibleValue: string;
alternateReadingOrderParents: Node[];
container: Node;
node: Node;
role: string;
}): string[] => {
if (!isElement(node)) {
return [];
}
const labels: Record<string, { label: string; value: string }> = {};
const attributes = getAttributesByRole({ accessibleValue, role });
attributes.forEach(([attributeName, implicitAttributeValue]) => {
const {
label: labelFromHtmlEquivalentAttribute,
value: valueFromHtmlEquivalentAttribute,
} = getLabelFromHtmlEquivalentAttribute({
attributeName,
container,
node,
});
if (labelFromHtmlEquivalentAttribute) {
labels[attributeName] = {
label: labelFromHtmlEquivalentAttribute,
value: valueFromHtmlEquivalentAttribute,
};
return;
}
const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =
getLabelFromAriaAttribute({
attributeName,
container,
node,
});
if (labelFromAriaAttribute) {
labels[attributeName] = {
label: labelFromAriaAttribute,
value: valueFromAriaAttribute,
};
return;
}
const {
label: labelFromImplicitHtmlElementValue,
value: valueFromImplicitHtmlElementValue,
} = getLabelFromImplicitHtmlElementValue({
attributeName,
container,
node,
});
if (labelFromImplicitHtmlElementValue) {
labels[attributeName] = {
label: labelFromImplicitHtmlElementValue,
value: valueFromImplicitHtmlElementValue,
};
return;
}
const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(
{
attributeName,
attributeValue: implicitAttributeValue,
container,
}
);
if (labelFromImplicitAriaAttributeValue) {
labels[attributeName] = {
label: labelFromImplicitAriaAttributeValue,
value: implicitAttributeValue,
};
return;
}
});
|
const processedLabels = postProcessLabels({ labels, role }).filter(Boolean);
|
/**
* aria-flowto MUST requirements:
*
* The reading order goes both directions, and a user needs to be aware of the
* alternate reading order so that they can invoke the functionality.
*
* The reading order goes both directions, and a user needs to be able to
* travel backwards through their chosen reading order.
*
* REF: https://a11ysupport.io/tech/aria/aria-flowto_attribute
*/
if (alternateReadingOrderParents.length > 0) {
processedLabels.push(
`${alternateReadingOrderParents.length} previous alternate reading ${
alternateReadingOrderParents.length === 1 ? "order" : "orders"
}`
);
}
return processedLabels;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " });\n if (label) {\n return { label, value: attributeValue };\n }\n }\n return { label: \"\", value: \"\" };\n};",
"score": 0.8749725818634033
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/postProcessLabels.ts",
"retrieved_chunk": " if (labels[preferred] && labels[dropped]) {\n labels[dropped].value = \"\";\n }\n }\n if (labels[\"aria-valuenow\"]) {\n labels[\"aria-valuenow\"].label = postProcessAriaValueNow({\n value: labels[\"aria-valuenow\"].value,\n min: labels[\"aria-valuemin\"]?.value,\n max: labels[\"aria-valuemax\"]?.value,\n role,",
"score": 0.8652941584587097
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8628738522529602
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/postProcessLabels.ts",
"retrieved_chunk": " [\"aria-valuetext\", \"aria-valuenow\"],\n];\nexport const postProcessLabels = ({\n labels,\n role,\n}: {\n labels: Record<string, { label: string; value: string }>;\n role: string;\n}) => {\n for (const [preferred, dropped] of priorityReplacementMap) {",
"score": 0.8563095331192017
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.8550098538398743
}
] |
typescript
|
const processedLabels = postProcessLabels({ labels, role }).filter(Boolean);
|
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
const childNode = getNodeByIdRef({ container, idRef });
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
|
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
|
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
|
src/createAccessibilityTree.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": "export function moveToNextAlternateReadingOrderElement({\n index,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-flowto\",\n index,\n container,",
"score": 0.8254910111427307
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8239368200302124
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " *\n * The reading order goes both directions, and a user needs to be able to\n * travel backwards through their chosen reading order.\n *\n * REF: https://a11ysupport.io/tech/aria/aria-flowto_attribute\n */\n if (alternateReadingOrderParents.length > 0) {\n processedLabels.push(\n `${alternateReadingOrderParents.length} previous alternate reading ${\n alternateReadingOrderParents.length === 1 ? \"order\" : \"orders\"",
"score": 0.8238039016723633
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": "}: {\n allowedAccessibilityRoles: string[][];\n alternateReadingOrderParents: Node[];\n container: Node;\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n const accessibleDescription = getAccessibleDescription(node);\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);",
"score": 0.8198812007904053
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.8161053657531738
}
] |
typescript
|
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
|
const { explicitRole, implicitRole, role } = getRole({
|
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const isExplicitPresentational = presentationRoles.includes(explicitRole);
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.9303630590438843
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.9205859899520874
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " inheritedImplicitPresentational,\n node,\n}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: HTMLElement;\n}) {\n const rawRoles = node.getAttribute(\"role\")?.trim().split(\" \") ?? [];\n const authorErrorFilteredRoles = rawRoles",
"score": 0.9084950685501099
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 0.9030458927154541
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue: string;\n allowedAccessibilityChildRoles: string[][];\n alternateReadingOrderParents: Node[];\n childrenPresentational: boolean;\n node: Node;\n parent: Node | null;\n role: string;\n spokenRole: string;\n}\ninterface AccessibilityNodeTree extends AccessibilityNode {",
"score": 0.901058554649353
}
] |
typescript
|
const { explicitRole, implicitRole, role } = getRole({
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
|
const accessibleDescription = getAccessibleDescription(node);
|
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role } = getRole({
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const isExplicitPresentational = presentationRoles.includes(explicitRole);
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " inheritedImplicitPresentational,\n node,\n}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: HTMLElement;\n}) {\n const rawRoles = node.getAttribute(\"role\")?.trim().split(\" \") ?? [];\n const authorErrorFilteredRoles = rawRoles",
"score": 0.9044844508171082
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.903717041015625
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.8972357511520386
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n container,\n node: childNode,\n inheritedImplicitPresentational: tree.childrenPresentational,\n });",
"score": 0.8901361227035522
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8852429389953613
}
] |
typescript
|
const accessibleDescription = getAccessibleDescription(node);
|
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
[moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
|
>}`]: (args: VirtualCommandArgs) => number | null;
|
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
|
src/commands/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.8555235266685486
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.8400909900665283
},
{
"filename": "src/commands/types.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nexport interface VirtualCommandArgs {\n currentIndex: number;\n container: Node;\n tree: AccessibilityNode[];\n}",
"score": 0.8152387142181396
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " );\n }\n #getCurrentIndexByNode(tree: AccessibilityNode[]) {\n return tree.findIndex(({ node }) => node === this.#activeNode?.node);\n }\n /**\n * Getter for screen reader commands.\n *\n * Use with `await virtual.perform(command)`.\n */",
"score": 0.8072469234466553
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.8034372329711914
}
] |
typescript
|
>}`]: (args: VirtualCommandArgs) => number | null;
|
import { getAccessibleName } from "../getAccessibleName";
import { getAccessibleValue } from "../getAccessibleValue";
import { getItemText } from "../../getItemText";
import { getNodeByIdRef } from "../../getNodeByIdRef";
enum State {
BUSY = "busy",
CHECKED = "checked",
CURRENT = "current item",
DISABLED = "disabled",
EXPANDED = "expanded",
INVALID = "invalid",
MODAL = "modal",
MULTI_SELECTABLE = "multi-selectable",
PARTIALLY_CHECKED = "partially checked",
PARTIALLY_PRESSED = "partially pressed",
PRESSED = "pressed",
READ_ONLY = "read only",
REQUIRED = "required",
SELECTED = "selected",
}
// https://w3c.github.io/aria/#state_prop_def
const ariaPropertyToVirtualLabelMap: Record<
string,
((...args: unknown[]) => string) | null
> = {
"aria-activedescendant": idRef("active descendant"),
"aria-atomic": null, // Handled by live region logic
"aria-autocomplete": token({
inline: "autocomplete inlined",
list: "autocomplete in list",
both: "autocomplete inlined and in list",
none: "no autocomplete",
}),
"aria-braillelabel": null, // Currently won't do - not implementing a braille screen reader
"aria-brailleroledescription": null, // Currently won't do - not implementing a braille screen reader
"aria-busy": state(State.BUSY),
"aria-checked": tristate(State.CHECKED, State.PARTIALLY_CHECKED),
"aria-colcount": integer("column count"),
"aria-colindex": integer("column index"),
"aria-colindextext": string("column index"),
"aria-colspan": integer("column span"),
"aria-controls": idRefs("control", "controls"), // Handled by virtual.perform()
"aria-current": token({
page: "current page",
step: "current step",
location: "current location",
date: "current date",
time: "current time",
true: State.CURRENT,
false: `not ${State.CURRENT}`,
}),
"aria-describedby": null, // Handled by accessible description
"aria-description": null, // Handled by accessible description
"aria-details": idRefs("linked details", "linked details", false),
"aria-disabled": state(State.DISABLED),
"aria-dropeffect": null, // Deprecated in WAI-ARIA 1.1
"aria-errormessage": null, // TODO: decide what to announce here
"aria-expanded": state(State.EXPANDED),
"aria-flowto": idRefs("alternate reading order", "alternate reading orders"), // Handled by virtual.perform()
"aria-grabbed": null, // Deprecated in WAI-ARIA 1.1
"aria-haspopup": token({
/**
* Assistive technologies SHOULD NOT expose the aria-haspopup property if
* it has a value of false.
*
* REF: // https://w3c.github.io/aria/#aria-haspopup
*/
false: null,
true: "has popup menu",
menu: "has popup menu",
listbox: "has popup listbox",
tree: "has popup tree",
grid: "has popup grid",
dialog: "has popup dialog",
}),
"aria-hidden": null, // Excluded from accessibility tree
"aria-invalid": token({
grammar: "grammatical error detected",
false: `not ${State.INVALID}`,
spelling: "spelling error detected",
true: State.INVALID,
}),
"aria-keyshortcuts": string("key shortcuts"),
"aria-label": null, // Handled by accessible name
"aria-labelledby": null, // Handled by accessible name
"aria-level": integer("level"),
"aria-live": null, // Handled by live region logic
"aria-modal": state(State.MODAL),
"aria-multiselectable": state(State.MULTI_SELECTABLE),
"aria-orientation": token({
horizontal: "orientated horizontally",
vertical: "orientated vertically",
}),
"aria-owns": null, // Handled by accessibility tree construction
"aria-placeholder": string("placeholder"),
"aria-posinset": integer("item set position"),
"aria-pressed": tristate(State.PRESSED, State.PARTIALLY_PRESSED),
"aria-readonly": state(State.READ_ONLY),
"aria-relevant": null, // Handled by live region logic
"aria-required": state(State.REQUIRED),
"aria-roledescription": null, // Handled by accessible description
"aria-rowcount": integer("row count"),
"aria-rowindex": integer("row index"),
"aria-rowindextext": string("row index"),
"aria-rowspan": integer("row span"),
"aria-selected": state(State.SELECTED),
"aria-setsize": integer("item set size"),
"aria-sort": token({
ascending: "sorted in ascending order",
descending: "sorted in descending order",
none: "no defined sort order",
other: "non ascending / descending sort order applied",
}),
"aria-valuemax": number("max value"),
"aria-valuemin": number("min value"),
"aria-valuenow": number("current value"),
"aria-valuetext": string("current value"),
};
interface MapperArgs {
attributeValue: string;
container?: Node;
negative?: boolean;
}
function state(stateValue: State) {
return function stateMapper({ attributeValue, negative }: MapperArgs) {
if (negative) {
return attributeValue !== "false" ? `not ${stateValue}` : stateValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function idRefs(
propertyDescriptionSuffixSingular: string,
propertyDescriptionSuffixPlural: string,
printCount = true
) {
return function mapper({ attributeValue, container }: MapperArgs) {
const idRefsCount = attributeValue
.trim()
.split(" ")
|
.filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;
|
if (idRefsCount === 0) {
return "";
}
return `${printCount ? `${idRefsCount} ` : ""}${
idRefsCount === 1
? propertyDescriptionSuffixSingular
: propertyDescriptionSuffixPlural
}`;
};
}
function idRef(propertyName: string) {
return function mapper({ attributeValue: idRef, container }: MapperArgs) {
const node = getNodeByIdRef({ container, idRef });
if (!node) {
return "";
}
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const itemText = getItemText({ accessibleName, accessibleValue });
return concat(propertyName)({ attributeValue: itemText });
};
}
function tristate(stateValue: State, mixedValue: State) {
return function stateMapper({ attributeValue }: MapperArgs) {
if (attributeValue === "mixed") {
return mixedValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function token(tokenMap: Record<string, string>) {
return function tokenMapper({ attributeValue }: MapperArgs) {
return tokenMap[attributeValue];
};
}
function concat(propertyName: string) {
return function mapper({ attributeValue }: MapperArgs) {
return attributeValue ? `${propertyName} ${attributeValue}` : "";
};
}
function integer(propertyName: string) {
return concat(propertyName);
}
function number(propertyName: string) {
return concat(propertyName);
}
function string(propertyName: string) {
return concat(propertyName);
}
export const mapAttributeNameAndValueToLabel = ({
attributeName,
attributeValue,
container,
negative = false,
}: {
attributeName: string;
attributeValue: string | null;
container: Node;
negative?: boolean;
}) => {
if (typeof attributeValue !== "string") {
return null;
}
const mapper = ariaPropertyToVirtualLabelMap[attributeName];
return mapper?.({ attributeValue, container, negative }) ?? null;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getIdRefsByAttribute.ts",
"retrieved_chunk": "export function getIdRefsByAttribute({ attributeName, node }) {\n return (node.getAttribute(attributeName) ?? \"\")\n .trim()\n .split(\" \")\n .filter(Boolean);\n}",
"score": 0.8462532758712769
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.815402626991272
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " alternateReadingOrderMap: Map<Node, Set<Node>>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-flowto\",\n node,\n });\n idRefs.forEach((idRef) => {\n const childNode = getNodeByIdRef({ container, idRef });\n if (!childNode) {",
"score": 0.8060076832771301
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": "function addOwnedNodes(\n node: Element,\n ownedNodes: Set<Node>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-owns\",\n node,\n });\n idRefs.forEach((idRef) => {",
"score": 0.798503041267395
},
{
"filename": "src/getNodeByIdRef.ts",
"retrieved_chunk": "import { isElement } from \"./isElement\";\nexport function getNodeByIdRef({ container, idRef }) {\n if (!isElement(container) || !idRef) {\n return null;\n }\n return container.querySelector(`#${idRef}`);\n}",
"score": 0.7932456731796265
}
] |
typescript
|
.filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role } = getRole({
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
|
const isExplicitPresentational = presentationRoles.includes(explicitRole);
|
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.8911899328231812
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 0.8890408873558044
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": " accessibleName === accessibleValue ? \"\" : accessibleValue;\n return [\n spokenRole,\n accessibleName,\n announcedValue,\n accessibleDescription,\n ...accessibleAttributeLabels,\n ]\n .filter(Boolean)\n .join(\", \");",
"score": 0.8870769739151001
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " const explicitRole = getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node: target,\n });\n target.removeAttribute(\"role\");\n let implicitRole = getImplicitRole(target) ?? \"\";\n if (!implicitRole) {\n // TODO: remove this fallback post https://github.com/eps1lon/dom-accessibility-api/pull/937",
"score": 0.8780815601348877
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8774539232254028
}
] |
typescript
|
const isExplicitPresentational = presentationRoles.includes(explicitRole);
|
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
[
|
moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
|
src/commands/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.839185357093811
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.8342464566230774
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.808972954750061
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " implicitRole = Object.keys(getRoles(target))?.[0] ?? \"\";\n }\n if (explicitRole) {\n return { explicitRole, implicitRole, role: explicitRole };\n }\n return {\n explicitRole,\n implicitRole,\n role: implicitRole,\n };",
"score": 0.8088997006416321
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.792655348777771
}
] |
typescript
|
moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
if (!isElement(node)) {
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
|
const itemText = getItemText(accessibilityNode);
|
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = commands[command]?.({
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
|
src/Virtual.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8304671049118042
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "import { getAccessibleName } from \"../getAccessibleName\";\nimport { getAccessibleValue } from \"../getAccessibleValue\";\nimport { getItemText } from \"../../getItemText\";\nimport { getNodeByIdRef } from \"../../getNodeByIdRef\";\nenum State {\n BUSY = \"busy\",\n CHECKED = \"checked\",\n CURRENT = \"current item\",\n DISABLED = \"disabled\",\n EXPANDED = \"expanded\",",
"score": 0.8289328813552856
},
{
"filename": "src/getItemText.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getItemText = (\n accessibilityNode: Pick<\n AccessibilityNode,\n \"accessibleName\" | \"accessibleValue\"\n >\n) => {\n const { accessibleName, accessibleValue } = accessibilityNode;\n const announcedValue =\n accessibleName === accessibleValue ? \"\" : accessibleValue;",
"score": 0.8261823654174805
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "].join(\", \");\nfunction isFocusable(node: HTMLElement) {\n return node.matches(FOCUSABLE_SELECTOR);\n}\nfunction hasGlobalStateOrProperty(node: HTMLElement) {\n return globalStatesAndProperties.some((global) => node.hasAttribute(global));\n}\nfunction getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,",
"score": 0.824690580368042
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8232488036155701
}
] |
typescript
|
const itemText = getItemText(accessibilityNode);
|
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
|
if (!isElement(node)) {
|
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = commands[command]?.({
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
|
src/Virtual.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }: AccessibilityContext\n): AccessibilityNodeTree {\n /**\n * Authors MUST NOT create circular references with aria-owns. In the case of\n * authoring error with aria-owns, the user agent MAY ignore some aria-owns\n * element references in order to build a consistent model of the content.\n *\n * REF: https://w3c.github.io/aria/#aria-owns\n */\n if (visitedNodes.has(node)) {",
"score": 0.8051059246063232
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": "function addOwnedNodes(\n node: Element,\n ownedNodes: Set<Node>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-owns\",\n node,\n });\n idRefs.forEach((idRef) => {",
"score": 0.8014276027679443
},
{
"filename": "src/isElement.ts",
"retrieved_chunk": "export function isElement(node: Node): node is HTMLElement {\n return node.nodeType === Node.ELEMENT_NODE;\n}",
"score": 0.7978020906448364
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n node\n .querySelectorAll(\"[aria-owns]\")\n .forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));\n return ownedNodes;\n}\nfunction getOwnedNodes(node: Node, container: Node) {\n const ownedNodes = new Set<Node>();\n if (!isElement(node) || !isElement(container)) {\n return ownedNodes;",
"score": 0.7956022024154663
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " return tree;\n }\n visitedNodes.add(node);\n node.childNodes.forEach((childNode) => {\n if (isHiddenFromAccessibilityTree(childNode)) {\n return;\n }\n // REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357\n if (ownedNodes.has(childNode)) {\n return;",
"score": 0.7895088791847229
}
] |
typescript
|
if (!isElement(node)) {
|
import { getAccessibleName } from "../getAccessibleName";
import { getAccessibleValue } from "../getAccessibleValue";
import { getItemText } from "../../getItemText";
import { getNodeByIdRef } from "../../getNodeByIdRef";
enum State {
BUSY = "busy",
CHECKED = "checked",
CURRENT = "current item",
DISABLED = "disabled",
EXPANDED = "expanded",
INVALID = "invalid",
MODAL = "modal",
MULTI_SELECTABLE = "multi-selectable",
PARTIALLY_CHECKED = "partially checked",
PARTIALLY_PRESSED = "partially pressed",
PRESSED = "pressed",
READ_ONLY = "read only",
REQUIRED = "required",
SELECTED = "selected",
}
// https://w3c.github.io/aria/#state_prop_def
const ariaPropertyToVirtualLabelMap: Record<
string,
((...args: unknown[]) => string) | null
> = {
"aria-activedescendant": idRef("active descendant"),
"aria-atomic": null, // Handled by live region logic
"aria-autocomplete": token({
inline: "autocomplete inlined",
list: "autocomplete in list",
both: "autocomplete inlined and in list",
none: "no autocomplete",
}),
"aria-braillelabel": null, // Currently won't do - not implementing a braille screen reader
"aria-brailleroledescription": null, // Currently won't do - not implementing a braille screen reader
"aria-busy": state(State.BUSY),
"aria-checked": tristate(State.CHECKED, State.PARTIALLY_CHECKED),
"aria-colcount": integer("column count"),
"aria-colindex": integer("column index"),
"aria-colindextext": string("column index"),
"aria-colspan": integer("column span"),
"aria-controls": idRefs("control", "controls"), // Handled by virtual.perform()
"aria-current": token({
page: "current page",
step: "current step",
location: "current location",
date: "current date",
time: "current time",
true: State.CURRENT,
false: `not ${State.CURRENT}`,
}),
"aria-describedby": null, // Handled by accessible description
"aria-description": null, // Handled by accessible description
"aria-details": idRefs("linked details", "linked details", false),
"aria-disabled": state(State.DISABLED),
"aria-dropeffect": null, // Deprecated in WAI-ARIA 1.1
"aria-errormessage": null, // TODO: decide what to announce here
"aria-expanded": state(State.EXPANDED),
"aria-flowto": idRefs("alternate reading order", "alternate reading orders"), // Handled by virtual.perform()
"aria-grabbed": null, // Deprecated in WAI-ARIA 1.1
"aria-haspopup": token({
/**
* Assistive technologies SHOULD NOT expose the aria-haspopup property if
* it has a value of false.
*
* REF: // https://w3c.github.io/aria/#aria-haspopup
*/
false: null,
true: "has popup menu",
menu: "has popup menu",
listbox: "has popup listbox",
tree: "has popup tree",
grid: "has popup grid",
dialog: "has popup dialog",
}),
"aria-hidden": null, // Excluded from accessibility tree
"aria-invalid": token({
grammar: "grammatical error detected",
false: `not ${State.INVALID}`,
spelling: "spelling error detected",
true: State.INVALID,
}),
"aria-keyshortcuts": string("key shortcuts"),
"aria-label": null, // Handled by accessible name
"aria-labelledby": null, // Handled by accessible name
"aria-level": integer("level"),
"aria-live": null, // Handled by live region logic
"aria-modal": state(State.MODAL),
"aria-multiselectable": state(State.MULTI_SELECTABLE),
"aria-orientation": token({
horizontal: "orientated horizontally",
vertical: "orientated vertically",
}),
"aria-owns": null, // Handled by accessibility tree construction
"aria-placeholder": string("placeholder"),
"aria-posinset": integer("item set position"),
"aria-pressed": tristate(State.PRESSED, State.PARTIALLY_PRESSED),
"aria-readonly": state(State.READ_ONLY),
"aria-relevant": null, // Handled by live region logic
"aria-required": state(State.REQUIRED),
"aria-roledescription": null, // Handled by accessible description
"aria-rowcount": integer("row count"),
"aria-rowindex": integer("row index"),
"aria-rowindextext": string("row index"),
"aria-rowspan": integer("row span"),
"aria-selected": state(State.SELECTED),
"aria-setsize": integer("item set size"),
"aria-sort": token({
ascending: "sorted in ascending order",
descending: "sorted in descending order",
none: "no defined sort order",
other: "non ascending / descending sort order applied",
}),
"aria-valuemax": number("max value"),
"aria-valuemin": number("min value"),
"aria-valuenow": number("current value"),
"aria-valuetext": string("current value"),
};
interface MapperArgs {
attributeValue: string;
container?: Node;
negative?: boolean;
}
function state(stateValue: State) {
return function stateMapper({ attributeValue, negative }: MapperArgs) {
if (negative) {
return attributeValue !== "false" ? `not ${stateValue}` : stateValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function idRefs(
propertyDescriptionSuffixSingular: string,
propertyDescriptionSuffixPlural: string,
printCount = true
) {
return function mapper({ attributeValue, container }: MapperArgs) {
const idRefsCount = attributeValue
.trim()
.split(" ")
.filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;
if (idRefsCount === 0) {
return "";
}
return `${printCount ? `${idRefsCount} ` : ""}${
idRefsCount === 1
? propertyDescriptionSuffixSingular
: propertyDescriptionSuffixPlural
}`;
};
}
function idRef(propertyName: string) {
return function mapper({ attributeValue: idRef, container }: MapperArgs) {
const node = getNodeByIdRef({ container, idRef });
if (!node) {
return "";
}
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
|
const itemText = getItemText({ accessibleName, accessibleValue });
|
return concat(propertyName)({ attributeValue: itemText });
};
}
function tristate(stateValue: State, mixedValue: State) {
return function stateMapper({ attributeValue }: MapperArgs) {
if (attributeValue === "mixed") {
return mixedValue;
}
return attributeValue !== "false" ? stateValue : `not ${stateValue}`;
};
}
function token(tokenMap: Record<string, string>) {
return function tokenMapper({ attributeValue }: MapperArgs) {
return tokenMap[attributeValue];
};
}
function concat(propertyName: string) {
return function mapper({ attributeValue }: MapperArgs) {
return attributeValue ? `${propertyName} ${attributeValue}` : "";
};
}
function integer(propertyName: string) {
return concat(propertyName);
}
function number(propertyName: string) {
return concat(propertyName);
}
function string(propertyName: string) {
return concat(propertyName);
}
export const mapAttributeNameAndValueToLabel = ({
attributeName,
attributeValue,
container,
negative = false,
}: {
attributeName: string;
attributeValue: string | null;
container: Node;
negative?: boolean;
}) => {
if (typeof attributeValue !== "string") {
return null;
}
const mapper = ariaPropertyToVirtualLabelMap[attributeName];
return mapper?.({ attributeValue, container, negative }) ?? null;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getIdRefsByAttribute.ts",
"retrieved_chunk": "export function getIdRefsByAttribute({ attributeName, node }) {\n return (node.getAttribute(attributeName) ?? \"\")\n .trim()\n .split(\" \")\n .filter(Boolean);\n}",
"score": 0.8482394218444824
},
{
"filename": "src/getNodeByIdRef.ts",
"retrieved_chunk": "import { isElement } from \"./isElement\";\nexport function getNodeByIdRef({ container, idRef }) {\n if (!isElement(container) || !idRef) {\n return null;\n }\n return container.querySelector(`#${idRef}`);\n}",
"score": 0.8316100239753723
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8299580812454224
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8289196491241455
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": "import { getIdRefsByAttribute } from \"./getIdRefsByAttribute\";\nimport { getNodeAccessibilityData } from \"./getNodeAccessibilityData\";\nimport { getNodeByIdRef } from \"./getNodeByIdRef\";\nimport { HTMLElementWithValue } from \"./getNodeAccessibilityData/getAccessibleValue\";\nimport { isElement } from \"./isElement\";\nimport { isInaccessible } from \"dom-accessibility-api\";\nexport interface AccessibilityNode {\n accessibleAttributeLabels: string[];\n accessibleDescription: string;\n accessibleName: string;",
"score": 0.8270676136016846
}
] |
typescript
|
const itemText = getItemText({ accessibleName, accessibleValue });
|
import { getAttributesByRole } from "./getAttributesByRole";
import { getLabelFromAriaAttribute } from "./getLabelFromAriaAttribute";
import { getLabelFromHtmlEquivalentAttribute } from "./getLabelFromHtmlEquivalentAttribute";
import { getLabelFromImplicitHtmlElementValue } from "./getLabelFromImplicitHtmlElementValue";
import { isElement } from "../../isElement";
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
import { postProcessLabels } from "./postProcessLabels";
export const getAccessibleAttributeLabels = ({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
}: {
accessibleValue: string;
alternateReadingOrderParents: Node[];
container: Node;
node: Node;
role: string;
}): string[] => {
if (!isElement(node)) {
return [];
}
const labels: Record<string, { label: string; value: string }> = {};
const attributes = getAttributesByRole({ accessibleValue, role });
attributes.forEach(([attributeName, implicitAttributeValue]) => {
const {
label: labelFromHtmlEquivalentAttribute,
value: valueFromHtmlEquivalentAttribute,
} = getLabelFromHtmlEquivalentAttribute({
attributeName,
container,
node,
});
if (labelFromHtmlEquivalentAttribute) {
labels[attributeName] = {
label: labelFromHtmlEquivalentAttribute,
value: valueFromHtmlEquivalentAttribute,
};
return;
}
const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =
getLabelFromAriaAttribute({
attributeName,
container,
node,
});
if (labelFromAriaAttribute) {
labels[attributeName] = {
label: labelFromAriaAttribute,
value: valueFromAriaAttribute,
};
return;
}
const {
label: labelFromImplicitHtmlElementValue,
value: valueFromImplicitHtmlElementValue,
} = getLabelFromImplicitHtmlElementValue({
attributeName,
container,
node,
});
if (labelFromImplicitHtmlElementValue) {
labels[attributeName] = {
label: labelFromImplicitHtmlElementValue,
value: valueFromImplicitHtmlElementValue,
};
return;
}
|
const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(
{
|
attributeName,
attributeValue: implicitAttributeValue,
container,
}
);
if (labelFromImplicitAriaAttributeValue) {
labels[attributeName] = {
label: labelFromImplicitAriaAttributeValue,
value: implicitAttributeValue,
};
return;
}
});
const processedLabels = postProcessLabels({ labels, role }).filter(Boolean);
/**
* aria-flowto MUST requirements:
*
* The reading order goes both directions, and a user needs to be aware of the
* alternate reading order so that they can invoke the functionality.
*
* The reading order goes both directions, and a user needs to be able to
* travel backwards through their chosen reading order.
*
* REF: https://a11ysupport.io/tech/aria/aria-flowto_attribute
*/
if (alternateReadingOrderParents.length > 0) {
processedLabels.push(
`${alternateReadingOrderParents.length} previous alternate reading ${
alternateReadingOrderParents.length === 1 ? "order" : "orders"
}`
);
}
return processedLabels;
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " });\n if (label) {\n return { label, value: attributeValue };\n }\n }\n return { label: \"\", value: \"\" };\n};",
"score": 0.8980210423469543
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8848042488098145
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.8832043409347534
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": "import { mapAttributeNameAndValueToLabel } from \"./mapAttributeNameAndValueToLabel\";\nconst mapLocalNameToImplicitValue = {\n \"aria-level\": {\n h1: \"1\",\n h2: \"2\",\n h3: \"3\",\n h4: \"4\",\n h5: \"5\",\n h6: \"6\",\n },",
"score": 0.881739616394043
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.8755019307136536
}
] |
typescript
|
const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(
{
|
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
if (!isElement(node)) {
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
|
) as { [K in VirtualCommandKey]: K };
|
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = commands[command]?.({
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
|
src/Virtual.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),\n};\nexport type VirtualCommands = {\n [K in keyof typeof commands]: (typeof commands)[K];\n};\nexport type VirtualCommandKey = keyof VirtualCommands;",
"score": 0.8347878456115723
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " (typeof quickLandmarkNavigationRoles)[number]\n >}`]: (args: VirtualCommandArgs) => number | null;\n};\nexport const commands = {\n jumpToControlledElement,\n jumpToDetailsElement,\n moveToNextAlternateReadingOrderElement,\n moveToPreviousAlternateReadingOrderElement,\n ...quickLandmarkNavigationCommands,\n moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),",
"score": 0.7823609113693237
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " \"search\",\n] as const;\nconst quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<\n Record<string, unknown>\n>((accumulatedCommands, role) => {\n const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(\n 1\n )}`;\n const moveToPreviousCommand = `moveToPrevious${role\n .at(0)",
"score": 0.7795157432556152
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " .toUpperCase()}${role.slice(1)}`;\n return {\n ...accumulatedCommands,\n [moveToNextCommand]: getNextIndexByRole([role]),\n [moveToPreviousCommand]: getPreviousIndexByRole([role]),\n };\n}, {}) as {\n [K in\n | `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`\n | `moveToPrevious${Capitalize<",
"score": 0.7746729850769043
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import { StartOptions, Virtual } from \"./Virtual\";\nexport const virtual = new Virtual();\ntype _Virtual = typeof virtual;\nexport { StartOptions, _Virtual as Virtual };",
"score": 0.7650867700576782
}
] |
typescript
|
) as { [K in VirtualCommandKey]: K };
|
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
if (!isElement(node)) {
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const
|
nextIndex = commands[command]?.({
|
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
|
src/Virtual.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/types.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nexport interface VirtualCommandArgs {\n currentIndex: number;\n container: Node;\n tree: AccessibilityNode[];\n}",
"score": 0.8240683674812317
},
{
"filename": "src/commands/jumpToControlledElement.ts",
"retrieved_chunk": " */\nexport function jumpToControlledElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: JumpToControlledElementCommandArgs) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-controls\",\n index,",
"score": 0.8165030479431152
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8014246821403503
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " (typeof quickLandmarkNavigationRoles)[number]\n >}`]: (args: VirtualCommandArgs) => number | null;\n};\nexport const commands = {\n jumpToControlledElement,\n jumpToDetailsElement,\n moveToNextAlternateReadingOrderElement,\n moveToPreviousAlternateReadingOrderElement,\n ...quickLandmarkNavigationCommands,\n moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),",
"score": 0.7953542470932007
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7905380725860596
}
] |
typescript
|
nextIndex = commands[command]?.({
|
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
const childNode = getNodeByIdRef({ container, idRef });
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
.
|
querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
|
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
|
src/createAccessibilityTree.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8361176252365112
},
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": "export function moveToNextAlternateReadingOrderElement({\n index,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-flowto\",\n index,\n container,",
"score": 0.8275851607322693
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " *\n * The reading order goes both directions, and a user needs to be able to\n * travel backwards through their chosen reading order.\n *\n * REF: https://a11ysupport.io/tech/aria/aria-flowto_attribute\n */\n if (alternateReadingOrderParents.length > 0) {\n processedLabels.push(\n `${alternateReadingOrderParents.length} previous alternate reading ${\n alternateReadingOrderParents.length === 1 ? \"order\" : \"orders\"",
"score": 0.8223447203636169
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": "}: {\n allowedAccessibilityRoles: string[][];\n alternateReadingOrderParents: Node[];\n container: Node;\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n const accessibleDescription = getAccessibleDescription(node);\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);",
"score": 0.8211014866828918
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " }\n }\n return role;\n};\nexport function getNodeAccessibilityData({\n allowedAccessibilityRoles,\n alternateReadingOrderParents,\n container,\n inheritedImplicitPresentational,\n node,",
"score": 0.8160525560379028
}
] |
typescript
|
querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
|
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
|
const childNode = getNodeByIdRef({ container, idRef });
|
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
|
src/createAccessibilityTree.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": "export function moveToNextAlternateReadingOrderElement({\n index,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-flowto\",\n index,\n container,",
"score": 0.8801190853118896
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8672835230827332
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8508778214454651
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.8416834473609924
},
{
"filename": "src/commands/jumpToDetailsElement.ts",
"retrieved_chunk": " attributeName: \"aria-details\",\n index: 0,\n container,\n currentIndex,\n tree,\n });\n}",
"score": 0.8405045866966248
}
] |
typescript
|
const childNode = getNodeByIdRef({ container, idRef });
|
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
|
[moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
|
src/commands/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.8411437273025513
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.8328242897987366
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " implicitRole = Object.keys(getRoles(target))?.[0] ?? \"\";\n }\n if (explicitRole) {\n return { explicitRole, implicitRole, role: explicitRole };\n }\n return {\n explicitRole,\n implicitRole,\n role: implicitRole,\n };",
"score": 0.8136058449745178
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.8111430406570435
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.7925989627838135
}
] |
typescript
|
[moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
[moveToNextCommand]: getNextIndexByRole([role]),
|
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
|
src/commands/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.8411437273025513
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.8328242897987366
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " implicitRole = Object.keys(getRoles(target))?.[0] ?? \"\";\n }\n if (explicitRole) {\n return { explicitRole, implicitRole, role: explicitRole };\n }\n return {\n explicitRole,\n implicitRole,\n role: implicitRole,\n };",
"score": 0.8136058449745178
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.8111430406570435
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.7925989627838135
}
] |
typescript
|
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
};
|
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
// REF: https://www.w3.org/TR/html-aria/#docconformance-attr
const ariaToHTMLAttributeMapping: Record<
string,
Array<{ name: string; negative?: boolean }>
> = {
"aria-checked": [{ name: "checked" }],
"aria-disabled": [{ name: "disabled" }],
// "aria-hidden": [{ name: "hidden" }],
"aria-placeholder": [{ name: "placeholder" }],
"aria-valuemax": [{ name: "max" }],
"aria-valuemin": [{ name: "min" }],
"aria-readonly": [
{ name: "readonly" },
{ name: "contenteditable", negative: true },
],
"aria-required": [{ name: "required" }],
"aria-colspan": [{ name: "colspan" }],
"aria-rowspan": [{ name: "rowspan" }],
};
export const getLabelFromHtmlEquivalentAttribute = ({
attributeName,
container,
node,
}: {
attributeName: string;
container: Node;
node: HTMLElement;
}) => {
const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];
if (!htmlAttribute?.length) {
return { label: "", value: "" };
}
for (const { name, negative = false } of htmlAttribute) {
const attributeValue = node.getAttribute(name);
const
|
label = mapAttributeNameAndValueToLabel({
|
attributeName,
attributeValue,
container,
negative,
});
if (label) {
return { label, value: attributeValue };
}
}
return { label: "", value: "" };
};
|
src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " node,\n });\n if (labelFromImplicitHtmlElementValue) {\n labels[attributeName] = {\n label: labelFromImplicitHtmlElementValue,\n value: valueFromImplicitHtmlElementValue,\n };\n return;\n }\n const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(",
"score": 0.9219418168067932
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.9022256135940552
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.9001984000205994
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " }\n const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =\n getLabelFromAriaAttribute({\n attributeName,\n container,\n node,\n });\n if (labelFromAriaAttribute) {\n labels[attributeName] = {\n label: labelFromAriaAttribute,",
"score": 0.8995590209960938
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8939982652664185
}
] |
typescript
|
label = mapAttributeNameAndValueToLabel({
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role } = getRole({
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const
|
isExplicitPresentational = presentationRoles.includes(explicitRole);
|
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.8954516649246216
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8842745423316956
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n container,\n node: childNode,\n inheritedImplicitPresentational: tree.childrenPresentational,\n });",
"score": 0.881272554397583
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " const explicitRole = getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node: target,\n });\n target.removeAttribute(\"role\");\n let implicitRole = getImplicitRole(target) ?? \"\";\n if (!implicitRole) {\n // TODO: remove this fallback post https://github.com/eps1lon/dom-accessibility-api/pull/937",
"score": 0.8750498294830322
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": " accessibleName === accessibleValue ? \"\" : accessibleValue;\n return [\n spokenRole,\n accessibleName,\n announcedValue,\n accessibleDescription,\n ...accessibleAttributeLabels,\n ]\n .filter(Boolean)\n .join(\", \");",
"score": 0.8732466697692871
}
] |
typescript
|
isExplicitPresentational = presentationRoles.includes(explicitRole);
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role } = getRole({
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels
|
= getAccessibleAttributeLabels({
|
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const isExplicitPresentational = presentationRoles.includes(explicitRole);
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.9162009358406067
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 0.9086909294128418
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.9081697463989258
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.900611400604248
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8997248411178589
}
] |
typescript
|
= getAccessibleAttributeLabels({
|
import { isElement } from "../isElement";
export type HTMLElementWithValue =
| HTMLButtonElement
| HTMLDataElement
| HTMLInputElement
| HTMLLIElement
| HTMLMeterElement
| HTMLOptionElement
| HTMLProgressElement
| HTMLParamElement;
const ignoredInputTypes = ["checkbox", "radio"];
const allowedLocalNames = [
"button",
"data",
"input",
// "li",
"meter",
"option",
"progress",
"param",
];
function getSelectValue(node: HTMLSelectElement) {
const selectedOptions = [...node.options].filter(
(optionElement) => optionElement.selected
);
if (node.multiple) {
return [...selectedOptions]
.map((optionElement) => getValue(optionElement))
.join("; ");
}
if (selectedOptions.length === 0) {
return "";
}
return getValue(selectedOptions[0]);
}
function getInputValue(node: HTMLInputElement) {
if (ignoredInputTypes.includes(node.type)) {
return "";
}
return getValue(node);
}
function getValue(node: HTMLElementWithValue) {
if (!allowedLocalNames.includes(node.localName)) {
return "";
}
if (
node.getAttribute("aria-valuetext") ||
node.getAttribute("aria-valuenow")
) {
return "";
}
return typeof node.value === "number" ? `${node.value}` : node.value;
}
export function getAccessibleValue(node: Node) {
if (!isElement(node)) {
return "";
}
|
switch (node.localName) {
|
case "input": {
return getInputValue(node as HTMLInputElement);
}
case "select": {
return getSelectValue(node as HTMLSelectElement);
}
}
return getValue(node as HTMLElementWithValue);
}
|
src/getNodeAccessibilityData/getAccessibleValue.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getAccessibleName.ts",
"retrieved_chunk": "import { computeAccessibleName } from \"dom-accessibility-api\";\nimport { isElement } from \"../isElement\";\nexport function getAccessibleName(node: Node) {\n return isElement(node)\n ? computeAccessibleName(node).trim()\n : node.textContent.trim();\n}",
"score": 0.8882733583450317
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleDescription.ts",
"retrieved_chunk": "import { computeAccessibleDescription } from \"dom-accessibility-api\";\nimport { isElement } from \"../isElement\";\nexport function getAccessibleDescription(node: Node) {\n return isElement(node) ? computeAccessibleDescription(node).trim() : \"\";\n}",
"score": 0.8806231021881104
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " // to include.\n accessibleName ===\n (\n node.textContent ||\n `${(node as HTMLElementWithValue).value}` ||\n \"\"\n )?.trim()\n );\n}\nfunction flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {",
"score": 0.8470054268836975
},
{
"filename": "src/getItemText.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getItemText = (\n accessibilityNode: Pick<\n AccessibilityNode,\n \"accessibleName\" | \"accessibleValue\"\n >\n) => {\n const { accessibleName, accessibleValue } = accessibilityNode;\n const announcedValue =\n accessibleName === accessibleValue ? \"\" : accessibleValue;",
"score": 0.8418276906013489
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8354039192199707
}
] |
typescript
|
switch (node.localName) {
|
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role
|
} = getRole({
|
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const isExplicitPresentational = presentationRoles.includes(explicitRole);
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
|
src/getNodeAccessibilityData/index.ts
|
guidepup-virtual-screen-reader-1b0a234
|
[
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.9230987429618835
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: [],\n alternateReadingOrderParents: [],\n container: node,\n node,",
"score": 0.9108682870864868
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue: string;\n allowedAccessibilityChildRoles: string[][];\n alternateReadingOrderParents: Node[];\n childrenPresentational: boolean;\n node: Node;\n parent: Node | null;\n role: string;\n spokenRole: string;\n}\ninterface AccessibilityNodeTree extends AccessibilityNode {",
"score": 0.8997435569763184
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n container,\n node: childNode,\n inheritedImplicitPresentational: tree.childrenPresentational,\n });",
"score": 0.8951684236526489
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8946589231491089
}
] |
typescript
|
} = getRole({
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy
|
(targetCharacter: EnemyCharacter) {
|
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8789746165275574
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ).play();\n Actions.sequence(\n Actions.parallel(\n Actions.fadeOut(this.dungeonGrid, 0.2),\n Actions.moveTo(\n this.dungeonGrid,\n this.dungeonGrid.position.x - dx,\n this.dungeonGrid.position.y - dy,\n 0.5",
"score": 0.834640383720398
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8334454894065857
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.828838050365448
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = true;\n this.pumpQueuedMove();\n })\n ).play();\n }\n } else {\n this.queuedMove = { dx, dy };\n }\n }\n postMove(delay: number) {",
"score": 0.8226965069770813
}
] |
typescript
|
(targetCharacter: EnemyCharacter) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
|
const enemyCharacter = new EnemyCharacter("enemy1");
|
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.8529941439628601
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.8206520080566406
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n clearEnemies() {\n for (let i = this.characters.length - 1; i >= 0; i--) {\n const c = this.characters[i];\n if (!c.isPlayer) {\n Actions.fadeOutAndRemove(c, 0.2).play();\n this.characters.splice(i, 1);\n }\n }\n }",
"score": 0.8201822638511658
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": " this.maxHp = 1;\n } else if (this.type === \"enemy2\") {\n this.hp = 2;\n this.maxHp = 2;\n } else if (this.type === \"enemy3\") {\n this.hp = 3;\n this.maxHp = 3;\n }\n }\n get isEnemy() {",
"score": 0.8195101618766785
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8161571025848389
}
] |
typescript
|
const enemyCharacter = new EnemyCharacter("enemy1");
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new
|
EnemyCharacter(type);
|
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.8851041197776794
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.871636688709259
},
{
"filename": "src/screens/game/character/PlayerCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nexport default class PlayerCharacter extends Character {\n constructor() {\n super(\"player-character.png\");\n this.type = \"player\";\n this.hp = 4;\n this.maxHp = 4;\n }\n get isPlayer() {\n return true;",
"score": 0.8332380056381226
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8200986385345459
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8193790912628174
}
] |
typescript
|
EnemyCharacter(type);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find
|
(c => c.isPlayer);
|
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8681681156158447
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8561931252479553
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8485637903213501
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8473483920097351
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8293420672416687
}
] |
typescript
|
(c => c.isPlayer);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
|
this.setPositionTo(w, w.from, true);
|
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n from: this.serialiseCoords(w.from),\n to: this.serialiseCoords(w.to),\n };\n });\n }\n private static deserialiseWalls(walls: any): Wall[] {\n return walls.map(\n (w: any) =>\n new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))",
"score": 0.8352254629135132
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8324254751205444
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " }\n setPositionTo(\n actor: PIXI.Container,\n coords: Coords,\n isWall: boolean = false\n ) {\n if (isWall) {\n if ((actor as Wall).isHorizontal) {\n actor.position.set(\n this.cellSize * coords.col + (this.cellSize - actor.width) / 2,",
"score": 0.825514018535614
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.8245683908462524
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nexport default class Wall extends PIXI.Container {\n static CONNECTION_PREFERRED_RATIO = 0.6;\n static PREDETERMINED_LAYOUTS: any = { shrine: [] };\n from: Coords;\n to: Coords;\n sprite: PIXI.Sprite;\n constructor(from: Coords, to: Coords) {",
"score": 0.8233464956283569
}
] |
typescript
|
this.setPositionTo(w, w.from, true);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
|
private static serialiseCharacters(characters: Character[]) {
|
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8557328581809998
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.8347702026367188
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.cellSquares.push(col1);\n this.cellStairs.push(col2);\n }\n this.addChild(this.wallsHolder);\n this.addChild(this.charactersHolder);\n for (let i = 0; i < this.dimension; i++) {\n for (let j = 0; j < this.dimension; j++) {\n this.coords.push(new Coords(i, j));\n }\n }",
"score": 0.8182786703109741
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " w.alpha = 0;\n Actions.fadeIn(w, 0.2).play();\n this.wallsHolder.addChild(w);\n w.setCellSize(this.cellSize);\n // Place in the correct place\n this.setPositionTo(w, w.from, true);\n }\n }\n addCharacter(character: Character) {\n character.scale.set(0.2);",
"score": 0.8169159293174744
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Delete all old walls\n for (const w of this.walls) {\n Actions.fadeOutAndRemove(w, 0.2).play();\n }\n this.walls = Wall.randomLayout(numWalls, this.dimension);\n // Add some new walls... they must generate any closed areas\n this.drawWalls(this.walls);\n }\n drawWalls(walls: Wall[]) {\n for (const w of walls) {",
"score": 0.8159478902816772
}
] |
typescript
|
private static serialiseCharacters(characters: Character[]) {
|
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
Save.initialise();
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (!Save.loadGameState(gameScreen)) {
gameScreen.nextLevel();
}
this.setScreen(gameScreen);
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
|
if (Save.hasGameState()) {
|
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
|
src/Game.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.queuedMove = null;\n this.level = 0;\n this.score = 0;\n this.gameContainer = new PIXI.Container();\n this.addChild(this.gameContainer);\n // Score\n this.scoreLabel = new PIXI.BitmapText(\"0\", Font.makeFontOptions(\"small\"));\n this.scoreLabel.anchor.set(0.5);\n this.scoreLabel.tint = 0xffffff;\n this.gameContainer.addChild(this.scoreLabel);",
"score": 0.8641060590744019
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " background.anchor.set(0, 0);\n this.addChild(background);\n for (let i = 0; i < this.dimension; i++) {\n const col1 = [];\n const col2 = [];\n for (let j = 0; j < this.dimension; j++) {\n const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);\n cell.tint = 0;\n cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;\n cell.width = this.cellSize;",
"score": 0.8606309294700623
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " sprite: PIXI.Sprite;\n heartsHolder: PIXI.Container;\n constructor(backgroundPath: string) {\n super();\n this.coords = new Coords(0, 0);\n this.sprite = PIXI.Sprite.from(Game.tex(backgroundPath));\n this.sprite.anchor.set(0.5, 1);\n this.addChild(this.sprite);\n // Add holder for hearts\n this.heartsHolder = new PIXI.Container();",
"score": 0.8384735584259033
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8381820321083069
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " state: GameState = \"play\";\n modals: PIXI.Container[] = [];\n score: number;\n scoreLabel: PIXI.BitmapText;\n prevWidth: number = 0;\n prevHeight: number = 0;\n constructor() {\n super();\n // Setup\n this.readyToMove = true;",
"score": 0.836866557598114
}
] |
typescript
|
if (Save.hasGameState()) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
|
targetCharacter.position.x += this.position.x;
|
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8381814956665039
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.832310676574707
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " 0\n );\n heart.tint = (i < this._hp) ? 0xff0000 : 0xffffff;\n this.heartsHolder.addChild(heart);\n }\n }\n damage(amount: number): boolean {\n this.hp -= amount;\n return this.hp <= 0;\n }",
"score": 0.8291482925415039
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8237972855567932
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.8232119083404541
}
] |
typescript
|
targetCharacter.position.x += this.position.x;
|
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
Save.initialise();
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (!Save.loadGameState(gameScreen)) {
gameScreen.nextLevel();
}
this.
|
setScreen(gameScreen);
|
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
if (Save.hasGameState()) {
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
|
src/Game.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " // Save game state...\n const data = this.serialiseGameState(gameScreen);\n this.engine.save(\"currentGameState\", data);\n }\n static loadGameState(gameScreen: GameScreen) {\n // Save game state...\n const data = this.engine.load(\"currentGameState\");\n if (data) {\n // Load data into gameScreen...\n this.deserialiseGameState(gameScreen, data);",
"score": 0.8784259557723999
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8693418502807617
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8457486033439636
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.gameOverModal.alpha = 0;\n Actions.sequence(\n Actions.delay(2),\n Actions.fadeIn(this.gameOverModal, 0.2)\n ).play();\n this.addChild(this.gameOverModal);\n this.resizeAgain();\n }\n nextLevel() {\n this.incScore(1);",
"score": 0.8333652019500732
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.831769585609436
}
] |
typescript
|
setScreen(gameScreen);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
|
c = new PlayerCharacter();
|
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.8615031838417053
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.8431306481361389
},
{
"filename": "src/screens/game/character/PlayerCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nexport default class PlayerCharacter extends Character {\n constructor() {\n super(\"player-character.png\");\n this.type = \"player\";\n this.hp = 4;\n this.maxHp = 4;\n }\n get isPlayer() {\n return true;",
"score": 0.838320255279541
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8306853175163269
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8209971189498901
}
] |
typescript
|
c = new PlayerCharacter();
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c =
|
new EnemyCharacter(type);
|
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.883564829826355
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.8703552484512329
},
{
"filename": "src/screens/game/character/PlayerCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nexport default class PlayerCharacter extends Character {\n constructor() {\n super(\"player-character.png\");\n this.type = \"player\";\n this.hp = 4;\n this.maxHp = 4;\n }\n get isPlayer() {\n return true;",
"score": 0.8323405981063843
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8215059041976929
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8189214468002319
}
] |
typescript
|
new EnemyCharacter(type);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
|
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
|
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8539640307426453
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8471605777740479
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8371952772140503
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8256150484085083
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " exitDir: Coords = null;\n constructor(gameScreen: GameScreen, dimension: number) {\n super(dimension);\n this.gameScreen = gameScreen;\n // Add cell backgrounds\n const background = PIXI.Sprite.from(PIXI.Texture.WHITE);\n background.tint = 0xd3c8a2;\n background.width = this.edgeSize;\n background.height = this.edgeSize;\n background.alpha = 1;",
"score": 0.8142127394676208
}
] |
typescript
|
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
|
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
Save.initialise();
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (!
|
Save.loadGameState(gameScreen)) {
|
gameScreen.nextLevel();
}
this.setScreen(gameScreen);
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
if (Save.hasGameState()) {
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
|
src/Game.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " // Save game state...\n const data = this.serialiseGameState(gameScreen);\n this.engine.save(\"currentGameState\", data);\n }\n static loadGameState(gameScreen: GameScreen) {\n // Save game state...\n const data = this.engine.load(\"currentGameState\");\n if (data) {\n // Load data into gameScreen...\n this.deserialiseGameState(gameScreen, data);",
"score": 0.8749275207519531
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8686224222183228
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.8337439298629761
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8309502601623535
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " state: GameState = \"play\";\n modals: PIXI.Container[] = [];\n score: number;\n scoreLabel: PIXI.BitmapText;\n prevWidth: number = 0;\n prevHeight: number = 0;\n constructor() {\n super();\n // Setup\n this.readyToMove = true;",
"score": 0.8251838684082031
}
] |
typescript
|
Save.loadGameState(gameScreen)) {
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.
|
coords = coords;
|
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.9091205596923828
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.8855041861534119
},
{
"filename": "src/screens/game/character/PlayerCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nexport default class PlayerCharacter extends Character {\n constructor() {\n super(\"player-character.png\");\n this.type = \"player\";\n this.hp = 4;\n this.maxHp = 4;\n }\n get isPlayer() {\n return true;",
"score": 0.8530826568603516
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8447476625442505
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8380745649337769
}
] |
typescript
|
coords = coords;
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
|
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
|
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Coords } from \"utils\";\nimport type { EnemyCharacterType } from \"./EnemyCharacter\";\nexport type CharacterType = \"player\" | EnemyCharacterType;\nexport default class Character extends PIXI.Container {\n coords: Coords;\n _hp: number = 1;\n _maxHp: number = 1;\n type: CharacterType;",
"score": 0.848747968673706
},
{
"filename": "src/screens/game/character/EnemyCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nimport * as _ from \"underscore\";\nexport type EnemyCharacterType = \"enemy1\" | \"enemy2\" | \"enemy3\";\nexport default class EnemyCharacter extends Character {\n constructor(type: EnemyCharacterType) {\n const spriteName = \"enemy-character.png\";\n super(spriteName);\n this.type = type;\n if (this.type === \"enemy1\") {\n this.hp = 1;",
"score": 0.8320224285125732
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8206847906112671
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8130356073379517
},
{
"filename": "src/screens/game/character/PlayerCharacter.ts",
"retrieved_chunk": "import Character from \"./Character\";\nexport default class PlayerCharacter extends Character {\n constructor() {\n super(\"player-character.png\");\n this.type = \"player\";\n this.hp = 4;\n this.maxHp = 4;\n }\n get isPlayer() {\n return true;",
"score": 0.8044151067733765
}
] |
typescript
|
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
|
if (!this.inBounds(targetCoord)) {
|
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8739497661590576
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8685508966445923
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n return !(c < 0 || c >= this.dimension || r < 0 || r >= this.dimension);\n }\n makeMoveTo(\n character: Character,",
"score": 0.8562880158424377
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8382437825202942
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " dy = 1;\n }\n if (dx != 0 || dy != 0) {\n // Attempted move\n this.doMove(dx, dy);\n }\n }\n}",
"score": 0.8366754651069641
}
] |
typescript
|
if (!this.inBounds(targetCoord)) {
|
import * as PIXI from "pixi.js";
import { Action, Actions } from "pixi-actions";
import Character from "../character/Character";
import { Coords } from "utils";
import Wall from "./Wall";
export default class Grid extends PIXI.Container {
dimension: number;
edgeSize: number;
constructor(dimension: number) {
super();
this.dimension = dimension;
this.edgeSize = 28 * this.dimension;
}
get cellSize(): number {
return this.edgeSize / this.dimension;
}
inBounds(col: number | Coords, row: number = null) {
let c = 0,
r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
return !(c < 0 || c >= this.dimension || r < 0 || r >= this.dimension);
}
makeMoveTo(
character: Character,
dx: number = 0,
dy: number = 0,
time: number = 0.1
): Action {
return Actions.moveTo(
character,
this.cellSize * (character.coords.col + dx) + this.cellSize / 2,
this.cellSize * (character.coords.row + dy) + this.cellSize - 3,
time
);
}
setPositionTo(
actor: PIXI.Container,
coords: Coords,
isWall: boolean = false
) {
if (isWall) {
if
|
((actor as Wall).isHorizontal) {
|
actor.position.set(
this.cellSize * coords.col + (this.cellSize - actor.width) / 2,
this.cellSize * coords.row + -actor.height / 2
);
} else {
actor.position.set(
this.cellSize * coords.col + -actor.width / 2,
this.cellSize * coords.row + (this.cellSize - actor.height) / 2
);
}
} else {
actor.position.set(
this.cellSize * coords.col + this.cellSize / 2,
this.cellSize * coords.row + this.cellSize - 3
);
}
}
}
|
src/screens/game/grid/Grid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nexport default class Wall extends PIXI.Container {\n static CONNECTION_PREFERRED_RATIO = 0.6;\n static PREDETERMINED_LAYOUTS: any = { shrine: [] };\n from: Coords;\n to: Coords;\n sprite: PIXI.Sprite;\n constructor(from: Coords, to: Coords) {",
"score": 0.8431357741355896
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8292430639266968
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " this.sprite.width = this.isHorizontal ? withSize : againstSize;\n this.sprite.height = this.isHorizontal ? againstSize : withSize;\n }\n blocks(start: Coords, dx: number, dy: number) {\n if (this.isHorizontal) {\n if (dy == 0) return false;\n if (dy < 0 && this.from.equals(start)) {\n // Hitting a wall\n return true;\n }",
"score": 0.8292145729064941
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Animate to the new position\n this.makeMoveTo(character).play();\n return { didMove: true, delay: 0.05, wentThroughExit: false };\n }\n doesWallSeparate(start: Coords, dx: number, dy: number) {\n for (const w of this.walls) {\n if (w.blocks(start, dx, dy)) {\n return true;\n }\n }",
"score": 0.8262255191802979
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " const dx = horizontal ? 1 : 0;\n const dy = horizontal ? 0 : 1;\n let startX = null,\n startY = null;\n startX = _.random(horizontal ? 0 : 1, dimension - 1);\n startY = _.random(horizontal ? 1 : 0, dimension - 1);\n const from = new Coords(startX, startY);\n const to = from.clone().add(dx, dy);\n // If there is already a wall here, skip!\n let alreadyExists = false;",
"score": 0.8228230476379395
}
] |
typescript
|
((actor as Wall).isHorizontal) {
|
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
|
Save.initialise();
|
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (!Save.loadGameState(gameScreen)) {
gameScreen.nextLevel();
}
this.setScreen(gameScreen);
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
if (Save.hasGameState()) {
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
|
src/Game.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " state: GameState = \"play\";\n modals: PIXI.Container[] = [];\n score: number;\n scoreLabel: PIXI.BitmapText;\n prevWidth: number = 0;\n prevHeight: number = 0;\n constructor() {\n super();\n // Setup\n this.readyToMove = true;",
"score": 0.8698821067810059
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.queuedMove = null;\n this.level = 0;\n this.score = 0;\n this.gameContainer = new PIXI.Container();\n this.addChild(this.gameContainer);\n // Score\n this.scoreLabel = new PIXI.BitmapText(\"0\", Font.makeFontOptions(\"small\"));\n this.scoreLabel.anchor.set(0.5);\n this.scoreLabel.tint = 0xffffff;\n this.gameContainer.addChild(this.scoreLabel);",
"score": 0.8688763380050659
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import Game from \"Game\";\nimport * as PIXI from \"pixi.js\";\nimport \"./style.css\";\nlet timeout: any = null;\nfunction onLoad() {\n function doResize() {\n game.resize();\n }\n const app = new PIXI.Application({\n width: window.innerWidth,",
"score": 0.8481127023696899
},
{
"filename": "src/index.ts",
"retrieved_chunk": " height: window.innerHeight,\n antialias: true,\n transparent: false,\n resolution: window.devicePixelRatio || 1,\n });\n app.renderer.view.style.position = \"absolute\";\n app.renderer.view.style.display = \"block\";\n app.renderer.plugins.interaction.interactionFrequency = 60;\n const game = new Game(app);\n clearTimeout(timeout);",
"score": 0.8430507779121399
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Font } from \"utils\";\nimport * as _ from \"underscore\";\nimport GameScreen from \"./GameScreen\";\nexport default class GameOverModal extends PIXI.Container {\n game: GameScreen;\n scoresTable: PIXI.Container;\n constructor(game: GameScreen) {\n super();",
"score": 0.8422057032585144
}
] |
typescript
|
Save.initialise();
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
|
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8369752764701843
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.827241063117981
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8034799695014954
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Action, Actions } from \"pixi-actions\";\nimport Character from \"../character/Character\";\nimport { Coords } from \"utils\";\nimport Wall from \"./Wall\";\nexport default class Grid extends PIXI.Container {\n dimension: number;\n edgeSize: number;\n constructor(dimension: number) {\n super();",
"score": 0.8028711080551147
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8028309941291809
}
] |
typescript
|
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
|
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8368005752563477
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8271395564079285
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8033121824264526
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Action, Actions } from \"pixi-actions\";\nimport Character from \"../character/Character\";\nimport { Coords } from \"utils\";\nimport Wall from \"./Wall\";\nexport default class Grid extends PIXI.Container {\n dimension: number;\n edgeSize: number;\n constructor(dimension: number) {\n super();",
"score": 0.8027368783950806
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8026461601257324
}
] |
typescript
|
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
|
dungeonGrid.addCharacter(c);
|
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.858292281627655
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8445855379104614
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8409228920936584
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " exitDir: Coords = null;\n constructor(gameScreen: GameScreen, dimension: number) {\n super(dimension);\n this.gameScreen = gameScreen;\n // Add cell backgrounds\n const background = PIXI.Sprite.from(PIXI.Texture.WHITE);\n background.tint = 0xd3c8a2;\n background.width = this.edgeSize;\n background.height = this.edgeSize;\n background.alpha = 1;",
"score": 0.8309124708175659
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8281542062759399
}
] |
typescript
|
dungeonGrid.addCharacter(c);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
|
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.836825966835022
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8270806074142456
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8032591342926025
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Action, Actions } from \"pixi-actions\";\nimport Character from \"../character/Character\";\nimport { Coords } from \"utils\";\nimport Wall from \"./Wall\";\nexport default class Grid extends PIXI.Container {\n dimension: number;\n edgeSize: number;\n constructor(dimension: number) {\n super();",
"score": 0.8027477264404297
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8027182221412659
}
] |
typescript
|
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.
|
drawWalls(dungeonGrid.walls);
|
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8599258065223694
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.cellSquares.push(col1);\n this.cellStairs.push(col2);\n }\n this.addChild(this.wallsHolder);\n this.addChild(this.charactersHolder);\n for (let i = 0; i < this.dimension; i++) {\n for (let j = 0; j < this.dimension; j++) {\n this.coords.push(new Coords(i, j));\n }\n }",
"score": 0.8493446707725525
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8463605642318726
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.8454642295837402
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8360284566879272
}
] |
typescript
|
drawWalls(dungeonGrid.walls);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
|
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8669441938400269
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8294175863265991
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.829086184501648
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8147879242897034
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.8098770380020142
}
] |
typescript
|
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
|
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8669441938400269
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8294175863265991
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.829086184501648
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8147879242897034
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.8098770380020142
}
] |
typescript
|
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid
|
: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8677161931991577
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8267889022827148
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8145900368690491
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " characters: Character[] = [];\n walls: Wall[] = [];\n edgeWalls: Wall[] = [];\n wallsHolder: PIXI.Container = new PIXI.Container();\n charactersHolder: PIXI.Container = new PIXI.Container();\n gameScreen: GameScreen;\n coords: Coords[] = [];\n cellSquares: PIXI.Sprite[][] = [];\n cellStairs: PIXI.Sprite[][] = [];\n exitCoords: Coords;",
"score": 0.8122481107711792
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.8099508285522461
}
] |
typescript
|
: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
|
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
|
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.836429238319397
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " next();\n })\n .load((_, resources) => {\n this.resources = resources;\n this.spritesheet = this.resources[\"spritesheet\"].spritesheet;\n this.postInit();\n });\n }\n gotoGameScreen() {\n const gameScreen = new GameScreen();",
"score": 0.8346238136291504
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": " this.game = game;\n // Leaderboard\n const titleLabel = new PIXI.BitmapText(\n \"Game Over\",\n Font.makeFontOptions(\"small\")\n );\n titleLabel.anchor.set(0.5, 0.5);\n titleLabel.position.x = Game.TARGET_WIDTH / 2;\n titleLabel.position.y = 20;\n this.addChild(titleLabel);",
"score": 0.8307870030403137
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport Game from \"Game\";\nimport { Font } from \"utils\";\nimport * as _ from \"underscore\";\nimport GameScreen from \"./GameScreen\";\nexport default class GameOverModal extends PIXI.Container {\n game: GameScreen;\n scoresTable: PIXI.Container;\n constructor(game: GameScreen) {\n super();",
"score": 0.8294442892074585
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;\n this.stage.addChild(this.innerBackgroundSprite);\n if (Save.hasGameState()) {\n this.gotoGameScreen();\n } else {\n this.gotoMenuScreen();\n }\n this.resize();",
"score": 0.8245798349380493
}
] |
typescript
|
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.
|
position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
|
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.8747549057006836
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n const coords = _.sample(possibles);\n this.exitCoords = coords;\n if (Game.EXIT_TYPE == \"door\") {\n const possibleDirs = [];\n if (coords.row == 0) possibleDirs.push(new Coords(0, -1));\n if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));\n if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));\n if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));\n if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);",
"score": 0.845096230506897
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " for (let i = 0; i < this.dimension; i++) {\n for (let j = 0; j < this.dimension; j++) {\n if (i == 2 && j == 2) continue;\n if (\n Game.EXIT_TYPE == \"door\" &&\n ![0, this.dimension - 1].includes(i) &&\n ![0, this.dimension - 1].includes(j)\n )\n continue;\n const c = new Coords(i, j);",
"score": 0.8421669006347656
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n this.updateExitCoords();\n }\n updateExitCoords() {\n if (Game.EXIT_TYPE == \"stairs\") {\n this.cellStairs.forEach((a, i) =>\n a.forEach(\n (stairs, j) =>\n (stairs.visible =\n this.exitCoords &&",
"score": 0.8319455981254578
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.8306547403335571
}
] |
typescript
|
position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen
|
.gameContainer.removeChild(gameScreen.dungeonGrid);
|
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8649152517318726
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8315128684043884
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8265789747238159
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8248098492622375
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.8216950297355652
}
] |
typescript
|
.gameContainer.removeChild(gameScreen.dungeonGrid);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
|
Actions.clear(this.playerCharacter);
|
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.8507423400878906
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8420337438583374
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n clearEnemies() {\n for (let i = this.characters.length - 1; i >= 0; i--) {\n const c = this.characters[i];\n if (!c.isPlayer) {\n Actions.fadeOutAndRemove(c, 0.2).play();\n this.characters.splice(i, 1);\n }\n }\n }",
"score": 0.8380528092384338
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8369492292404175
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.8352541923522949
}
] |
typescript
|
Actions.clear(this.playerCharacter);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
|
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
|
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8739485740661621
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8641610145568848
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8504767417907715
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8470535278320312
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8372492790222168
}
] |
typescript
|
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
|
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.
|
playerCharacter = pc;
|
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
|
src/save/Save.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.866858184337616
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.8424422740936279
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport Game from \"Game\";\nimport Screen from \"../Screen\";\nimport { Font } from \"utils\";\nimport Save from \"../../save/Save\";\nimport DungeonGrid from \"./grid/DungeonGrid\";\nimport { PlayerCharacter, EnemyCharacter } from \"./character\";\nimport GameOverModal from \"./GameOverModal\";\nimport * as _ from \"underscore\";",
"score": 0.8387861847877502
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.8380833864212036
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8303219079971313
}
] |
typescript
|
playerCharacter = pc;
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
|
Save.saveGameState(this);
|
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8518936634063721
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " dungeonGrid.updateExitCoords();\n return dungeonGrid;\n }\n // Game state\n private static serialiseGameState(gameScreen: GameScreen) {\n return {\n level: gameScreen.level,\n state: gameScreen.state,\n score: gameScreen.score,\n dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),",
"score": 0.8489919900894165
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);\n const chars = this.deserialiseCharacters(data.characters);\n for (const c of chars) {\n dungeonGrid.addCharacter(c);\n }\n dungeonGrid.walls = this.deserialiseWalls(data.walls);\n dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);\n dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);\n dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);\n dungeonGrid.drawWalls(dungeonGrid.walls);",
"score": 0.845309317111969
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;\n this.stage.addChild(this.innerBackgroundSprite);\n if (Save.hasGameState()) {\n this.gotoGameScreen();\n } else {\n this.gotoMenuScreen();\n }\n this.resize();",
"score": 0.8376457691192627
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.8361061215400696
}
] |
typescript
|
Save.saveGameState(this);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
|
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
|
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " w.alpha = 0;\n Actions.fadeIn(w, 0.2).play();\n this.wallsHolder.addChild(w);\n w.setCellSize(this.cellSize);\n // Place in the correct place\n this.setPositionTo(w, w.from, true);\n }\n }\n addCharacter(character: Character) {\n character.scale.set(0.2);",
"score": 0.8539863228797913
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Actions } from \"pixi-actions\";\nimport { Character, EnemyCharacter, PlayerCharacter } from \"../character\";\nimport GameScreen from \"../GameScreen\";\nimport Grid from \"./Grid\";\nimport Wall from \"./Wall\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nimport Game from \"Game\";\nexport default class DungeonGrid extends Grid {",
"score": 0.848408579826355
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);\n const chars = this.deserialiseCharacters(data.characters);\n for (const c of chars) {\n dungeonGrid.addCharacter(c);\n }\n dungeonGrid.walls = this.deserialiseWalls(data.walls);\n dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);\n dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);\n dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);\n dungeonGrid.drawWalls(dungeonGrid.walls);",
"score": 0.8417502641677856
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.cellSquares.push(col1);\n this.cellStairs.push(col2);\n }\n this.addChild(this.wallsHolder);\n this.addChild(this.charactersHolder);\n for (let i = 0; i < this.dimension; i++) {\n for (let j = 0; j < this.dimension; j++) {\n this.coords.push(new Coords(i, j));\n }\n }",
"score": 0.8304216861724854
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8300365209579468
}
] |
typescript
|
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
|
const enemyMoveResult = this.dungeonGrid.moveEnemies();
|
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return false;\n }\n moveEnemies() {\n let delay = 0;\n // 1. Dijkstra the grid, ignoring enemies\n // Pick the closest character\n const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const enemiesAndDistances = [];\n for (const char of this.characters) {\n if (char.isEnemy) {",
"score": 0.8561721444129944
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let atLeastOneMove = false;\n for (let tries = 0; tries < 5; tries++) {\n const tryAgainLater = [];\n for (const e of sortedEnemies) {\n const char = e.char;\n const dijks = this.dijkstra(\n this.gameScreen.playerCharacter.coords,\n true,\n char.coords\n );",
"score": 0.8345024585723877
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const dx = targetCol - char.coords.col;\n const dy = targetRow - char.coords.row;\n atLeastOneMove = true;\n delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);\n }\n if (tryAgainLater.length == 0) {\n break;\n } else {\n sortedEnemies = tryAgainLater;\n }",
"score": 0.8316696286201477
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.8285660147666931
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n clearEnemies() {\n for (let i = this.characters.length - 1; i >= 0; i--) {\n const c = this.characters[i];\n if (!c.isPlayer) {\n Actions.fadeOutAndRemove(c, 0.2).play();\n this.characters.splice(i, 1);\n }\n }\n }",
"score": 0.8251123428344727
}
] |
typescript
|
const enemyMoveResult = this.dungeonGrid.moveEnemies();
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
|
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
|
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Hitting a wall?\n if (this.doesWallSeparate(character.coords, dx, dy)) {\n Game.instance.playSound(\"bump\");\n const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Is there another character here?",
"score": 0.8850897550582886
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.8756308555603027
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " try {\n const targetCharacter = this.getCharacterAt(targetCoord);\n if (targetCharacter) {\n let delay = this.bumpAnimation(character, dx, dy);\n if (character.isPlayer && targetCharacter.isEnemy) {\n // Attack the character\n Game.instance.playSound(\"attack\");\n delay += this.damageEnemy(targetCharacter as EnemyCharacter);\n return { didMove: true, delay, wentThroughExit: false };\n } else if (character.isEnemy && targetCharacter.isPlayer) {",
"score": 0.8696330785751343
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8671866059303284
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n }\n return null;\n }\n bumpAnimation(character: Character, dx: number, dy: number) {\n const time = 0.1;\n Actions.sequence(\n this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),\n this.makeMoveTo(character, 0, 0, time / 2)\n ).play();",
"score": 0.8665711879730225
}
] |
typescript
|
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
|
character.scale.set(0.2);
|
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8495967984199524
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.845067024230957
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8376682996749878
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8198674917221069
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.8159986734390259
}
] |
typescript
|
character.scale.set(0.2);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
|
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
|
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
|
src/screens/game/GameScreen.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.8807839155197144
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8730007410049438
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.8654283285140991
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Animate to the new position\n this.makeMoveTo(character).play();\n return { didMove: true, delay: 0.05, wentThroughExit: false };\n }\n doesWallSeparate(start: Coords, dx: number, dy: number) {\n for (const w of this.walls) {\n if (w.blocks(start, dx, dy)) {\n return true;\n }\n }",
"score": 0.8599402904510498
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Hitting a wall?\n if (this.doesWallSeparate(character.coords, dx, dy)) {\n Game.instance.playSound(\"bump\");\n const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Is there another character here?",
"score": 0.8590575456619263
}
] |
typescript
|
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
|
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
|
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8428746461868286
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.828284502029419
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.8151649832725525
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " dungeonGrid.updateExitCoords();\n return dungeonGrid;\n }\n // Game state\n private static serialiseGameState(gameScreen: GameScreen) {\n return {\n level: gameScreen.level,\n state: gameScreen.state,\n score: gameScreen.score,\n dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),",
"score": 0.8102924227714539
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8098191618919373
}
] |
typescript
|
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions
|
.fadeOutAndRemove(c, 0.2).play();
|
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.8413729667663574
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8384048938751221
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8329254984855652
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.821042537689209
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const monsterLevel = Math.min(this.level, 20);\n const numEnemies =\n 2 +\n Math.min(5, Math.floor(monsterLevel / 5)) +\n Math.min(10, Math.max(0, monsterLevel - 40));\n this.spawnEnemy(numEnemies);\n Save.saveGameState(this);\n }\n spawnEnemy(n: number) {\n for (let i = 0; i < n; i++) {",
"score": 0.8154414892196655
}
] |
typescript
|
.fadeOutAndRemove(c, 0.2).play();
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
|
this.setPositionTo(character, character.coords);
|
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8529683351516724
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8463656902313232
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8159058094024658
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8157683610916138
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " );\n }\n // Characters\n private static serialiseCharacters(characters: Character[]) {\n return characters.map((c) => {\n return {\n type: c.type,\n coords: this.serialiseCoords(c.coords),\n hp: c.hp,\n };",
"score": 0.8127659559249878
}
] |
typescript
|
this.setPositionTo(character, character.coords);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie =
|
targetCharacter.damage(1);
|
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8999179601669312
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8596034049987793
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8518971800804138
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ).play();\n Actions.sequence(\n Actions.parallel(\n Actions.fadeOut(this.dungeonGrid, 0.2),\n Actions.moveTo(\n this.dungeonGrid,\n this.dungeonGrid.position.x - dx,\n this.dungeonGrid.position.y - dy,\n 0.5",
"score": 0.8352190852165222
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8275759220123291
}
] |
typescript
|
targetCharacter.damage(1);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
|
if (character.isPlayer && targetCharacter.isEnemy) {
|
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.864398717880249
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8383707404136658
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8377100229263306
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8318853378295898
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " if (dx == 0) return false;\n if (dx < 0 && this.from.equals(start)) {\n // Hitting a wall\n return true;\n }\n if (\n dx > 0 &&\n this.from.col == start.col + 1 &&\n this.from.row == start.row\n ) {",
"score": 0.8284803628921509
}
] |
typescript
|
if (character.isPlayer && targetCharacter.isEnemy) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.
|
setPositionTo(w, w.from, true);
|
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n from: this.serialiseCoords(w.from),\n to: this.serialiseCoords(w.to),\n };\n });\n }\n private static deserialiseWalls(walls: any): Wall[] {\n return walls.map(\n (w: any) =>\n new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))",
"score": 0.831992506980896
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " }\n setPositionTo(\n actor: PIXI.Container,\n coords: Coords,\n isWall: boolean = false\n ) {\n if (isWall) {\n if ((actor as Wall).isHorizontal) {\n actor.position.set(\n this.cellSize * coords.col + (this.cellSize - actor.width) / 2,",
"score": 0.8319894075393677
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8250507712364197
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": "import * as PIXI from \"pixi.js\";\nimport { Coords } from \"utils\";\nimport * as _ from \"underscore\";\nexport default class Wall extends PIXI.Container {\n static CONNECTION_PREFERRED_RATIO = 0.6;\n static PREDETERMINED_LAYOUTS: any = { shrine: [] };\n from: Coords;\n to: Coords;\n sprite: PIXI.Sprite;\n constructor(from: Coords, to: Coords) {",
"score": 0.8217289447784424
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.8184125423431396
}
] |
typescript
|
setPositionTo(w, w.from, true);
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
|
let walls: Wall[] = Wall.edges(this.dimension);
|
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " // Generate walls which go all around the edges\n const walls: Wall[] = [];\n for (let edge = 0; edge < 4; edge++) {\n for (let i = 0; i < dimension; i++) {\n const startCoords = new Coords(0, 0);\n const endCoords = new Coords(0, 0);\n if (edge == 0 || edge == 2) {\n // Top/bottom\n startCoords.col = i;\n endCoords.col = i + 1;",
"score": 0.8589528799057007
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " startCoords.row = edge == 0 ? 0 : dimension;\n endCoords.row = startCoords.row;\n } else {\n // Left/right\n startCoords.row = i;\n endCoords.row = i + 1;\n startCoords.col = edge == 1 ? 0 : dimension;\n endCoords.col = startCoords.col;\n }\n walls.push(new Wall(startCoords, endCoords));",
"score": 0.8551715612411499
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " } else {\n // If it's vertical, you can't go on either edge\n if (w[0].col == 0 || w[0].col == dimension - 1) continue;\n }\n // If another wall here, don't add\n for (const w2 of walls) {\n if (w2.from.equals(w[0]) && w2.to.equals(w[1])) {\n continue outer;\n }\n }",
"score": 0.8490115404129028
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " [prevWall.from.clone().add(0, 1), prevWall.to.clone().add(0, 1)],\n // 4 perpendicular\n [prevWall.from.clone(), prevWall.from.clone().add(1, 0)],\n [prevWall.from.clone().add(-1, 0), prevWall.from.clone()],\n [prevWall.to.clone(), prevWall.to.clone().add(1, 0)],\n [prevWall.to.clone().add(-1, 0), prevWall.to.clone()]\n );\n }\n // Remove any which are duplicated, or out of bounds\n const viableConnectingWalls: Coords[][] = [];",
"score": 0.8387600183486938
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " outer: for (const w of connectingWalls) {\n // If not in bounds, don't add to Q\n if (w[0].col < 0 || w[0].row < 0) continue;\n if (w[0].col >= dimension || w[0].row >= dimension) continue;\n if (w[1].col < 0 || w[1].row < 0) continue;\n if (w[1].col >= dimension || w[1].row >= dimension) continue;\n const isHorizontal = w[0].row == w[1].row;\n if (isHorizontal) {\n // If it's horizontal, you can't go on top or bottom\n if (w[0].row == 0 || w[0].row == dimension - 1) continue;",
"score": 0.8326747417449951
}
] |
typescript
|
let walls: Wall[] = Wall.edges(this.dimension);
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, NonNullable<E["errException"]>, X>;
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (isJsError(a)) {
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const
|
{ errCode, errMessage, errContext, errException } =
a as Partial<Err>;
|
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " expect(a.errMessage).toEqual(b.errMessage);\n expect(a.errCode).toEqual(b.errCode);\n expect(a.errContext).toEqual(b.errContext);\n expect(a.errException).toEqual(b.errException);\n}",
"score": 0.8606681823730469
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8582830429077148
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " assertResultEquals(err(e, \"super fail\", 999, { some: \"data\" }), {\n errMessage: \"super fail\",\n errCode: 999,\n errContext: { some: \"data\" },\n });\n });\n});\nfunction errIsErr(a: Err, b: Err): void {\n expect(a.ok).toEqual(a.ok);\n expect(a.err).toEqual(b.err);",
"score": 0.8544092178344727
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " err({\n errCode: 123,\n errContext: { some: \"data\" },\n errException: e,\n }),\n {\n errCode: 123,\n errMessage: \"error123: fail\",\n errContext: { some: \"data\" },\n errException: e,",
"score": 0.8440176248550415
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " const e = err(\"fail\", 555, { old: \"data\" });\n // no overrides\n assertResultEquals(err(e), {\n errMessage: \"fail\",\n errCode: 555,\n errContext: { old: \"data\" },\n });\n // just the message\n assertResultEquals(err(e, \"super fail\"), {\n errMessage: \"super fail\",",
"score": 0.8394888043403625
}
] |
typescript
|
{ errCode, errMessage, errContext, errException } =
a as Partial<Err>;
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
|
character.alpha = 0;
|
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8450830578804016
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8362103700637817
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8348938822746277
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8171138167381287
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.8091638684272766
}
] |
typescript
|
character.alpha = 0;
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
|
this.charactersHolder.removeChild(targetCharacter);
|
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.814703106880188
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8089315891265869
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.80007004737854
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.7984919548034668
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.7949498891830444
}
] |
typescript
|
this.charactersHolder.removeChild(targetCharacter);
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, NonNullable<E["errException"]>, X>;
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
|
if (isJsError(a)) {
|
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " expect(a.errMessage).toEqual(b.errMessage);\n expect(a.errCode).toEqual(b.errCode);\n expect(a.errContext).toEqual(b.errContext);\n expect(a.errException).toEqual(b.errException);\n}",
"score": 0.828336238861084
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8247162699699402
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8078339695930481
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.799884557723999
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " return err();\n }\n if (typeof value === \"object\") {\n if ((\"ok\" in value && value.ok) || (\"err\" in value && !value.err)) {\n const data = (value as Ok).data ?? null;\n return ok(data);\n } else if ((\"err\" in value && value.err) || (\"ok\" in value && !value.ok)) {\n const e = value as Err;\n const errCode = e.errCode ?? 0;\n const errMessage = e.errMessage || \"\";",
"score": 0.7991583943367004
}
] |
typescript
|
if (isJsError(a)) {
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, NonNullable<E["errException"]>, X>;
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (isJsError(a)) {
// err(Error, message?, code?, context?)
exception = a;
|
message = typeof b === "string" ? b : a.message || "";
|
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8537878394126892
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " expect(a.errMessage).toEqual(b.errMessage);\n expect(a.errCode).toEqual(b.errCode);\n expect(a.errContext).toEqual(b.errContext);\n expect(a.errException).toEqual(b.errException);\n}",
"score": 0.8370802402496338
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8206795454025269
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " assertResultEquals(err(e, \"super fail\", 999, { some: \"data\" }), {\n errMessage: \"super fail\",\n errCode: 999,\n errContext: { some: \"data\" },\n });\n });\n});\nfunction errIsErr(a: Err, b: Err): void {\n expect(a.ok).toEqual(a.ok);\n expect(a.err).toEqual(b.err);",
"score": 0.8205540776252747
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " return err();\n }\n if (typeof value === \"object\") {\n if ((\"ok\" in value && value.ok) || (\"err\" in value && !value.err)) {\n const data = (value as Ok).data ?? null;\n return ok(data);\n } else if ((\"err\" in value && value.err) || (\"ok\" in value && !value.ok)) {\n const e = value as Err;\n const errCode = e.errCode ?? 0;\n const errMessage = e.errMessage || \"\";",
"score": 0.8190253376960754
}
] |
typescript
|
message = typeof b === "string" ? b : a.message || "";
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C,
|
NonNullable<E["errException"]>, X>;
|
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (isJsError(a)) {
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8576360940933228
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8146546483039856
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n ).toEqual(\n err({\n errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,",
"score": 0.8012456893920898
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " err({\n errCode: 123,\n errContext: { some: \"data\" },\n errException: e,\n }),\n {\n errCode: 123,\n errMessage: \"error123: fail\",\n errContext: { some: \"data\" },\n errException: e,",
"score": 0.8007115125656128
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " const e = err(\"fail\", 555, { old: \"data\" });\n // no overrides\n assertResultEquals(err(e), {\n errMessage: \"fail\",\n errCode: 555,\n errContext: { old: \"data\" },\n });\n // just the message\n assertResultEquals(err(e, \"super fail\"), {\n errMessage: \"super fail\",",
"score": 0.7985807657241821
}
] |
typescript
|
NonNullable<E["errException"]>, X>;
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, NonNullable<E["errException"]>, X>;
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (
|
isJsError(a)) {
|
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.82061767578125
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " expect(a.errMessage).toEqual(b.errMessage);\n expect(a.errCode).toEqual(b.errCode);\n expect(a.errContext).toEqual(b.errContext);\n expect(a.errException).toEqual(b.errException);\n}",
"score": 0.8169951438903809
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8037002682685852
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.7987825870513916
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " return err();\n }\n if (typeof value === \"object\") {\n if ((\"ok\" in value && value.ok) || (\"err\" in value && !value.err)) {\n const data = (value as Ok).data ?? null;\n return ok(data);\n } else if ((\"err\" in value && value.err) || (\"ok\" in value && !value.ok)) {\n const e = value as Err;\n const errCode = e.errCode ?? 0;\n const errMessage = e.errMessage || \"\";",
"score": 0.7959173917770386
}
] |
typescript
|
isJsError(a)) {
|
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
|
if (player.damage(1)) {
|
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
|
src/screens/game/grid/DungeonGrid.ts
|
MaxBittker-broughlike-c8d94d5
|
[
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8529779314994812
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8511292934417725
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.841262698173523
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.83344966173172
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8332982063293457
}
] |
typescript
|
if (player.damage(1)) {
|
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, NonNullable<E["errException"]>, X>;
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (isJsError(a)) {
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
|
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
|
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
|
src/err.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8601858615875244
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " assertResultEquals(err(e, \"super fail\", 999, { some: \"data\" }), {\n errMessage: \"super fail\",\n errCode: 999,\n errContext: { some: \"data\" },\n });\n });\n});\nfunction errIsErr(a: Err, b: Err): void {\n expect(a.ok).toEqual(a.ok);\n expect(a.err).toEqual(b.err);",
"score": 0.8587429523468018
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " err({\n errCode: 123,\n errContext: { some: \"data\" },\n errException: e,\n }),\n {\n errCode: 123,\n errMessage: \"error123: fail\",\n errContext: { some: \"data\" },\n errException: e,",
"score": 0.8540109992027283
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " expect(a.errMessage).toEqual(b.errMessage);\n expect(a.errCode).toEqual(b.errCode);\n expect(a.errContext).toEqual(b.errContext);\n expect(a.errException).toEqual(b.errException);\n}",
"score": 0.8531387448310852
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " const e = err(\"fail\", 555, { old: \"data\" });\n // no overrides\n assertResultEquals(err(e), {\n errMessage: \"fail\",\n errCode: 555,\n errContext: { old: \"data\" },\n });\n // just the message\n assertResultEquals(err(e, \"super fail\"), {\n errMessage: \"super fail\",",
"score": 0.8441874980926514
}
] |
typescript
|
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
|
import type { Err, Ok, Result } from "./api";
import { err } from "./err";
import { ok } from "./ok";
import { isJsError } from "./shared";
export function toResult<
D extends unknown,
T extends { ok: true; data?: D } | { err: false; data?: D },
>(value: T): Ok<T>;
export function toResult<
C extends unknown,
T extends { ok: false; errCode?: C } | { err: true; errCode?: C },
>(value: T): Err<T["errCode"]>;
export function toResult<D extends false | "" | 0 | null | undefined>(
value: D,
): Err;
export function toResult<
D extends true | unknown[] | Record<string, unknown> | number | string,
>(value: D): Ok<D>;
export function toResult(value: unknown): Result {
if (value === undefined || value === null) {
return err();
}
if (typeof value === "object") {
if (("ok" in value && value.ok) || ("err" in value && !value.err)) {
const data = (value as Ok).data ?? null;
return ok(data);
} else if (("err" in value && value.err) || ("ok" in value && !value.ok)) {
const e = value as Err;
const errCode = e.errCode ?? 0;
const errMessage = e.errMessage || "";
const errContext = e.errContext ?? null;
const errException = isJsError(e.errException) ? e.errException : null;
return err({
errCode,
errMessage,
errContext,
errException,
});
}
// fallback for any {} object
return
|
value ? ok(value) : err();
|
}
switch (typeof value) {
case "boolean":
return value ? ok(value) : err();
case "number":
return value === 0 ? err() : ok(value);
case "string":
return value === "" ? err() : ok(value);
default:
return err();
}
}
|
src/toResult.ts
|
yearofmoo-okej-03a1277
|
[
{
"filename": "src/err.ts",
"retrieved_chunk": " exception = errException ?? null;\n code =\n typeof c === \"number\"\n ? c\n : typeof errCode === \"number\"\n ? errCode\n : 0;\n message = isValidString(b)\n ? b\n : isValidString(errMessage)",
"score": 0.8631791472434998
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " err({\n errCode: 123,\n errContext: { some: \"data\" },\n errException: e,\n }),\n {\n errCode: 123,\n errMessage: \"error123: fail\",\n errContext: { some: \"data\" },\n errException: e,",
"score": 0.862229585647583
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " expect(toResult({ err: true, errCode: \"FFF\" })).toEqual(\n err({ errCode: \"FFF\" }),\n );\n expect(toResult({ ok: false, errCode: \"FFF\" })).toEqual(\n err({ errCode: \"FFF\" }),\n );\n const ctx = { a: 1 };\n expect(toResult({ err: true, errContext: ctx })).toEqual(\n err({ errContext: ctx }),\n );",
"score": 0.8614704608917236
},
{
"filename": "src/from.ts",
"retrieved_chunk": " return ok(data);\n } catch (e) {\n return err(e);\n }\n}",
"score": 0.8588346242904663
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " });\n it(\"should convert a simple {ok:false} or {err:true} object to an Err result\", () => {\n expect(toResult({ ok: false })).toEqual(err());\n expect(toResult({ err: true })).toEqual(err());\n });\n it(\"should retain the errMessage, errCode, errContext and errException when accepting an err-like input value\", () => {\n expect(toResult({ ok: false, errMessage: \"noo\" })).toEqual(err(\"noo\"));\n expect(toResult({ err: true, errMessage: \"noo!\" })).toEqual(err(\"noo!\"));\n expect(toResult({ err: true, errCode: 999 })).toEqual(err(999));\n expect(toResult({ ok: false, errCode: 999 })).toEqual(err(999));",
"score": 0.8554734587669373
}
] |
typescript
|
value ? ok(value) : err();
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import ConversationContext from './conversation-context';
import { Session } from "../types/session";
/**
* In memory conversation context manager.
*/
class MemoryConversationContext extends ConversationContext {
private readonly conversationContexts: { [conversationId: string]: any };
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
super(settings);
this.conversationContexts = {};
}
/**
* Gets the conversation context from the session.
* @param {Object} session Chatbot session of the conversation.
* @returns {Promise<Object>} Promise to resolve the conversation context.
*/
public
|
getConversationContext(session: Session): Promise<Object> {
|
return new Promise((resolve, reject) => {
const conversationId = this.getConversationId(session);
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
if (!this.conversationContexts[conversationId]) {
this.conversationContexts[conversationId] = {};
}
return resolve(this.conversationContexts[conversationId]);
});
}
public setConversationContext(session: Session, context: any): Promise<void> {
return new Promise((resolve, reject) => {
const conversationId = this.getConversationId(session);
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
this.conversationContexts[conversationId] = context;
return resolve();
});
}
}
export default MemoryConversationContext;
|
src/recognizer/memory-conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8478477597236633
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8432906866073608
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " conversationContext?: MemoryConversationContext;\n }) {\n this.nlpManager =\n this.settings.nlpManager ||\n new NlpManager({\n container: this.settings.container,\n ner: { threshold: this.settings.nerThreshold || 1 },\n });\n this.threshold = this.settings.threshold || 0.7;\n this.conversationContext =",
"score": 0.8208250403404236
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * Given a session instance of a chatbot, return the conversation identifier.\n * @param {Object} session Session instance of a message of chatbot.\n * @returns {String} Identifier of the conversation.\n */\n public getConversationId(session: Session): string | undefined {\n if (session?.message?.address?.conversation) {\n return session.message.address.conversation.id;\n }\n if (session?._activity?.conversation) {\n return session._activity.conversation.id;",
"score": 0.8182166218757629
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8131043910980225
}
] |
typescript
|
getConversationContext(session: Session): Promise<Object> {
|
import fs from 'fs';
import { BuiltinMicrosoft } from '@nlpjs/builtin-microsoft';
import { BuiltinDuckling } from '@nlpjs/builtin-duckling';
import { containerBootstrap } from '@nlpjs/core-loader';
import Language from '@nlpjs/language';
import { LangAll } from '@nlpjs/lang-all';
import { Nlp } from '@nlpjs/nlp';
import { Evaluator, Template } from '@nlpjs/evaluator';
import { fs as requestfs } from '@nlpjs/request';
import { SentimentManager } from '../sentiment';
import NlpExcelReader from './nlp-excel-reader';
export interface NlpManagerSettings {
container?: any
languages?: string[]
nlu?: {
log?: boolean
}
ner?: {
useDuckling?: boolean
ducklingUrl?: string
locale?: string
threshold?: number
}
action?: {
[key: string]: (params: any, context: any, result: any) => Promise<void> | void
}
settings?: any
forceNER?: boolean
processTransformer?: (result: any) => any
}
class NlpManager {
private readonly settings: NlpManagerSettings;
private container: any;
private nlp: any;
private sentimentManager: SentimentManager;
constructor(settings: NlpManagerSettings) {
this.settings = settings;
if (!this.settings.container) {
this.settings.container = containerBootstrap();
}
this.container = this.settings.container;
this.container.registerConfiguration('ner', {
entityPreffix: '%',
entitySuffix: '%',
});
this.container.register('fs', requestfs);
this.container.register('Language', Language, false);
this.container.use(LangAll);
this.container.use(Evaluator);
this.container.use(Template);
this.nlp = new Nlp(this.settings);
this.sentimentManager = new SentimentManager();
if (this.settings.ner) {
if (this.settings.ner.ducklingUrl || this.settings.ner.useDuckling) {
const builtin = new BuiltinDuckling(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
} else {
const builtin = new BuiltinMicrosoft(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
}
} else {
const builtin = new BuiltinMicrosoft(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
}
}
public addDocument(locale: string, utterance: string, intent: string) {
return this.nlp.addDocument(locale, utterance, intent);
}
public removeDocument(locale: string, utterance: string, intent: string) {
return this.nlp.removeDocument(locale, utterance, intent);
}
public addLanguage(locale: string) {
return this.nlp.addLanguage(locale);
}
public removeLanguage(locale: string) {
return this.nlp.removeLanguage(locale);
}
public assignDomain(locale: string, intent: string, domain: string) {
return this.nlp.assignDomain(locale, intent, domain);
}
public getIntentDomain(locale: string, intent: string): string {
return this.nlp.getIntentDomain(locale, intent);
}
public getDomains(): string[] {
return this.nlp.getDomains();
}
public guessLanguage(text: string): string {
return this.nlp.guessLanguage(text);
}
public addAction(
intent: string,
action: string,
parameters: string[],
fn?: (params: any, context: any, result: any) => Promise<void> | void
) {
if (!fn) {
fn = this.settings.action ? this.settings.action[action] : undefined;
}
return this.nlp.addAction(intent, action, parameters, fn);
}
getActions(intent: string): string[] {
return this.nlp.getActions(intent);
}
removeAction(intent: string, action: string, parameters?: string[]): boolean {
return this.nlp.removeAction(intent, action, parameters);
}
removeActions(intent: string): boolean {
return this.nlp.removeActions(intent);
}
addAnswer(locale: string, intent: string, answer: string, opts?: any): string {
return this.nlp.addAnswer(locale, intent, answer, opts);
}
removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {
return this.nlp.removeAnswer(locale, intent, answer, opts);
}
findAllAnswers(locale: string, intent: string): string[] {
return this.nlp.findAllAnswers(locale, intent);
}
async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {
const sentiment = await this.nlp.getSentiment(locale, utterance);
return this.sentimentManager.translate(sentiment.sentiment);
}
addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {
return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);
}
removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {
return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);
}
addRegexEntity(entityName: string, languages: string[], regex: string): void {
return this.nlp.addNerRegexRule(languages, entityName, regex);
}
addBetweenCondition(locale: string, name: string, left: string, right: string, opts?: any): void {
return this.nlp.addNerBetweenCondition(locale, name, left, right, opts);
}
addPositionCondition(locale: string, name: string, position: string, words: string[], opts?: any): void {
return this.nlp.addNerPositionCondition(locale, name, position, words, opts);
}
addAfterCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterCondition(locale, name, words, opts);
}
addAfterFirstCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterFirstCondition(locale, name, words, opts);
}
addAfterLastCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterLastCondition(locale, name, words, opts);
}
addBeforeCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeCondition(locale, name, words, opts);
}
addBeforeFirstCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeFirstCondition(locale, name, words, opts);
}
addBeforeLastCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeLastCondition(locale, name, words, opts);
}
describeLanguage(locale: string, name: string): void {
return this.nlp.describeLanguage(locale, name);
}
beginEdit(): void {
}
async train(): Promise<void> {
return this.nlp.train();
}
classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {
return this.nlp.classify(locale, utterance, settings);
}
async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {
const result = await this.nlp.process(locale, utterance, context, settings);
if (this.settings.processTransformer) {
return this.settings.processTransformer(result);
}
return result;
}
extractEntities(locale: string, utterance: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {
return this.nlp.extractEntities(locale, utterance, context, settings);
}
toObj(): any {
return this.nlp.toJSON();
}
fromObj(obj: any): any {
return this.nlp.fromJSON(obj);
}
/**
* Export NLP manager information as a string.
* @param {Boolean} minified If true, the returned JSON will have no spacing or indentation.
* @returns {String} NLP manager information as a JSON string.
*/
export(minified = false): string {
const clone = this.toObj();
return minified ? JSON.stringify(clone) : JSON.stringify(clone, null, 2);
}
/**
* Load NLP manager information from a string.
* @param {String|Object} data JSON string or object to load NLP manager information from.
*/
import(data: string | Record<string, unknown>): void {
const clone = typeof data === 'string' ? JSON.parse(data) : data;
this.fromObj(clone);
}
/**
* Save the NLP manager information into a file.
* @param {String} srcFileName Filename for saving the NLP manager.
* @param minified
*/
save(srcFileName?: string, minified = false): void {
const fileName = srcFileName || 'model.nlp';
fs.writeFileSync(fileName, this.export(minified), 'utf8');
}
/**
* Load the NLP manager information from a file.
* @param srcFileName
*/
load(srcFileName?: string): void {
const fileName = srcFileName || 'model.nlp';
const data = fs.readFileSync(fileName, 'utf8');
this.import(data);
}
/**
* Load the NLP manager information from an Excel file.
* @param fileName
*/
loadExcel(fileName = 'model.xls'): void {
const reader =
|
new NlpExcelReader(this);
|
reader.load(fileName);
}
async testCorpus(corpus: any): Promise<any> {
const { data } = corpus;
const result = {
total: 0,
good: 0,
bad: 0,
};
const promises = [];
const intents = [];
for (let i = 0; i < data.length; i += 1) {
const intentData = data[i];
const { tests } = intentData;
for (let j = 0; j < tests.length; j += 1) {
promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));
intents.push(intentData.intent);
}
}
result.total += promises.length;
const results = await Promise.all(promises);
for (let i = 0; i < results.length; i += 1) {
const current = results[i];
if (current.intent === intents[i]) {
result.good += 1;
} else {
result.bad += 1;
}
}
return result
}
addCorpora(corpora: any): void {
this.nlp.addCorpora(corpora);
}
addCorpus(corpus: any): void {
this.nlp.addCorpus(corpus);
}
async trainAndEvaluate(fileName: string | object): Promise<any> {
let corpus = fileName;
if (typeof fileName === 'string') {
const nlpfs = this.container.get('fs');
const fileData = await nlpfs.readFile(fileName);
if (!fileData) {
throw new Error(`Corpus not found "${fileName}"`);
}
corpus = typeof fileData === 'string' ? JSON.parse(fileData) : fileData;
}
this.nlp.addCorpus(corpus);
await this.train();
return this.testCorpus(corpus);
}
}
export default NlpManager;
|
src/nlp/nlp-manager.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-excel-reader.ts",
"retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {",
"score": 0.9008544683456421
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.nlpManager.save(filename);\n }\n /**\n * Loads the NLP manager from an excel.\n * @param {String} filename Name of the file.\n */\n public async loadExcel(filename: string): Promise<void> {\n this.nlpManager.loadExcel(filename);\n await this.train();\n this.save(filename);",
"score": 0.8932675719261169
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " * @param {String} filename Name of the file.\n */\n public load(filename: string): void {\n this.nlpManager.load(filename);\n }\n /**\n * Saves the model into a file.\n * @param {String} filename Name of the file.\n */\n public save(filename: string): void {",
"score": 0.8427150249481201
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8345845937728882
},
{
"filename": "src/nlp/index.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport NlpUtil from './nlp-util';\nimport NlpManager from './nlp-manager';\nimport NlpExcelReader from './nlp-excel-reader';\nexport {\n NlpUtil,\n NlpManager,\n NlpExcelReader\n}",
"score": 0.8138741850852966
}
] |
typescript
|
new NlpExcelReader(this);
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { NlpManager } from '../nlp';
import MemoryConversationContext from './memory-conversation-context';
/**
* Microsoft Bot Framework compatible recognizer for nlp.js.
*/
class Recognizer {
private readonly nlpManager: NlpManager;
private readonly threshold: number;
private readonly conversationContext: MemoryConversationContext;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(private readonly settings: {
|
nlpManager?: NlpManager;
|
container?: any;
nerThreshold?: number;
threshold?: number;
conversationContext?: MemoryConversationContext;
}) {
this.nlpManager =
this.settings.nlpManager ||
new NlpManager({
container: this.settings.container,
ner: { threshold: this.settings.nerThreshold || 1 },
});
this.threshold = this.settings.threshold || 0.7;
this.conversationContext =
this.settings.conversationContext || new MemoryConversationContext({});
}
/**
* Train the NLP manager.
*/
public async train(): Promise<void> {
await this.nlpManager.train();
}
/**
* Loads the model from a file.
* @param {String} filename Name of the file.
*/
public load(filename: string): void {
this.nlpManager.load(filename);
}
/**
* Saves the model into a file.
* @param {String} filename Name of the file.
*/
public save(filename: string): void {
this.nlpManager.save(filename);
}
/**
* Loads the NLP manager from an excel.
* @param {String} filename Name of the file.
*/
public async loadExcel(filename: string): Promise<void> {
this.nlpManager.loadExcel(filename);
await this.train();
this.save(filename);
}
/**
* Process an utterance using the NLP manager. This is done using a given context
* as the context object.
* @param {Object} srcContext Source context
* @param {String} locale Locale of the utterance.
* @param {String} utterance Locale of the utterance.
*/
public async process(
srcContext: Record<string, unknown>,
locale?: string,
utterance?: string
): Promise<string> {
const context = srcContext || {};
const response = await (locale
? this.nlpManager.process(locale, utterance, context)
: this.nlpManager.process(utterance, undefined, context));
if (response.score < this.threshold || response.intent === 'None') {
response.answer = undefined;
return response;
}
for (let i = 0; i < response.entities.length; i += 1) {
const entity = response.entities[i];
context[entity.entity] = entity.option;
}
if (response.slotFill) {
context.slotFill = response.slotFill;
} else {
delete context.slotFill;
}
return response;
}
/**
* Given an utterance and the locale, returns the recognition of the utterance.
* @param {String} utterance Utterance to be recognized.
* @param {String} model Model of the utterance.
* @param {Function} cb Callback Function.
*/
public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {
const response = await this.process(
model,
model ? model.locale : undefined,
utterance
);
return cb(null, response);
}
}
export default Recognizer;
|
src/recognizer/recognizer.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": "class NlpManager {\n private readonly settings: NlpManagerSettings;\n private container: any;\n private nlp: any;\n private sentimentManager: SentimentManager;\n constructor(settings: NlpManagerSettings) {\n this.settings = settings;\n if (!this.settings.container) {\n this.settings.container = containerBootstrap();\n }",
"score": 0.8713473081588745
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.865646481513977
},
{
"filename": "src/types/@nlpjs/nlu.d.ts",
"retrieved_chunk": " stemming?: boolean;\n useRegExpTokenize?: boolean;\n useLemma?: boolean;\n minScore?: number;\n ner?: any;\n skipStopWords?: boolean;\n pipeline?: any;\n }\n export class NluNeural {\n constructor(settings?: NluNeuralSettings);",
"score": 0.8480845093727112
},
{
"filename": "src/index.ts",
"retrieved_chunk": " Recognizer,\n ConversationContext,\n MemoryConversationContext,\n} from './recognizer'\nimport { BrainNLU } from './nlu'\nexport {\n Language,\n NlpUtil,\n NlpManager,\n NlpExcelReader,",
"score": 0.8368775248527527
},
{
"filename": "src/types/@nlpjs/nlu.d.ts",
"retrieved_chunk": " settings: NluNeuralSettings;\n train(corpus: any[], settings?: NluNeuralSettings): Promise<void>;\n process(utterance: string, context?: any): Promise<{\n classifications: Array<{\n intent: string;\n score: number;\n }>;\n }>;\n }\n export class NluNeuralManager {",
"score": 0.8341802358627319
}
] |
typescript
|
nlpManager?: NlpManager;
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { NlpManager } from '../nlp';
import MemoryConversationContext from './memory-conversation-context';
/**
* Microsoft Bot Framework compatible recognizer for nlp.js.
*/
class Recognizer {
private readonly nlpManager: NlpManager;
private readonly threshold: number;
private readonly conversationContext: MemoryConversationContext;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(private readonly settings: {
nlpManager?: NlpManager;
container?: any;
nerThreshold?: number;
threshold?: number;
|
conversationContext?: MemoryConversationContext;
|
}) {
this.nlpManager =
this.settings.nlpManager ||
new NlpManager({
container: this.settings.container,
ner: { threshold: this.settings.nerThreshold || 1 },
});
this.threshold = this.settings.threshold || 0.7;
this.conversationContext =
this.settings.conversationContext || new MemoryConversationContext({});
}
/**
* Train the NLP manager.
*/
public async train(): Promise<void> {
await this.nlpManager.train();
}
/**
* Loads the model from a file.
* @param {String} filename Name of the file.
*/
public load(filename: string): void {
this.nlpManager.load(filename);
}
/**
* Saves the model into a file.
* @param {String} filename Name of the file.
*/
public save(filename: string): void {
this.nlpManager.save(filename);
}
/**
* Loads the NLP manager from an excel.
* @param {String} filename Name of the file.
*/
public async loadExcel(filename: string): Promise<void> {
this.nlpManager.loadExcel(filename);
await this.train();
this.save(filename);
}
/**
* Process an utterance using the NLP manager. This is done using a given context
* as the context object.
* @param {Object} srcContext Source context
* @param {String} locale Locale of the utterance.
* @param {String} utterance Locale of the utterance.
*/
public async process(
srcContext: Record<string, unknown>,
locale?: string,
utterance?: string
): Promise<string> {
const context = srcContext || {};
const response = await (locale
? this.nlpManager.process(locale, utterance, context)
: this.nlpManager.process(utterance, undefined, context));
if (response.score < this.threshold || response.intent === 'None') {
response.answer = undefined;
return response;
}
for (let i = 0; i < response.entities.length; i += 1) {
const entity = response.entities[i];
context[entity.entity] = entity.option;
}
if (response.slotFill) {
context.slotFill = response.slotFill;
} else {
delete context.slotFill;
}
return response;
}
/**
* Given an utterance and the locale, returns the recognition of the utterance.
* @param {String} utterance Utterance to be recognized.
* @param {String} model Model of the utterance.
* @param {Function} cb Callback Function.
*/
public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {
const response = await this.process(
model,
model ? model.locale : undefined,
utterance
);
return cb(null, response);
}
}
export default Recognizer;
|
src/recognizer/recognizer.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": "class NlpManager {\n private readonly settings: NlpManagerSettings;\n private container: any;\n private nlp: any;\n private sentimentManager: SentimentManager;\n constructor(settings: NlpManagerSettings) {\n this.settings = settings;\n if (!this.settings.container) {\n this.settings.container = containerBootstrap();\n }",
"score": 0.8886381983757019
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8787291646003723
},
{
"filename": "src/types/@nlpjs/nlu.d.ts",
"retrieved_chunk": " stemming?: boolean;\n useRegExpTokenize?: boolean;\n useLemma?: boolean;\n minScore?: number;\n ner?: any;\n skipStopWords?: boolean;\n pipeline?: any;\n }\n export class NluNeural {\n constructor(settings?: NluNeuralSettings);",
"score": 0.8741130828857422
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " constructor(settings: any = {}) {\n this.settings = settings;\n if (!this.settings.container) {\n this.settings.container = containerBootstrap();\n }\n this.container = this.settings.container;\n this.container.use(LangAll);\n if (!this.settings.l) {\n this.nlu = new NluNeural({\n locale: this.settings.locale || this.settings.language || 'en',",
"score": 0.8688123822212219
},
{
"filename": "src/types/@nlpjs/nlp.d.ts",
"retrieved_chunk": "declare module '@nlpjs/nlp' {\n export class Nlp {\n constructor(settings: any)\n }\n}",
"score": 0.8459309339523315
}
] |
typescript
|
conversationContext?: MemoryConversationContext;
|
import { XDoc } from '@nlpjs/xtables';
import NlpManager from './nlp-manager';
class NlpExcelReader {
private manager: NlpManager;
private xdoc: XDoc;
constructor(manager: NlpManager) {
this.manager = manager;
this.xdoc = new XDoc();
}
load(filename: string): void {
this.xdoc.read(filename);
this.loadSettings();
this.loadLanguages();
this.loadNamedEntities();
this.loadRegexEntities();
this.loadIntents();
this.loadResponses();
}
loadSettings(): void {}
loadLanguages(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Languages').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addLanguage(row.iso2);
});
}
loadNamedEntities(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Named Entities').data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addNamedEntityText(row.entity, row.option, languages, [row.text]);
});
}
loadRegexEntities(): void {
const table = this.xdoc.getTable('Regex Entities');
if (table) {
const rows: Record<string, string>[] = table.data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager
|
.addRegexEntity(row.entity, languages, row.regex);
|
});
}
}
loadIntents(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Intents').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addDocument(row.language, row.utterance, row.intent);
});
}
loadResponses(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Responses').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addAnswer(row.language, row.intent, row.response, row.condition);
// this.manager.addAnswer(row.language, row.intent, row.response, row.condition, row.url);
});
}
}
export default NlpExcelReader;
|
src/nlp/nlp-excel-reader.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/types/@nlpjs/nlu.d.ts",
"retrieved_chunk": " entities?: {\n [locale: string]: {\n [name: string]: {\n type: string;\n values: { [value: string]: any };\n };\n };\n };\n regex?: { [name: string]: { [locale: string]: string } };\n stems?: { [locale: string]: { [value: string]: string } };",
"score": 0.813399612903595
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.sentimentManager.translate(sentiment.sentiment);\n }\n addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n addRegexEntity(entityName: string, languages: string[], regex: string): void {\n return this.nlp.addNerRegexRule(languages, entityName, regex);",
"score": 0.8089224100112915
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.nlp.addNerBeforeFirstCondition(locale, name, words, opts);\n }\n addBeforeLastCondition(locale: string, name: string, words: string[], opts?: any): void {\n return this.nlp.addNerBeforeLastCondition(locale, name, words, opts);\n }\n describeLanguage(locale: string, name: string): void {\n return this.nlp.describeLanguage(locale, name);\n }\n beginEdit(): void {\n }",
"score": 0.7904579043388367
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " addAfterFirstCondition(locale: string, name: string, words: string[], opts?: any): void {\n return this.nlp.addNerAfterFirstCondition(locale, name, words, opts);\n }\n addAfterLastCondition(locale: string, name: string, words: string[], opts?: any): void {\n return this.nlp.addNerAfterLastCondition(locale, name, words, opts);\n }\n addBeforeCondition(locale: string, name: string, words: string[], opts?: any): void {\n return this.nlp.addNerBeforeCondition(locale, name, words, opts);\n }\n addBeforeFirstCondition(locale: string, name: string, words: string[], opts?: any): void {",
"score": 0.7813659310340881
},
{
"filename": "src/types/@nlpjs/language.d.ts",
"retrieved_chunk": " Devanagari: RegExp;\n jpn: RegExp;\n kor: RegExp;\n tel: RegExp;\n tam: RegExp;\n guj: RegExp;\n kan: RegExp;\n mal: RegExp;\n Myanmar: RegExp;\n ori: RegExp;",
"score": 0.7786576747894287
}
] |
typescript
|
.addRegexEntity(row.entity, languages, row.regex);
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
public getConversationId(session: Session): string | undefined {
|
if (session?.message?.address?.conversation) {
|
return session.message.address.conversation.id;
}
if (session?._activity?.conversation) {
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
|
src/recognizer/conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.8706785440444946
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * @returns {Promise<Object>} Promise to resolve the conversation context.\n */\n public getConversationContext(session: Session): Promise<Object> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }\n if (!this.conversationContexts[conversationId]) {\n this.conversationContexts[conversationId] = {};",
"score": 0.8302722573280334
},
{
"filename": "src/types/session.d.ts",
"retrieved_chunk": "export type Session = {\n message?: {\n address?: {\n conversation?: {\n id: string;\n };\n };\n };\n _activity?: {\n conversation?: {",
"score": 0.8295937776565552
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " }\n return resolve(this.conversationContexts[conversationId]);\n });\n }\n public setConversationContext(session: Session, context: any): Promise<void> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }",
"score": 0.824510931968689
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " conversationContext?: MemoryConversationContext;\n }) {\n this.nlpManager =\n this.settings.nlpManager ||\n new NlpManager({\n container: this.settings.container,\n ner: { threshold: this.settings.nerThreshold || 1 },\n });\n this.threshold = this.settings.threshold || 0.7;\n this.conversationContext =",
"score": 0.8046164512634277
}
] |
typescript
|
if (session?.message?.address?.conversation) {
|
import { XDoc } from '@nlpjs/xtables';
import NlpManager from './nlp-manager';
class NlpExcelReader {
private manager: NlpManager;
private xdoc: XDoc;
constructor(manager: NlpManager) {
this.manager = manager;
this.xdoc = new XDoc();
}
load(filename: string): void {
this.xdoc.read(filename);
this.loadSettings();
this.loadLanguages();
this.loadNamedEntities();
this.loadRegexEntities();
this.loadIntents();
this.loadResponses();
}
loadSettings(): void {}
loadLanguages(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Languages').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addLanguage(row.iso2);
});
}
loadNamedEntities(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Named Entities').data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addNamedEntityText(row.entity, row.option, languages, [row.text]);
});
}
loadRegexEntities(): void {
const table = this.xdoc.getTable('Regex Entities');
if (table) {
const rows: Record<string, string>[] = table.data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addRegexEntity(row.entity, languages, row.regex);
});
}
}
loadIntents(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Intents').data;
rows.forEach((row: Record<string, string>) => {
this
|
.manager.addDocument(row.language, row.utterance, row.intent);
|
});
}
loadResponses(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Responses').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addAnswer(row.language, row.intent, row.response, row.condition);
// this.manager.addAnswer(row.language, row.intent, row.response, row.condition, row.url);
});
}
}
export default NlpExcelReader;
|
src/nlp/nlp-excel-reader.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " } else {\n const builtin = new BuiltinMicrosoft(this.settings.ner);\n this.container.register('extract-builtin-??', builtin, true);\n }\n }\n public addDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.addDocument(locale, utterance, intent);\n }\n public removeDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.removeDocument(locale, utterance, intent);",
"score": 0.8149811029434204
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " bad: 0,\n };\n const promises = [];\n const intents = [];\n for (let i = 0; i < data.length; i += 1) {\n const intentData = data[i];\n const { tests } = intentData;\n for (let j = 0; j < tests.length; j += 1) {\n promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));\n intents.push(intentData.intent);",
"score": 0.8020705580711365
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n public addLanguage(locale: string) {\n return this.nlp.addLanguage(locale);\n }\n public removeLanguage(locale: string) {\n return this.nlp.removeLanguage(locale);\n }\n public assignDomain(locale: string, intent: string, domain: string) {\n return this.nlp.assignDomain(locale, intent, domain);\n }",
"score": 0.7990493774414062
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " });\n }\n this.corpus = [];\n }\n add(utterance: string, intent: string) {\n this.corpus.push({ utterance, intent });\n }\n train() {\n return this.nlu?.train(this.corpus, this.settings);\n }",
"score": 0.7958741784095764
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.sentimentManager.translate(sentiment.sentiment);\n }\n addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n addRegexEntity(entityName: string, languages: string[], regex: string): void {\n return this.nlp.addNerRegexRule(languages, entityName, regex);",
"score": 0.795131266117096
}
] |
typescript
|
.manager.addDocument(row.language, row.utterance, row.intent);
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import ConversationContext from './conversation-context';
import { Session } from "../types/session";
/**
* In memory conversation context manager.
*/
class MemoryConversationContext extends ConversationContext {
private readonly conversationContexts: { [conversationId: string]: any };
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
super(settings);
this.conversationContexts = {};
}
/**
* Gets the conversation context from the session.
* @param {Object} session Chatbot session of the conversation.
* @returns {Promise<Object>} Promise to resolve the conversation context.
*/
public getConversationContext(session
|
: Session): Promise<Object> {
|
return new Promise((resolve, reject) => {
const conversationId = this.getConversationId(session);
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
if (!this.conversationContexts[conversationId]) {
this.conversationContexts[conversationId] = {};
}
return resolve(this.conversationContexts[conversationId]);
});
}
public setConversationContext(session: Session, context: any): Promise<void> {
return new Promise((resolve, reject) => {
const conversationId = this.getConversationId(session);
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
this.conversationContexts[conversationId] = context;
return resolve();
});
}
}
export default MemoryConversationContext;
|
src/recognizer/memory-conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8465531468391418
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8430279493331909
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * Given a session instance of a chatbot, return the conversation identifier.\n * @param {Object} session Session instance of a message of chatbot.\n * @returns {String} Identifier of the conversation.\n */\n public getConversationId(session: Session): string | undefined {\n if (session?.message?.address?.conversation) {\n return session.message.address.conversation.id;\n }\n if (session?._activity?.conversation) {\n return session._activity.conversation.id;",
"score": 0.8202850818634033
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " conversationContext?: MemoryConversationContext;\n }) {\n this.nlpManager =\n this.settings.nlpManager ||\n new NlpManager({\n container: this.settings.container,\n ner: { threshold: this.settings.nerThreshold || 1 },\n });\n this.threshold = this.settings.threshold || 0.7;\n this.conversationContext =",
"score": 0.8181673288345337
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8102142810821533
}
] |
typescript
|
: Session): Promise<Object> {
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
public getConversationId(session: Session): string | undefined {
if (session?.message?.address?.conversation) {
return session.message.address.conversation.id;
}
|
if (session?._activity?.conversation) {
|
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
|
src/recognizer/conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/types/session.d.ts",
"retrieved_chunk": "export type Session = {\n message?: {\n address?: {\n conversation?: {\n id: string;\n };\n };\n };\n _activity?: {\n conversation?: {",
"score": 0.8413987159729004
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * @returns {Promise<Object>} Promise to resolve the conversation context.\n */\n public getConversationContext(session: Session): Promise<Object> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }\n if (!this.conversationContexts[conversationId]) {\n this.conversationContexts[conversationId] = {};",
"score": 0.8343650102615356
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " }\n return resolve(this.conversationContexts[conversationId]);\n });\n }\n public setConversationContext(session: Session, context: any): Promise<void> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }",
"score": 0.8134945034980774
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.7941911816596985
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport ConversationContext from './conversation-context';\nimport { Session } from \"../types/session\";\n/**\n * In memory conversation context manager.\n */\nclass MemoryConversationContext extends ConversationContext {\n private readonly conversationContexts: { [conversationId: string]: any };\n /**",
"score": 0.7787004113197327
}
] |
typescript
|
if (session?._activity?.conversation) {
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
|
public getConversationId(session: Session): string | undefined {
|
if (session?.message?.address?.conversation) {
return session.message.address.conversation.id;
}
if (session?._activity?.conversation) {
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
|
src/recognizer/conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.8835422992706299
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * @returns {Promise<Object>} Promise to resolve the conversation context.\n */\n public getConversationContext(session: Session): Promise<Object> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }\n if (!this.conversationContexts[conversationId]) {\n this.conversationContexts[conversationId] = {};",
"score": 0.8287742137908936
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " }\n return resolve(this.conversationContexts[conversationId]);\n });\n }\n public setConversationContext(session: Session, context: any): Promise<void> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }",
"score": 0.8261477947235107
},
{
"filename": "src/types/session.d.ts",
"retrieved_chunk": "export type Session = {\n message?: {\n address?: {\n conversation?: {\n id: string;\n };\n };\n };\n _activity?: {\n conversation?: {",
"score": 0.8130133748054504
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8070433139801025
}
] |
typescript
|
public getConversationId(session: Session): string | undefined {
|
import fs from 'fs';
import { BuiltinMicrosoft } from '@nlpjs/builtin-microsoft';
import { BuiltinDuckling } from '@nlpjs/builtin-duckling';
import { containerBootstrap } from '@nlpjs/core-loader';
import Language from '@nlpjs/language';
import { LangAll } from '@nlpjs/lang-all';
import { Nlp } from '@nlpjs/nlp';
import { Evaluator, Template } from '@nlpjs/evaluator';
import { fs as requestfs } from '@nlpjs/request';
import { SentimentManager } from '../sentiment';
import NlpExcelReader from './nlp-excel-reader';
export interface NlpManagerSettings {
container?: any
languages?: string[]
nlu?: {
log?: boolean
}
ner?: {
useDuckling?: boolean
ducklingUrl?: string
locale?: string
threshold?: number
}
action?: {
[key: string]: (params: any, context: any, result: any) => Promise<void> | void
}
settings?: any
forceNER?: boolean
processTransformer?: (result: any) => any
}
class NlpManager {
private readonly settings: NlpManagerSettings;
private container: any;
private nlp: any;
private sentimentManager: SentimentManager;
constructor(settings: NlpManagerSettings) {
this.settings = settings;
if (!this.settings.container) {
this.settings.container = containerBootstrap();
}
this.container = this.settings.container;
this.container.registerConfiguration('ner', {
entityPreffix: '%',
entitySuffix: '%',
});
this.container.register('fs', requestfs);
this.container.register('Language', Language, false);
this.container.use(LangAll);
this.container.use(Evaluator);
this.container.use(Template);
this.nlp = new Nlp(this.settings);
this.sentimentManager = new SentimentManager();
if (this.settings.ner) {
if (this.settings.ner.ducklingUrl || this.settings.ner.useDuckling) {
const builtin = new BuiltinDuckling(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
} else {
const builtin = new BuiltinMicrosoft(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
}
} else {
const builtin = new BuiltinMicrosoft(this.settings.ner);
this.container.register('extract-builtin-??', builtin, true);
}
}
public addDocument(locale: string, utterance: string, intent: string) {
return this.nlp.addDocument(locale, utterance, intent);
}
public removeDocument(locale: string, utterance: string, intent: string) {
return this.nlp.removeDocument(locale, utterance, intent);
}
public addLanguage(locale: string) {
return this.nlp.addLanguage(locale);
}
public removeLanguage(locale: string) {
return this.nlp.removeLanguage(locale);
}
public assignDomain(locale: string, intent: string, domain: string) {
return this.nlp.assignDomain(locale, intent, domain);
}
public getIntentDomain(locale: string, intent: string): string {
return this.nlp.getIntentDomain(locale, intent);
}
public getDomains(): string[] {
return this.nlp.getDomains();
}
public guessLanguage(text: string): string {
return this.nlp.guessLanguage(text);
}
public addAction(
intent: string,
action: string,
parameters: string[],
fn?: (params: any, context: any, result: any) => Promise<void> | void
) {
if (!fn) {
fn = this.settings.action ? this.settings.action[action] : undefined;
}
return this.nlp.addAction(intent, action, parameters, fn);
}
getActions(intent: string): string[] {
return this.nlp.getActions(intent);
}
removeAction(intent: string, action: string, parameters?: string[]): boolean {
return this.nlp.removeAction(intent, action, parameters);
}
removeActions(intent: string): boolean {
return this.nlp.removeActions(intent);
}
addAnswer(locale: string, intent: string, answer: string, opts?: any): string {
return this.nlp.addAnswer(locale, intent, answer, opts);
}
removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {
return this.nlp.removeAnswer(locale, intent, answer, opts);
}
findAllAnswers(locale: string, intent: string): string[] {
return this.nlp.findAllAnswers(locale, intent);
}
async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {
const sentiment = await this.nlp.getSentiment(locale, utterance);
return this.sentimentManager
|
.translate(sentiment.sentiment);
|
}
addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {
return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);
}
removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {
return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);
}
addRegexEntity(entityName: string, languages: string[], regex: string): void {
return this.nlp.addNerRegexRule(languages, entityName, regex);
}
addBetweenCondition(locale: string, name: string, left: string, right: string, opts?: any): void {
return this.nlp.addNerBetweenCondition(locale, name, left, right, opts);
}
addPositionCondition(locale: string, name: string, position: string, words: string[], opts?: any): void {
return this.nlp.addNerPositionCondition(locale, name, position, words, opts);
}
addAfterCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterCondition(locale, name, words, opts);
}
addAfterFirstCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterFirstCondition(locale, name, words, opts);
}
addAfterLastCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerAfterLastCondition(locale, name, words, opts);
}
addBeforeCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeCondition(locale, name, words, opts);
}
addBeforeFirstCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeFirstCondition(locale, name, words, opts);
}
addBeforeLastCondition(locale: string, name: string, words: string[], opts?: any): void {
return this.nlp.addNerBeforeLastCondition(locale, name, words, opts);
}
describeLanguage(locale: string, name: string): void {
return this.nlp.describeLanguage(locale, name);
}
beginEdit(): void {
}
async train(): Promise<void> {
return this.nlp.train();
}
classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {
return this.nlp.classify(locale, utterance, settings);
}
async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {
const result = await this.nlp.process(locale, utterance, context, settings);
if (this.settings.processTransformer) {
return this.settings.processTransformer(result);
}
return result;
}
extractEntities(locale: string, utterance: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {
return this.nlp.extractEntities(locale, utterance, context, settings);
}
toObj(): any {
return this.nlp.toJSON();
}
fromObj(obj: any): any {
return this.nlp.fromJSON(obj);
}
/**
* Export NLP manager information as a string.
* @param {Boolean} minified If true, the returned JSON will have no spacing or indentation.
* @returns {String} NLP manager information as a JSON string.
*/
export(minified = false): string {
const clone = this.toObj();
return minified ? JSON.stringify(clone) : JSON.stringify(clone, null, 2);
}
/**
* Load NLP manager information from a string.
* @param {String|Object} data JSON string or object to load NLP manager information from.
*/
import(data: string | Record<string, unknown>): void {
const clone = typeof data === 'string' ? JSON.parse(data) : data;
this.fromObj(clone);
}
/**
* Save the NLP manager information into a file.
* @param {String} srcFileName Filename for saving the NLP manager.
* @param minified
*/
save(srcFileName?: string, minified = false): void {
const fileName = srcFileName || 'model.nlp';
fs.writeFileSync(fileName, this.export(minified), 'utf8');
}
/**
* Load the NLP manager information from a file.
* @param srcFileName
*/
load(srcFileName?: string): void {
const fileName = srcFileName || 'model.nlp';
const data = fs.readFileSync(fileName, 'utf8');
this.import(data);
}
/**
* Load the NLP manager information from an Excel file.
* @param fileName
*/
loadExcel(fileName = 'model.xls'): void {
const reader = new NlpExcelReader(this);
reader.load(fileName);
}
async testCorpus(corpus: any): Promise<any> {
const { data } = corpus;
const result = {
total: 0,
good: 0,
bad: 0,
};
const promises = [];
const intents = [];
for (let i = 0; i < data.length; i += 1) {
const intentData = data[i];
const { tests } = intentData;
for (let j = 0; j < tests.length; j += 1) {
promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));
intents.push(intentData.intent);
}
}
result.total += promises.length;
const results = await Promise.all(promises);
for (let i = 0; i < results.length; i += 1) {
const current = results[i];
if (current.intent === intents[i]) {
result.good += 1;
} else {
result.bad += 1;
}
}
return result
}
addCorpora(corpora: any): void {
this.nlp.addCorpora(corpora);
}
addCorpus(corpus: any): void {
this.nlp.addCorpus(corpus);
}
async trainAndEvaluate(fileName: string | object): Promise<any> {
let corpus = fileName;
if (typeof fileName === 'string') {
const nlpfs = this.container.get('fs');
const fileData = await nlpfs.readFile(fileName);
if (!fileData) {
throw new Error(`Corpus not found "${fileName}"`);
}
corpus = typeof fileData === 'string' ? JSON.parse(fileData) : fileData;
}
this.nlp.addCorpus(corpus);
await this.train();
return this.testCorpus(corpus);
}
}
export default NlpManager;
|
src/nlp/nlp-manager.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " return this.add(locale, intent, answer, opts);\n }\n async findAnswer(locale: string, intent: string, context: any, settings?: any): Promise<{ response: any } | undefined> {\n const answer = await this.find(locale, intent, context, settings);\n if (!answer.answer) {\n return undefined;\n }\n return {\n response: answer.answer,\n };",
"score": 0.8855090141296387
},
{
"filename": "src/sentiment/sentiment-analyzer.ts",
"retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;",
"score": 0.8785302639007568
},
{
"filename": "src/types/@nlpjs/nlg.d.ts",
"retrieved_chunk": " }\n class NlgManager {\n constructor(settings?: NlgManagerSettings, container?: Container);\n add(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;\n addAnswer(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;\n filterAnswers(srcInput: {answer: string, opts: string}[]): {answers: {answer: string, opts: string}[]};\n find(locale: string, intent: string, context?: Record<string, any>, options?: FindAnswerOptions): Promise<NlgManagerAnswer>;\n findAnswer(locale: string, intent: string, context?: Record<string, any>, options?: FindAnswerOptions): Promise<Answer | undefined>;\n findAllAnswers(locale?: string, intent?: string, context?: Record<string, any>): Array<{answer: string, opts: string}>;\n remove(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;",
"score": 0.8775141835212708
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " locale?: string,\n utterance?: string\n ): Promise<string> {\n const context = srcContext || {};\n const response = await (locale\n ? this.nlpManager.process(locale, utterance, context)\n : this.nlpManager.process(utterance, undefined, context));\n if (response.score < this.threshold || response.intent === 'None') {\n response.answer = undefined;\n return response;",
"score": 0.8618000745773315
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " response: x.answer,\n opts: x.opts,\n }));\n }\n return super.findAllAnswers(locale);\n }\n}\nexport default NlgManager;",
"score": 0.8530054092407227
}
] |
typescript
|
.translate(sentiment.sentiment);
|
import { XDoc } from '@nlpjs/xtables';
import NlpManager from './nlp-manager';
class NlpExcelReader {
private manager: NlpManager;
private xdoc: XDoc;
constructor(manager: NlpManager) {
this.manager = manager;
this.xdoc = new XDoc();
}
load(filename: string): void {
this.xdoc.read(filename);
this.loadSettings();
this.loadLanguages();
this.loadNamedEntities();
this.loadRegexEntities();
this.loadIntents();
this.loadResponses();
}
loadSettings(): void {}
loadLanguages(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Languages').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addLanguage(row.iso2);
});
}
loadNamedEntities(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Named Entities').data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addNamedEntityText(row.entity, row.option, languages, [row.text]);
});
}
loadRegexEntities(): void {
const table = this.xdoc.getTable('Regex Entities');
if (table) {
const rows: Record<string, string>[] = table.data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addRegexEntity(row.entity, languages, row.regex);
});
}
}
loadIntents(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Intents').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addDocument(row.language, row.utterance, row.intent);
});
}
loadResponses(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Responses').data;
rows.forEach((row: Record<string, string>) => {
|
this.manager.addAnswer(row.language, row.intent, row.response, row.condition);
|
// this.manager.addAnswer(row.language, row.intent, row.response, row.condition, row.url);
});
}
}
export default NlpExcelReader;
|
src/nlp/nlp-excel-reader.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " } else {\n const builtin = new BuiltinMicrosoft(this.settings.ner);\n this.container.register('extract-builtin-??', builtin, true);\n }\n }\n public addDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.addDocument(locale, utterance, intent);\n }\n public removeDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.removeDocument(locale, utterance, intent);",
"score": 0.8173559308052063
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " });\n }\n this.corpus = [];\n }\n add(utterance: string, intent: string) {\n this.corpus.push({ utterance, intent });\n }\n train() {\n return this.nlu?.train(this.corpus, this.settings);\n }",
"score": 0.8061946034431458
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " bad: 0,\n };\n const promises = [];\n const intents = [];\n for (let i = 0; i < data.length; i += 1) {\n const intentData = data[i];\n const { tests } = intentData;\n for (let j = 0; j < tests.length; j += 1) {\n promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));\n intents.push(intentData.intent);",
"score": 0.7892353534698486
},
{
"filename": "src/types/@nlpjs/nlg.d.ts",
"retrieved_chunk": " }\n class NlgManager {\n constructor(settings?: NlgManagerSettings, container?: Container);\n add(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;\n addAnswer(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;\n filterAnswers(srcInput: {answer: string, opts: string}[]): {answers: {answer: string, opts: string}[]};\n find(locale: string, intent: string, context?: Record<string, any>, options?: FindAnswerOptions): Promise<NlgManagerAnswer>;\n findAnswer(locale: string, intent: string, context?: Record<string, any>, options?: FindAnswerOptions): Promise<Answer | undefined>;\n findAllAnswers(locale?: string, intent?: string, context?: Record<string, any>): Array<{answer: string, opts: string}>;\n remove(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;",
"score": 0.7871024012565613
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " getActions(intent: string): string[] {\n return this.nlp.getActions(intent);\n }\n removeAction(intent: string, action: string, parameters?: string[]): boolean {\n return this.nlp.removeAction(intent, action, parameters);\n }\n removeActions(intent: string): boolean {\n return this.nlp.removeActions(intent);\n }\n addAnswer(locale: string, intent: string, answer: string, opts?: any): string {",
"score": 0.7856210470199585
}
] |
typescript
|
this.manager.addAnswer(row.language, row.intent, row.response, row.condition);
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import ConversationContext from './conversation-context';
import { Session } from "../types/session";
/**
* In memory conversation context manager.
*/
class MemoryConversationContext extends ConversationContext {
private readonly conversationContexts: { [conversationId: string]: any };
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
super(settings);
this.conversationContexts = {};
}
/**
* Gets the conversation context from the session.
* @param {Object} session Chatbot session of the conversation.
* @returns {Promise<Object>} Promise to resolve the conversation context.
*/
public getConversationContext(session: Session): Promise<Object> {
return new Promise((resolve, reject) => {
const
|
conversationId = this.getConversationId(session);
|
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
if (!this.conversationContexts[conversationId]) {
this.conversationContexts[conversationId] = {};
}
return resolve(this.conversationContexts[conversationId]);
});
}
public setConversationContext(session: Session, context: any): Promise<void> {
return new Promise((resolve, reject) => {
const conversationId = this.getConversationId(session);
if (!conversationId) {
return reject(new Error('No conversation id found'));
}
this.conversationContexts[conversationId] = context;
return resolve();
});
}
}
export default MemoryConversationContext;
|
src/recognizer/memory-conversation-context.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * Given a session instance of a chatbot, return the conversation identifier.\n * @param {Object} session Session instance of a message of chatbot.\n * @returns {String} Identifier of the conversation.\n */\n public getConversationId(session: Session): string | undefined {\n if (session?.message?.address?.conversation) {\n return session.message.address.conversation.id;\n }\n if (session?._activity?.conversation) {\n return session._activity.conversation.id;",
"score": 0.8549277782440186
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8418380618095398
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " }\n return undefined;\n }\n}\nexport default ConversationContext;",
"score": 0.7974510192871094
},
{
"filename": "src/types/session.d.ts",
"retrieved_chunk": "export type Session = {\n message?: {\n address?: {\n conversation?: {\n id: string;\n };\n };\n };\n _activity?: {\n conversation?: {",
"score": 0.7962257862091064
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " conversationContext?: MemoryConversationContext;\n }) {\n this.nlpManager =\n this.settings.nlpManager ||\n new NlpManager({\n container: this.settings.container,\n ner: { threshold: this.settings.nerThreshold || 1 },\n });\n this.threshold = this.settings.threshold || 0.7;\n this.conversationContext =",
"score": 0.7834057807922363
}
] |
typescript
|
conversationId = this.getConversationId(session);
|
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { NlpManager } from '../nlp';
import MemoryConversationContext from './memory-conversation-context';
/**
* Microsoft Bot Framework compatible recognizer for nlp.js.
*/
class Recognizer {
private readonly nlpManager: NlpManager;
private readonly threshold: number;
private readonly conversationContext: MemoryConversationContext;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(private readonly settings: {
nlpManager?: NlpManager;
container?: any;
nerThreshold?: number;
threshold?: number;
conversationContext?: MemoryConversationContext;
}) {
this.nlpManager =
this.settings.nlpManager ||
new NlpManager({
container: this.settings.container,
ner: { threshold: this.settings.nerThreshold || 1 },
});
this.threshold = this.settings.threshold || 0.7;
this.conversationContext =
this.settings.conversationContext || new MemoryConversationContext({});
}
/**
* Train the NLP manager.
*/
public async train(): Promise<void> {
await this.nlpManager.train();
}
/**
* Loads the model from a file.
* @param {String} filename Name of the file.
*/
public load(filename: string): void {
|
this.nlpManager.load(filename);
|
}
/**
* Saves the model into a file.
* @param {String} filename Name of the file.
*/
public save(filename: string): void {
this.nlpManager.save(filename);
}
/**
* Loads the NLP manager from an excel.
* @param {String} filename Name of the file.
*/
public async loadExcel(filename: string): Promise<void> {
this.nlpManager.loadExcel(filename);
await this.train();
this.save(filename);
}
/**
* Process an utterance using the NLP manager. This is done using a given context
* as the context object.
* @param {Object} srcContext Source context
* @param {String} locale Locale of the utterance.
* @param {String} utterance Locale of the utterance.
*/
public async process(
srcContext: Record<string, unknown>,
locale?: string,
utterance?: string
): Promise<string> {
const context = srcContext || {};
const response = await (locale
? this.nlpManager.process(locale, utterance, context)
: this.nlpManager.process(utterance, undefined, context));
if (response.score < this.threshold || response.intent === 'None') {
response.answer = undefined;
return response;
}
for (let i = 0; i < response.entities.length; i += 1) {
const entity = response.entities[i];
context[entity.entity] = entity.option;
}
if (response.slotFill) {
context.slotFill = response.slotFill;
} else {
delete context.slotFill;
}
return response;
}
/**
* Given an utterance and the locale, returns the recognition of the utterance.
* @param {String} utterance Utterance to be recognized.
* @param {String} model Model of the utterance.
* @param {Function} cb Callback Function.
*/
public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {
const response = await this.process(
model,
model ? model.locale : undefined,
utterance
);
return cb(null, response);
}
}
export default Recognizer;
|
src/recognizer/recognizer.ts
|
Leoglme-node-nlp-typescript-fbee5fd
|
[
{
"filename": "src/nlp/nlp-excel-reader.ts",
"retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {",
"score": 0.8590748310089111
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);",
"score": 0.8487565517425537
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " async trainAndEvaluate(fileName: string | object): Promise<any> {\n let corpus = fileName;\n if (typeof fileName === 'string') {\n const nlpfs = this.container.get('fs');\n const fileData = await nlpfs.readFile(fileName);\n if (!fileData) {\n throw new Error(`Corpus not found \"${fileName}\"`);\n }\n corpus = typeof fileData === 'string' ? JSON.parse(fileData) : fileData;\n }",
"score": 0.8358885049819946
},
{
"filename": "src/nlp/nlp-excel-reader.ts",
"retrieved_chunk": " this.xdoc.read(filename);\n this.loadSettings();\n this.loadLanguages();\n this.loadNamedEntities();\n this.loadRegexEntities();\n this.loadIntents();\n this.loadResponses();\n }\n loadSettings(): void {}\n loadLanguages(): void {",
"score": 0.8325796723365784
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " });\n }\n this.corpus = [];\n }\n add(utterance: string, intent: string) {\n this.corpus.push({ utterance, intent });\n }\n train() {\n return this.nlu?.train(this.corpus, this.settings);\n }",
"score": 0.8287820816040039
}
] |
typescript
|
this.nlpManager.load(filename);
|
import { Context, MiddlewareHandler } from 'hono'
import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types'
import {
After,
Append,
AppendGlobalCode,
Before,
Prepend,
Remove,
RemoveAndKeepContent,
RemoveAttribute,
Replace,
SetAttribute,
SetInnerContent,
SetStyleProperty,
} from './htmlRewriterClasses'
export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => {
if (!options.url) {
options.url = 'https://edge-api.exporio.cloud'
}
if (!options.apiKey) {
throw new Error('Exporio middleware requires options for "apiKey"')
}
return async (c, next) => {
const exporioInstructions = await fetchExporioInstructions(c, options)
if (!exporioInstructions) {
c.set('contentUrl', c.req.url)
await next()
} else {
c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url))
await next()
applyRewriterInstruction(c, exporioInstructions)
applyCookieInstruction(c.res.headers, exporioInstructions)
}
}
}
|
const buildRequestJson = (c: Context, apiKey: string): RequestJson => {
|
const headersInit: HeadersInit = []
c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value]))
return {
originalRequest: {
url: c.req.url,
method: c.req.method,
headersInit: headersInit,
},
params: {
API_KEY: apiKey,
},
}
}
const fetchExporioInstructions = async (
c: Context,
options: ExporioMiddlewareOptions
): Promise<Instructions | null> => {
try {
const requestJson = buildRequestJson(c, options.apiKey)
const exporioRequest = new Request(options.url, {
method: 'POST',
body: JSON.stringify(requestJson),
headers: { 'Content-Type': 'application/json' },
})
const exporioResponse = await fetch(exporioRequest)
return await exporioResponse.json()
} catch (err) {
console.error('Failed to fetch exporio instructions', err)
return null
}
}
const getContentUrl = (instructions: Instructions, defaultUrl: string): string => {
const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
}
const applyRewriterInstruction = (c: Context, instructions: Instructions) => {
let response = new Response(c.res.body, c.res)
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
switch (method) {
// Default Methods
case 'After': {
const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Append': {
const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Before': {
const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Prepend': {
const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Remove': {
const rewriter = new HTMLRewriter().on(selector, new Remove())
response = rewriter.transform(response)
break
}
case 'RemoveAndKeepContent': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent())
response = rewriter.transform(response)
break
}
case 'RemoveAttribute': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1))
response = rewriter.transform(response)
break
}
case 'Replace': {
const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetAttribute': {
const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetInnerContent': {
const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2))
response = rewriter.transform(response)
break
}
// Custom Methods
case 'AppendGlobalCode': {
const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetStyleProperty': {
const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2))
response = rewriter.transform(response)
break
}
}
})
c.res = new Response(response.body, response)
}
const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`]
if (cookie.domain) {
cookieAttributes.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
cookieAttributes.push(`Path=${cookie.path}`)
}
if (cookie.expires) {
cookieAttributes.push(`Expires=${cookie.expires}`)
}
if (cookie.maxAge) {
cookieAttributes.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.httpOnly) {
cookieAttributes.push('HttpOnly')
}
if (cookie.secure) {
cookieAttributes.push('Secure')
}
if (cookie.sameSite) {
cookieAttributes.push(`SameSite=${cookie.sameSite}`)
}
if (cookie.partitioned) {
cookieAttributes.push('Partitioned')
}
headers.append('Set-Cookie', cookieAttributes.join('; '))
})
}
|
src/index.ts
|
exporio-edge-sdk-hono-23bcafc
|
[
{
"filename": "src/types/general.ts",
"retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }",
"score": 0.8439548015594482
},
{
"filename": "src/types/general.ts",
"retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }",
"score": 0.824429988861084
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'",
"score": 0.8116951584815979
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any",
"score": 0.7930637001991272
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }",
"score": 0.7822468280792236
}
] |
typescript
|
const buildRequestJson = (c: Context, apiKey: string): RequestJson => {
|
import { Context, MiddlewareHandler } from 'hono'
import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types'
import {
After,
Append,
AppendGlobalCode,
Before,
Prepend,
Remove,
RemoveAndKeepContent,
RemoveAttribute,
Replace,
SetAttribute,
SetInnerContent,
SetStyleProperty,
} from './htmlRewriterClasses'
export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => {
if (!options.url) {
options.url = 'https://edge-api.exporio.cloud'
}
if (!options.apiKey) {
throw new Error('Exporio middleware requires options for "apiKey"')
}
return async (c, next) => {
const exporioInstructions = await fetchExporioInstructions(c, options)
if (!exporioInstructions) {
c.set('contentUrl', c.req.url)
await next()
} else {
c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url))
await next()
applyRewriterInstruction(c, exporioInstructions)
applyCookieInstruction(c.res.headers, exporioInstructions)
}
}
}
const buildRequestJson = (c: Context, apiKey: string): RequestJson => {
const headersInit: HeadersInit = []
c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value]))
return {
originalRequest: {
url: c.req.url,
method: c.req.method,
headersInit: headersInit,
},
params: {
API_KEY: apiKey,
},
}
}
const fetchExporioInstructions = async (
c: Context,
options: ExporioMiddlewareOptions
): Promise<Instructions | null> => {
try {
const requestJson = buildRequestJson(c, options.apiKey)
const exporioRequest = new Request(options.url, {
method: 'POST',
body: JSON.stringify(requestJson),
headers: { 'Content-Type': 'application/json' },
})
const exporioResponse = await fetch(exporioRequest)
return await exporioResponse.json()
} catch (err) {
console.error('Failed to fetch exporio instructions', err)
return null
}
}
const getContentUrl = (instructions: Instructions, defaultUrl: string): string => {
|
const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
}
|
const applyRewriterInstruction = (c: Context, instructions: Instructions) => {
let response = new Response(c.res.body, c.res)
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
switch (method) {
// Default Methods
case 'After': {
const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Append': {
const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Before': {
const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Prepend': {
const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Remove': {
const rewriter = new HTMLRewriter().on(selector, new Remove())
response = rewriter.transform(response)
break
}
case 'RemoveAndKeepContent': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent())
response = rewriter.transform(response)
break
}
case 'RemoveAttribute': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1))
response = rewriter.transform(response)
break
}
case 'Replace': {
const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetAttribute': {
const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetInnerContent': {
const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2))
response = rewriter.transform(response)
break
}
// Custom Methods
case 'AppendGlobalCode': {
const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetStyleProperty': {
const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2))
response = rewriter.transform(response)
break
}
}
})
c.res = new Response(response.body, response)
}
const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`]
if (cookie.domain) {
cookieAttributes.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
cookieAttributes.push(`Path=${cookie.path}`)
}
if (cookie.expires) {
cookieAttributes.push(`Expires=${cookie.expires}`)
}
if (cookie.maxAge) {
cookieAttributes.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.httpOnly) {
cookieAttributes.push('HttpOnly')
}
if (cookie.secure) {
cookieAttributes.push('Secure')
}
if (cookie.sameSite) {
cookieAttributes.push(`SameSite=${cookie.sameSite}`)
}
if (cookie.partitioned) {
cookieAttributes.push('Partitioned')
}
headers.append('Set-Cookie', cookieAttributes.join('; '))
})
}
|
src/index.ts
|
exporio-edge-sdk-hono-23bcafc
|
[
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }",
"score": 0.7959713935852051
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}",
"score": 0.7896975874900818
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'",
"score": 0.7680753469467163
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": " partitioned?: boolean\n}\ntype CookieInstruction = {\n setCookie: boolean\n cookies: Cookie[]\n}\ntype Transformation = {\n method: string\n selector: string\n argument1: any",
"score": 0.755115807056427
},
{
"filename": "src/types/general.ts",
"retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }",
"score": 0.7540086507797241
}
] |
typescript
|
const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.