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 { startWithBytecode } from "smoldot/dist/mjs/no-auto-bytecode-browser"
import type { ValidatorData } from "../types"
// @ts-ignore
import SmWorker from "./sm-worker?worker"
// @ts-ignore
import ValidatorsWorker from "./validators-worker?worker"
const smWorker: Worker = SmWorker()
const smoldotRawChannel = new MessageChannel()
smWorker.postMessage(smoldotRawChannel.port1, [smoldotRawChannel.port1])
const validatorsWorker: Worker = ValidatorsWorker()
const chainSpecPromise = import("./polkadot-spec").then((x) => x.default)
const bytecodePromise = new Promise((resolve) => {
smWorker.addEventListener("message", (e) => {
resolve(e.data)
}),
{
once: true,
}
})
;(async () => {
const bytecode: any = await bytecodePromise
const client = startWithBytecode({
bytecode,
portToWorker: smoldotRawChannel.port2,
})
const chainSpec = await chainSpecPromise
const chain = await client.addChain({
chainSpec,
})
const validatorsChannel = new MessageChannel()
validatorsChannel.port2.onmessage = (e) => {
chain.sendJsonRpc(e.data)
}
validatorsWorker.postMessage(validatorsChannel.port1, [
validatorsChannel.port1,
])
try {
while (true)
validatorsChannel.port2.postMessage(await chain.nextJsonRpcResponse())
} catch (e) {
console.error(e)
validatorsWorker.postMessage(e)
}
})()
| export const validators = new Promise<Record<string, ValidatorData>>(
(res, rej) => { |
validatorsWorker.addEventListener(
"message",
(e) => {
if (e.data?.type === "result") {
console.trace("validators loaded")
res(e.data.payload)
} else rej(e.data?.payload ?? e.data)
},
{ once: true },
)
},
)
| src/api/validators/index.ts | w3f-validator-selection-tool-e904b57 | [
{
"filename": "src/api/validators/getValidators.ts",
"retrieved_chunk": " ]\n }),\n )\n postMessage({ type: \"result\", payload: result })\n } catch (e) {\n postMessage({ type: \"error\", payload: e })\n }\n}",
"score": 42.2616356830972
},
{
"filename": "src/api/validators/getPoints.ts",
"retrieved_chunk": "import { getStakingCurrentEra, getStakingErasRewardsPoints } from \"./chain\"\nconst N_ERAS = 83\nexport const getEraPoints = async (validators: string[]) => {\n const currentEra = await getStakingCurrentEra()\n const previousEras = Array(N_ERAS)\n .fill(null)\n .map((_, idx) => currentEra! - idx - 1)\n const allEraPoints = await Promise.all(\n previousEras.map(getStakingErasRewardsPoints),\n )",
"score": 15.866327728209434
},
{
"filename": "src/App/Results/Results.tsx",
"retrieved_chunk": " Reset\n </Button>\n )\n}\nexport default function Results() {\n const resultsState = useStateObservable(resultsState$)\n return (\n <form\n onSubmit={(e) => {\n e.preventDefault()",
"score": 15.742421516057993
},
{
"filename": "src/api/validators/chain/client.ts",
"retrieved_chunk": "import { createClient, ProviderStatus } from \"@unstoppablejs/client\"\nimport { WsProvider } from \"@unstoppablejs/ws-provider\"\nimport { storageClient } from \"@unstoppablejs/substrate-bindings\"\nlet onMessagePort: (port: MessagePort) => void\nconst smPortPromise: Promise<MessagePort> = new Promise((res) => {\n onMessagePort = res\n})\nexport const setSmPort = (smPort: MessagePort) => {\n onMessagePort(smPort)\n}",
"score": 15.586026125621148
},
{
"filename": "src/api/validators/getVotes.ts",
"retrieved_chunk": "import { lastValueFrom, mergeMap } from \"rxjs\"\nimport { getStakingNominatorsFromKey, stakingNominatorsKeys$ } from \"./chain\"\nexport const getVotes = async (validators: string[]) => {\n const votes: Map<string, { count: number }> = new Map(\n validators.map((v) => [v, { count: 0 }]),\n )\n const getNominatorAndUpdateVotes = async (storageKey: string) => {\n const nominator = await getStakingNominatorsFromKey(storageKey)\n nominator?.targets.forEach((t) => {\n const v = votes.get(t)",
"score": 15.316041527708855
}
] | typescript | export const validators = new Promise<Record<string, ValidatorData>>(
(res, rej) => { |
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/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": 38.01731617190286
},
{
"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": 21.52126727606348
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}\nfunction idRef(propertyName: string) {\n return function mapper({ attributeValue: idRef, container }: MapperArgs) {\n const node = getNodeByIdRef({ container, idRef });\n if (!node) {\n return \"\";\n }\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);\n const itemText = getItemText({ accessibleName, accessibleValue });",
"score": 21.055063802329293
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": " .filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;\n if (idRefsCount === 0) {\n return \"\";\n }\n return `${printCount ? `${idRefsCount} ` : \"\"}${\n idRefsCount === 1\n ? propertyDescriptionSuffixSingular\n : propertyDescriptionSuffixPlural\n }`;\n };",
"score": 18.838839807961776
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": "};\nexport const getLabelFromImplicitHtmlElementValue = ({\n attributeName,\n container,\n node,\n}: {\n attributeName: string;\n container: Node;\n node: HTMLElement;\n}) => {",
"score": 17.278904903410307
}
] | 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": " accessibleAttributeLabels,\n accessibleDescription: amendedAccessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n };\n}",
"score": 35.53153331508266
},
{
"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": 22.09303099368446
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " node,\n role,\n spokenRole,\n }) =>\n accessibleDescription === this.#activeNode?.accessibleDescription &&\n accessibleName === this.#activeNode?.accessibleName &&\n accessibleValue === this.#activeNode?.accessibleValue &&\n node === this.#activeNode?.node &&\n role === this.#activeNode?.role &&\n spokenRole === this.#activeNode?.spokenRole",
"score": 19.32786472366907
},
{
"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": 18.445778113584215
},
{
"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": 13.574869921988705
}
] | 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/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": 32.70309742603214
},
{
"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": 26.396472147300177
},
{
"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": 26.11816106919895
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const ownedNode = getNodeByIdRef({ container, idRef });\n if (!!ownedNode && !ownedNodes.has(ownedNode)) {\n ownedNodes.add(ownedNode);\n }\n });\n}\nfunction getAllOwnedNodes(node: Node) {\n const ownedNodes = new Set<Node>();\n if (!isElement(node)) {\n return ownedNodes;",
"score": 24.084136030156557
},
{
"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": 21.805616031518646
}
] | 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/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": 22.324356901125086
},
{
"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": 21.472468186233826
},
{
"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": 19.703545090243658
},
{
"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": 15.296268657686603
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": " );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };\n}",
"score": 15.24780063973337
}
] | 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/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": 32.37602353334553
},
{
"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": 24.473145083692277
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "export const mapAttributeNameAndValueToLabel = ({\n attributeName,\n attributeValue,\n container,\n negative = false,\n}: {\n attributeName: string;\n attributeValue: string | null;\n container: Node;\n negative?: boolean;",
"score": 24.12989294587911
},
{
"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": 22.232614088300778
},
{
"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": 20.08881794039865
}
] | 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/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": 26.574168543475107
},
{
"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": 25.858252475465612
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/postProcessLabels.ts",
"retrieved_chunk": " });\n }\n return Object.values(labels).map(({ label }) => label);\n};",
"score": 18.431078879728418
},
{
"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": 13.5859495711168
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " });\n if (label) {\n return { label, value: attributeValue };\n }\n }\n return { label: \"\", value: \"\" };\n};",
"score": 12.153992600963186
}
] | 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/isElement.ts",
"retrieved_chunk": "export function isElement(node: Node): node is HTMLElement {\n return node.nodeType === Node.ELEMENT_NODE;\n}",
"score": 25.127677309819298
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " */\nconst observeDOM = (function () {\n const MutationObserver = window.MutationObserver;\n return function observeDOM(\n node: Node,\n onChange: MutationCallback\n ): () => void {\n if (!isElement(node)) {\n return;\n }",
"score": 21.631259083475932
},
{
"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": 20.913403813294305
},
{
"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": 20.661016306062642
},
{
"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": 20.597361337637444
}
] | 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": 38.89130253388828
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " container,\n node,\n role,\n}: {\n accessibleValue: string;\n alternateReadingOrderParents: Node[];\n container: Node;\n node: Node;\n role: string;\n}): string[] => {",
"score": 29.02327880128705
},
{
"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": 26.725591778782068
},
{
"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": 25.86386326723907
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}\nfunction idRef(propertyName: string) {\n return function mapper({ attributeValue: idRef, container }: MapperArgs) {\n const node = getNodeByIdRef({ container, idRef });\n if (!node) {\n return \"\";\n }\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);\n const itemText = getItemText({ accessibleName, accessibleValue });",
"score": 23.735907881083794
}
] | 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": "}: {\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": 26.774670437298436
},
{
"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": 23.544034151262316
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " container,\n node,\n role,\n}: {\n accessibleValue: string;\n alternateReadingOrderParents: Node[];\n container: Node;\n node: Node;\n role: string;\n}): string[] => {",
"score": 22.40579883935765
},
{
"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": 21.762354069983942
},
{
"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": 19.373581597948156
}
] | 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/Virtual.ts",
"retrieved_chunk": " });\n if (typeof nextIndex !== \"number\") {\n return;\n }\n const newActiveNode = tree.at(nextIndex);\n this.#updateState(newActiveNode);\n return;\n }\n /**\n * Click the mouse.",
"score": 19.46147955549496
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleValue.ts",
"retrieved_chunk": " }\n return typeof node.value === \"number\" ? `${node.value}` : node.value;\n}\nexport function getAccessibleValue(node: Node) {\n if (!isElement(node)) {\n return \"\";\n }\n switch (node.localName) {\n case \"input\": {\n return getInputValue(node as HTMLInputElement);",
"score": 17.9849852403042
},
{
"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": 15.390343187745625
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": " none: \"no defined sort order\",\n other: \"non ascending / descending sort order applied\",\n }),\n \"aria-valuemax\": number(\"max value\"),\n \"aria-valuemin\": number(\"min value\"),\n \"aria-valuenow\": number(\"current value\"),\n \"aria-valuetext\": string(\"current value\"),\n};\ninterface MapperArgs {\n attributeValue: string;",
"score": 13.72722980300437
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": "import { isElement } from \"../isElement\";\nimport { VirtualCommandArgs } from \"./types\";\nexport interface MoveToNextAlternateReadingOrderElement\n extends VirtualCommandArgs {\n index?: number;\n}\n/**\n * aria-flowto:\n *\n * However, when aria-flowto is provided with multiple ID",
"score": 13.241969742890664
}
] | 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/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": 25.051361016410365
},
{
"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": 23.952543004058434
},
{
"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": 23.876369321026765
},
{
"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": 21.3999768279088
},
{
"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": 17.87307614508118
}
] | 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": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 21.44352731697275
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n children: [],\n childrenPresentational,\n node: childNode,\n parent: node,",
"score": 21.38571457988598
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)\n ? Array.from(alternateReadingOrderMap.get(childNode))\n : [];\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 20.69637390697793
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " tree.children.push(\n growTree(\n childNode,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n alternateReadingOrderParents,",
"score": 20.664596295754727
},
{
"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": 19.825138355677907
}
] | typescript | const isExplicitPresentational = presentationRoles.includes(explicitRole); |
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/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": 28.15684025556218
},
{
"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": 27.228911768154504
},
{
"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": 25.13514797159986
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": " );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };\n}",
"score": 21.073323184161826
},
{
"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": 19.693510858115175
}
] | typescript | const itemText = getItemText(accessibilityNode); |
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": 18.012369250777873
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " *\n * @param {object} [options] Click options.\n */\n async click({ button = \"left\", clickCount = 1 } = {}) {\n this.#checkContainer();\n await tick();\n if (!this.#activeNode) {\n return;\n }\n const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;",
"score": 15.374892836763145
},
{
"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": 12.722253528097
},
{
"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": 11.252056862112976
},
{
"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": 10.977965262754788
}
] | 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/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " *\n * See also \"Children Presentational: True\".\n *\n * REF:\n *\n * - https://w3c.github.io/aria/#conflict_resolution_presentation_none\n * - https://w3c.github.io/aria/#tree_exclusion\n * - https://w3c.github.io/aria/#mustContain\n */\n const isExplicitAllowedChildElement = allowedAccessibilityRoles.some(",
"score": 15.099050538981544
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " *\n * REF: https://w3c.github.io/aria/#region\n */\n \"region\",\n /**\n * Assistive technologies SHOULD enable users to quickly navigate to\n * elements with role search.\n *\n * REF: https://w3c.github.io/aria/#search\n */",
"score": 13.291014675898692
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " * is applied.\n *\n * REF: https://w3c.github.io/aria/#conflict_resolution_presentation_none\n */\n .filter((role) => {\n if (!presentationRoles.includes(role)) {\n return true;\n }\n if (hasGlobalStateOrProperty(node) || isFocusable(node)) {\n return false;",
"score": 13.159681939960592
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " * REF: https://w3c.github.io/aria/#form\n */\n \"form\",\n /**\n * Assistive technologies SHOULD enable users to quickly navigate to\n * elements with role main.\n *\n * REF: https://w3c.github.io/aria/#main\n */\n \"main\",",
"score": 13.134691833753237
},
{
"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": 12.846319547772548
}
] | 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/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": 32.70309742603214
},
{
"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": 27.969655212524682
},
{
"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": 27.446392189515027
},
{
"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": 27.077740430191984
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const ownedNode = getNodeByIdRef({ container, idRef });\n if (!!ownedNode && !ownedNodes.has(ownedNode)) {\n ownedNodes.add(ownedNode);\n }\n });\n}\nfunction getAllOwnedNodes(node: Node) {\n const ownedNodes = new Set<Node>();\n if (!isElement(node)) {\n return ownedNodes;",
"score": 25.570002528202536
}
] | typescript | const itemText = getItemText({ accessibleName, accessibleValue }); |
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": 45.87495387207909
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getAttributesByRole.ts",
"retrieved_chunk": " const {\n props: implicitRoleAttributes = {},\n prohibitedProps: prohibitedAttributes = [],\n } = (roles.get(role as ARIARoleDefinitionKey) ?? {}) as {\n props: ARIAPropertyMap;\n prohibitedProps: string[];\n };\n const uniqueAttributes = Array.from(\n new Set([\n ...Object.keys(implicitRoleAttributes),",
"score": 19.14039403133807
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/postProcessLabels.ts",
"retrieved_chunk": " });\n }\n return Object.values(labels).map(({ label }) => label);\n};",
"score": 17.066364404420675
},
{
"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": 14.639579242645294
},
{
"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": 14.587754237754774
}
] | typescript | ) as { [K in VirtualCommandKey]: K }; |
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/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": 16.878904493084736
},
{
"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": 16.417347323209505
},
{
"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": 15.38643920177622
},
{
"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": 14.791860979365616
},
{
"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": 12.441710711488813
}
] | 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": 30.32665063076955
},
{
"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": 14.974263609703899
},
{
"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": 14.61901017292722
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " const { alternateReadingOrderParents } = tree.at(currentIndex);\n const targetNode = alternateReadingOrderParents[index];\n if (!targetNode) {\n return;\n }\n return tree.findIndex(({ node }) => node === targetNode);\n}",
"score": 13.679604702304893
},
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": " currentIndex,\n tree,\n });\n}",
"score": 12.49479325196242
}
] | 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/isElement.ts",
"retrieved_chunk": "export function isElement(node: Node): node is HTMLElement {\n return node.nodeType === Node.ELEMENT_NODE;\n}",
"score": 16.833549981336958
},
{
"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": 14.551992625383555
},
{
"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": 14.517772872714513
},
{
"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": 14.502143940199021
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " */\nconst observeDOM = (function () {\n const MutationObserver = window.MutationObserver;\n return function observeDOM(\n node: Node,\n onChange: MutationCallback\n ): () => void {\n if (!isElement(node)) {\n return;\n }",
"score": 14.49938218794689
}
] | 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/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": 39.10676443027971
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}\nfunction idRef(propertyName: string) {\n return function mapper({ attributeValue: idRef, container }: MapperArgs) {\n const node = getNodeByIdRef({ container, idRef });\n if (!node) {\n return \"\";\n }\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);\n const itemText = getItemText({ accessibleName, accessibleValue });",
"score": 22.794056921378772
},
{
"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": 21.52126727606348
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": "};\nexport const getLabelFromImplicitHtmlElementValue = ({\n attributeName,\n container,\n node,\n}: {\n attributeName: string;\n container: Node;\n node: HTMLElement;\n}) => {",
"score": 19.001594961968696
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": " .filter((idRef) => !!getNodeByIdRef({ container, idRef })).length;\n if (idRefsCount === 0) {\n return \"\";\n }\n return `${printCount ? `${idRefsCount} ` : \"\"}${\n idRefsCount === 1\n ? propertyDescriptionSuffixSingular\n : propertyDescriptionSuffixPlural\n }`;\n };",
"score": 18.838839807961776
}
] | 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": 21.20327338459989
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " *\n * @param {object} [options] Click options.\n */\n async click({ button = \"left\", clickCount = 1 } = {}) {\n this.#checkContainer();\n await tick();\n if (!this.#activeNode) {\n return;\n }\n const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;",
"score": 19.313819872731145
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex =\n currentIndex === -1 || currentIndex === tree.length - 1\n ? 0\n : currentIndex + 1;\n const newActiveNode = tree.at(nextIndex);\n this.#updateState(newActiveNode);",
"score": 15.01231279767588
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " async previous() {\n this.#checkContainer();\n await tick();\n const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;\n const newActiveNode = tree.at(nextIndex);",
"score": 13.200940610104979
},
{
"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": 12.722253528097
}
] | 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": 21.20327338459989
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " *\n * @param {object} [options] Click options.\n */\n async click({ button = \"left\", clickCount = 1 } = {}) {\n this.#checkContainer();\n await tick();\n if (!this.#activeNode) {\n return;\n }\n const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;",
"score": 19.313819872731145
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex =\n currentIndex === -1 || currentIndex === tree.length - 1\n ? 0\n : currentIndex + 1;\n const newActiveNode = tree.at(nextIndex);\n this.#updateState(newActiveNode);",
"score": 15.01231279767588
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " async previous() {\n this.#checkContainer();\n await tick();\n const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;\n const newActiveNode = tree.at(nextIndex);",
"score": 13.200940610104979
},
{
"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": 12.722253528097
}
] | 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/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": 32.37602353334553
},
{
"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": 24.473145083692277
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "export const mapAttributeNameAndValueToLabel = ({\n attributeName,\n attributeValue,\n container,\n negative = false,\n}: {\n attributeName: string;\n attributeValue: string | null;\n container: Node;\n negative?: boolean;",
"score": 24.12989294587911
},
{
"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": 22.232614088300778
},
{
"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": 20.08881794039865
}
] | 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": " accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n children: [],\n childrenPresentational,\n node: childNode,\n parent: node,",
"score": 17.580535961886916
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " node,\n role,\n spokenRole,\n }) =>\n accessibleDescription === this.#activeNode?.accessibleDescription &&\n accessibleName === this.#activeNode?.accessibleName &&\n accessibleValue === this.#activeNode?.accessibleValue &&\n node === this.#activeNode?.node &&\n role === this.#activeNode?.role &&\n spokenRole === this.#activeNode?.spokenRole",
"score": 17.47707224358293
},
{
"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": 16.849119137793373
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " tree.children.push(\n growTree(\n childNode,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n alternateReadingOrderParents,",
"score": 16.772124260541222
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)\n ? Array.from(alternateReadingOrderMap.get(childNode))\n : [];\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 16.485047823061812
}
] | 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": 27.68268450729975
},
{
"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": 23.942348773367677
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}\nfunction idRef(propertyName: string) {\n return function mapper({ attributeValue: idRef, container }: MapperArgs) {\n const node = getNodeByIdRef({ container, idRef });\n if (!node) {\n return \"\";\n }\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);\n const itemText = getItemText({ accessibleName, accessibleValue });",
"score": 22.473793592490406
},
{
"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": 22.05275704885319
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " }\n return true;\n });\n return filteredRoles?.[0] ?? \"\";\n}\nexport function getRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node,",
"score": 21.88070711229605
}
] | 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/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": 21.506073764466052
},
{
"filename": "src/isElement.ts",
"retrieved_chunk": "export function isElement(node: Node): node is HTMLElement {\n return node.nodeType === Node.ELEMENT_NODE;\n}",
"score": 19.092519746497096
},
{
"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": 17.52582108997836
},
{
"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": 17.471085788675786
},
{
"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": 16.9516421662845
}
] | typescript | switch (node.localName) { |
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": 69.43060200777819
},
{
"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": 29.91914909174334
},
{
"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": 28.958943301624533
},
{
"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": 26.66351482389833
},
{
"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": 25.03250140452565
}
] | typescript | (targetCharacter: EnemyCharacter) { |
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": 33.37291589040602
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " container,\n node,\n role,\n}: {\n accessibleValue: string;\n alternateReadingOrderParents: Node[];\n container: Node;\n node: Node;\n role: string;\n}): string[] => {",
"score": 26.395914223530248
},
{
"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": 24.08496465449599
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}\nfunction idRef(propertyName: string) {\n return function mapper({ attributeValue: idRef, container }: MapperArgs) {\n const node = getNodeByIdRef({ container, idRef });\n if (!node) {\n return \"\";\n }\n const accessibleName = getAccessibleName(node);\n const accessibleValue = getAccessibleValue(node);\n const itemText = getItemText({ accessibleName, accessibleValue });",
"score": 22.461421056110538
},
{
"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": 20.253128958347308
}
] | typescript | } = getRole({ |
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/Game.ts",
"retrieved_chunk": " const absDeltaY = Math.abs(deltaY);\n const absMin = Math.min(absDeltaX, absDeltaY);\n const absMax = Math.max(absDeltaX, absDeltaY);\n // The other axis must be smaller than this to avoid a diagonal swipe\n const confusionThreshold = absMax / 2;\n if (absMin < confusionThreshold) {\n if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {\n if (absMax == absDeltaX) {\n // Right or left\n this.keydown(deltaX > 0 ? \"KeyD\" : \"KeyA\");",
"score": 32.38389473357357
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " Math.round(avgShort) +\n \"\\n\" +\n Math.round(avgLong) +\n \"\\n\";\n }\n notifyScreensOfSize() {\n // Let screens now\n for (const s of this.stage.children) {\n if (s instanceof Screen) {\n if (Game.MAINTAIN_RATIO) {",
"score": 30.419885392003312
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " ? Math.max(1, Math.floor(smoothScaling))\n : smoothScaling;\n this.stage.scale.set(this.scale, this.scale);\n if (this.innerBackgroundSprite) {\n if (Game.MAINTAIN_RATIO) {\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;\n } else {\n this.innerBackgroundSprite.width = resizeInfo.width;\n this.innerBackgroundSprite.height = resizeInfo.height;",
"score": 26.613659071888275
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " return this._maxHp;\n }\n set maxHp(maxHp: number) {\n this._maxHp = maxHp;\n this.heartsHolder.removeChildren();\n for (let i = 0; i < this._maxHp; i++) {\n const heart = PIXI.Sprite.from(Game.tex(\"heart.png\"));\n heart.anchor.set(0.5);\n heart.position.set(\n -(this._maxHp * heart.width)/2 + heart.width * (i + 0.5),",
"score": 26.169786256976916
},
{
"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": 23.417748757654103
}
] | 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/grid/DungeonGrid.ts",
"retrieved_chunk": " if (typeof col == \"number\") {\n c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n for (const char of this.characters) {\n if (char.coords.col == c && char.coords.row == r) {\n return char;",
"score": 44.05089418944644
},
{
"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": 44.04150777597699
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " return this;\n }\n clone(): Coords {\n return new Coords(this.col, this.row);\n }\n equals(col: number | Coords, row: number = null) {\n let c = 0;\n let r = 0;\n if (typeof col == \"number\") {\n c = col;",
"score": 43.84174973616696
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 42.74773928950568
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n return this.col == c && this.row == r;\n }\n}",
"score": 40.61403571801328
}
] | typescript | EnemyCharacter(type); |
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": 59.69735911699873
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " for (const w of walls) {\n if (w.from.equals(from) && w.to.equals(to)) {\n alreadyExists = true;\n break;\n }\n }\n if (alreadyExists) continue;\n prospective = new Wall(from, to);\n }\n // If we can't flood fill, skip!",
"score": 49.330302006858204
},
{
"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": 44.918969398971235
},
{
"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": 43.31302450600385
},
{
"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": 33.62474131280798
}
] | 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/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": 53.67470737969573
},
{
"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": 47.27354719322234
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 46.73362380979465
},
{
"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": 43.325671671190605
},
{
"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": 38.95390714843705
}
] | typescript | (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/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": 36.215432861009134
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " for (const w of walls) {\n if (w.from.equals(from) && w.to.equals(to)) {\n alreadyExists = true;\n break;\n }\n }\n if (alreadyExists) continue;\n prospective = new Wall(from, to);\n }\n // If we can't flood fill, skip!",
"score": 29.680464604003724
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Add outer wall\n let walls: Wall[] = Wall.edges(this.dimension);\n // Make hole where exit is\n if (this.exitCoords && this.exitDir) {\n walls = walls.filter(\n (w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)\n );\n }\n // Draw walls\n this.drawWalls(walls);",
"score": 29.41518221724885
},
{
"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": 23.793542665539693
},
{
"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": 23.113332387179117
}
] | 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/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": 56.14122310262858
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resize(this.prevWidth, this.prevHeight);\n }\n resize(width: number, height: number) {\n if (!this.parent) return;\n this.prevWidth = width;\n this.prevHeight = height;\n this.darkOverlay.width = Game.instance.width / Game.instance.scale;\n this.darkOverlay.height = Game.instance.height / Game.instance.scale;\n this.darkOverlay.position.set(\n -this.parent.position.x / Game.instance.scale,",
"score": 55.76274969884377
},
{
"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": 51.64998417167916
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " cell.height = this.cellSize;\n const offset1 = (this.cellSize - cell.width) / 2;\n cell.position.set(\n i * this.cellSize + offset1,\n j * this.cellSize + offset1\n );\n col1.push(cell);\n this.addChild(cell);\n const stair = PIXI.Sprite.from(Game.tex(\"stairs.png\"));\n stair.width = this.cellSize * 0.8;",
"score": 49.58881868669377
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": " this.addChild(button);\n // Clicker\n const clicker = PIXI.Sprite.from(PIXI.Texture.WHITE);\n clicker.tint = 0xff0000;\n clicker.alpha = 0;\n clicker.anchor.set(0.5, 0.5);\n clicker.width = button.width * 1.5;\n clicker.height = button.height * 2;\n clicker.position.set(button.position.x, button.position.y);\n this.addChild(clicker);",
"score": 49.02538478793451
}
] | 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/save/Save.ts",
"retrieved_chunk": " });\n }\n private static deserialiseCharacters(characters: any): Character[] {\n return characters.map(\n (c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))\n );\n }\n private static createCharacter(type: CharacterType, hp: number, coords: Coords) {\n let c;\n if (type === \"player\") {",
"score": 20.81973182952587
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n characters: this.serialiseCharacters(dungeonGrid.characters),\n walls: this.serialiseWalls(dungeonGrid.walls),\n edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),\n dimension: dungeonGrid.dimension,\n exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),\n exitDir: this.serialiseCoords(dungeonGrid.exitDir),\n };\n }\n private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {",
"score": 19.561391013057797
},
{
"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": 19.544541304131553
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": " this.addChild(button);\n // Clicker\n const clicker = PIXI.Sprite.from(PIXI.Texture.WHITE);\n clicker.tint = 0xff0000;\n clicker.alpha = 0;\n clicker.anchor.set(0.5, 0.5);\n clicker.width = button.width * 1.5;\n clicker.height = button.height * 2;\n clicker.position.set(button.position.x, button.position.y);\n this.addChild(clicker);",
"score": 18.91378718429414
},
{
"filename": "src/ui/Button.ts",
"retrieved_chunk": " theLabel.tint = 0;\n theLabel.anchor.set(0.5);\n theLabel.position.x = 0;\n theLabel.position.y = 0;\n this.label = theLabel;\n // Background\n const holderBackground = PIXI.Sprite.from(PIXI.Texture.WHITE);\n holderBackground.width = 200;\n holderBackground.height = 25;\n holderBackground.position.set(",
"score": 17.6876556253656
}
] | 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": 32.75868910186144
},
{
"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": 25.145621506696717
},
{
"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": 23.953918392968852
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " };\n }\n private static deserialiseGameState(gameScreen: GameScreen, data: any) {\n gameScreen.level = data.level;\n gameScreen.state = data.state;\n gameScreen.score = data.score;\n // Remove the old dungeon grid:\n if (gameScreen.dungeonGrid) {\n gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);\n }",
"score": 22.456785214991722
},
{
"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": 21.239869409069236
}
] | 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/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": 46.63614720094638
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " if (typeof col == \"number\") {\n c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n for (const char of this.characters) {\n if (char.coords.col == c && char.coords.row == r) {\n return char;",
"score": 45.38723203094642
},
{
"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": 40.75144373224506
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " return this;\n }\n clone(): Coords {\n return new Coords(this.col, this.row);\n }\n equals(col: number | Coords, row: number = null) {\n let c = 0;\n let r = 0;\n if (typeof col == \"number\") {\n c = col;",
"score": 39.47269061460867
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 37.88746890945433
}
] | 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/grid/DungeonGrid.ts",
"retrieved_chunk": " if (typeof col == \"number\") {\n c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n for (const char of this.characters) {\n if (char.coords.col == c && char.coords.row == r) {\n return char;",
"score": 44.05089418944644
},
{
"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": 44.04150777597699
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " return this;\n }\n clone(): Coords {\n return new Coords(this.col, this.row);\n }\n equals(col: number | Coords, row: number = null) {\n let c = 0;\n let r = 0;\n if (typeof col == \"number\") {\n c = col;",
"score": 43.84174973616696
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 42.74773928950568
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n return this.col == c && this.row == r;\n }\n}",
"score": 40.61403571801328
}
] | 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/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": 51.66173450573107
},
{
"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": 48.363822243499385
},
{
"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": 42.84858639445776
},
{
"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": 42.41834837771315
},
{
"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": 40.62101732792684
}
] | 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": 31.18950521217321
},
{
"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": 21.30066799649237
},
{
"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": 16.849095619011663
},
{
"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": 16.70883678486242
},
{
"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": 15.45070127816987
}
] | 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": 36.45614282627195
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " if (typeof col == \"number\") {\n c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n for (const char of this.characters) {\n if (char.coords.col == c && char.coords.row == r) {\n return char;",
"score": 29.557058773963824
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 27.526056069119164
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": " return this;\n }\n clone(): Coords {\n return new Coords(this.col, this.row);\n }\n equals(col: number | Coords, row: number = null) {\n let c = 0;\n let r = 0;\n if (typeof col == \"number\") {\n c = col;",
"score": 27.436577863274287
},
{
"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": 24.970764023938955
}
] | typescript | 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": 32.155198575606406
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " Q: number[][],\n n: number[],\n dx: number,\n dy: number,\n dimension: number,\n walls: Wall[],\n prospective: Wall,\n flood: boolean[][]\n ) {\n const col = n[0] + dx;",
"score": 26.837142286236563
},
{
"filename": "src/utils/Coords.ts",
"retrieved_chunk": "export default class Coords {\n col: number;\n row: number;\n constructor(col: number, row: number) {\n this.col = col;\n this.row = row;\n }\n add(dx: number, dy: number) {\n this.col += dx;\n this.row += dy;",
"score": 24.316953084416294
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " }\n // If the prospective blocks, don't add\n if (prospective.blocks(from, dx, dy)) return;\n Q.push([col, row]);\n }\n static floodFill(\n flood: boolean[][],\n walls: Wall[],\n prospective: Wall,\n dimension: number",
"score": 24.082765725162723
},
{
"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": 22.420519917592138
}
] | typescript | if (!this.inBounds(targetCoord)) { |
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": " if (typeof col == \"number\") {\n c = col;\n r = row;\n } else {\n c = col.col;\n r = col.row;\n }\n for (const char of this.characters) {\n if (char.coords.col == c && char.coords.row == r) {\n return char;",
"score": 40.22784158075455
},
{
"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": 39.97043932978453
},
{
"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": 35.45483201266465
},
{
"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": 35.19861352747524
},
{
"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": 32.50468042734382
}
] | typescript | private static createCharacter(type: CharacterType, hp: number, coords: Coords) { |
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/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": 15.364130123737208
},
{
"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": 12.810622916763798
},
{
"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": 10.191969355007245
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " // Hitting a wall\n return true;\n }\n }\n return false;\n }\n get isHorizontal(): boolean {\n return this.from.row == this.to.row;\n }\n static floodFillAddToQueue(",
"score": 9.90428862963505
},
{
"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": 9.310833446887157
}
] | 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/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": 32.35372086556516
},
{
"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": 29.243558753170664
},
{
"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": 27.054176598185027
},
{
"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": 23.44411533480545
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " h: number;\n constructor() {\n super();\n // Logo at top\n this.logo = new PIXI.BitmapText(\"TEMPLATE\", Font.makeFontOptions(\"large\"));\n this.logo.anchor.set(0.5, 0);\n this.logo.tint = 0xffffff;\n this.addChild(this.logo);\n // Button to continue or start\n this.startButton = new Button(\"Start\", () => {",
"score": 22.352850098458227
}
] | 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/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": 59.84165498298203
},
{
"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": 52.970944197303474
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " -this.parent.position.y / Game.instance.scale\n );\n // Dungeon grid position\n let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;\n let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;\n // Grids\n // Move it\n this.dungeonGrid.position.set(dungeonX, dungeonY);\n this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);\n // Modals",
"score": 49.4972032718624
},
{
"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": 48.139421172424775
},
{
"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": 46.38865874812143
}
] | 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/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": 59.84165498298203
},
{
"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": 52.970944197303474
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " -this.parent.position.y / Game.instance.scale\n );\n // Dungeon grid position\n let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;\n let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;\n // Grids\n // Move it\n this.dungeonGrid.position.set(dungeonX, dungeonY);\n this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);\n // Modals",
"score": 49.4972032718624
},
{
"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": 48.139421172424775
},
{
"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": 46.38865874812143
}
] | 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/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": 49.01793475962204
},
{
"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": 43.55694948898527
},
{
"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": 36.87709974595939
},
{
"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": 34.40263398387136
},
{
"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": 32.890089904193694
}
] | 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/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": 59.84165498298203
},
{
"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": 52.970944197303474
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " -this.parent.position.y / Game.instance.scale\n );\n // Dungeon grid position\n let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;\n let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;\n // Grids\n // Move it\n this.dungeonGrid.position.set(dungeonX, dungeonY);\n this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);\n // Modals",
"score": 49.4972032718624
},
{
"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": 48.139421172424775
},
{
"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": 46.38865874812143
}
] | 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/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": 58.17855638338743
},
{
"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": 51.900200392555696
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.exitCoords.col == i &&\n this.exitCoords.row == j)\n )\n );\n } else {\n // Remove other edge walls (if there are any)\n for (const c of this.edgeWalls) {\n this.wallsHolder.removeChild(c);\n }\n this.edgeWalls = [];",
"score": 51.328770048238596
},
{
"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": 50.48521443027456
},
{
"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": 46.388658748121436
}
] | 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/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": 27.63673335960995
},
{
"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": 27.20291211313667
},
{
"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": 24.247449567375682
},
{
"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": 24.15317992206286
},
{
"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": 22.980448823557552
}
] | 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/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": 27.63673335960995
},
{
"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": 27.20291211313667
},
{
"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": 24.247449567375682
},
{
"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": 24.15317992206286
},
{
"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": 22.980448823557552
}
] | 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/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": 27.63673335960995
},
{
"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": 27.20291211313667
},
{
"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": 22.980448823557552
},
{
"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": 21.884157554184895
},
{
"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": 19.06537683140844
}
] | 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/Game.ts",
"retrieved_chunk": " // Remove it!\n Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();\n }\n // Add new one\n screen.alpha = 0;\n Actions.fadeIn(screen, 0.2).play();\n this.currentScreen = screen;\n this.stage.addChild(screen);\n this.notifyScreensOfSize();\n }",
"score": 34.27753895872996
},
{
"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": 28.99718832952272
},
{
"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": 25.4770200303066
},
{
"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": 24.08778087044541
},
{
"filename": "src/ui/Button.ts",
"retrieved_chunk": " -holderBackground.width / 2,\n -holderBackground.height / 2\n );\n this.addChild(holderBackground);\n this.addChild(theLabel);\n const ee = this as any;\n ee.interactive = true;\n ee.on(\"pointertap\", () => {\n this.onclick();\n });",
"score": 23.618355439962823
}
] | 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/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": 82.06183030220274
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n characters: this.serialiseCharacters(dungeonGrid.characters),\n walls: this.serialiseWalls(dungeonGrid.walls),\n edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),\n dimension: dungeonGrid.dimension,\n exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),\n exitDir: this.serialiseCoords(dungeonGrid.exitDir),\n };\n }\n private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {",
"score": 81.64632905106897
},
{
"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": 60.81578790976876
},
{
"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": 58.75055331703389
},
{
"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": 45.55964056866232
}
] | 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/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": 36.32926835588448
},
{
"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": 34.560845294422855
},
{
"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": 27.768295130558823
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 25.086630821903373
},
{
"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": 25.074151841451936
}
] | 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/save/Save.ts",
"retrieved_chunk": " return {\n characters: this.serialiseCharacters(dungeonGrid.characters),\n walls: this.serialiseWalls(dungeonGrid.walls),\n edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),\n dimension: dungeonGrid.dimension,\n exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),\n exitDir: this.serialiseCoords(dungeonGrid.exitDir),\n };\n }\n private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {",
"score": 54.54536521664817
},
{
"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": 51.84026996119401
},
{
"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": 51.109295021702486
},
{
"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": 47.21467380112831
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Move in the direction which has the lowest distance\n let targetCol = dijks.col[char.coords.col][char.coords.row];\n let targetRow = dijks.row[char.coords.col][char.coords.row];\n if (targetCol == null || targetRow == null) {\n const neighbours: Coords[] = [];\n this.addPotentialNeighbour(neighbours, char.coords, 1, 0);\n this.addPotentialNeighbour(neighbours, char.coords, 0, 1);\n this.addPotentialNeighbour(neighbours, char.coords, -1, 0);\n this.addPotentialNeighbour(neighbours, char.coords, 0, -1);\n if (neighbours.length > 0) {",
"score": 46.34580351419485
}
] | 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/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": 58.82035454759509
},
{
"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": 51.790098037569834
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 50.27169021703643
},
{
"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": 49.385631714021294
},
{
"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": 41.66670034744593
}
] | 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/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": 53.674707379695725
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let anyCoincidence = false;\n if (this.gameScreen.playerCharacter.coords.equals(c)) {\n anyCoincidence = true;\n break;\n }\n if (!anyCoincidence) {\n possibles.push(c);\n }\n }\n }",
"score": 50.159478146922375
},
{
"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": 47.27354719322234
},
{
"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": 45.85413073959585
},
{
"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": 41.58066235222089
}
] | 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/Game.ts",
"retrieved_chunk": " const absDeltaY = Math.abs(deltaY);\n const absMin = Math.min(absDeltaX, absDeltaY);\n const absMax = Math.max(absDeltaX, absDeltaY);\n // The other axis must be smaller than this to avoid a diagonal swipe\n const confusionThreshold = absMax / 2;\n if (absMin < confusionThreshold) {\n if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {\n if (absMax == absDeltaX) {\n // Right or left\n this.keydown(deltaX > 0 ? \"KeyD\" : \"KeyA\");",
"score": 54.767966260867766
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " ? Math.max(1, Math.floor(smoothScaling))\n : smoothScaling;\n this.stage.scale.set(this.scale, this.scale);\n if (this.innerBackgroundSprite) {\n if (Game.MAINTAIN_RATIO) {\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;\n } else {\n this.innerBackgroundSprite.width = resizeInfo.width;\n this.innerBackgroundSprite.height = resizeInfo.height;",
"score": 46.85933298512023
},
{
"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": 41.16173862385334
},
{
"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": 40.243430924657
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " Math.round(avgShort) +\n \"\\n\" +\n Math.round(avgLong) +\n \"\\n\";\n }\n notifyScreensOfSize() {\n // Let screens now\n for (const s of this.stage.children) {\n if (s instanceof Screen) {\n if (Game.MAINTAIN_RATIO) {",
"score": 36.85468383852013
}
] | 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": 50.60458054540061
},
{
"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": 44.46192372551066
},
{
"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": 44.08596135506871
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n characters: this.serialiseCharacters(dungeonGrid.characters),\n walls: this.serialiseWalls(dungeonGrid.walls),\n edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),\n dimension: dungeonGrid.dimension,\n exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),\n exitDir: this.serialiseCoords(dungeonGrid.exitDir),\n };\n }\n private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {",
"score": 41.63814614525564
},
{
"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": 40.86712895189217
}
] | 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": 17.715051380560194
},
{
"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": 16.662147828196243
},
{
"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": 16.379376413720976
},
{
"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": 14.950607281086272
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " // Remove it!\n Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();\n }\n // Add new one\n screen.alpha = 0;\n Actions.fadeIn(screen, 0.2).play();\n this.currentScreen = screen;\n this.stage.addChild(screen);\n this.notifyScreensOfSize();\n }",
"score": 14.629409987732718
}
] | 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/Wall.ts",
"retrieved_chunk": " const row = n[1] + dy;\n const from = new Coords(n[0], n[1]);\n // If not in bounds, don't add to Q\n if (col < 0 || row < 0) return;\n if (col >= dimension || row >= dimension) return;\n // If already flooded, don't add\n if (flood[col][row]) return;\n // If a wall blocks, don't add\n for (const w of walls) {\n if (w.blocks(from, dx, dy)) return;",
"score": 24.89596246596478
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " }\n // If the prospective blocks, don't add\n if (prospective.blocks(from, dx, dy)) return;\n Q.push([col, row]);\n }\n static floodFill(\n flood: boolean[][],\n walls: Wall[],\n prospective: Wall,\n dimension: number",
"score": 22.428298281552472
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // If there are no unvisited, we are done\n if (smallests.length == 0) break;\n // Otherwise, set current to unvisited with smallest tentative\n const randomSmallest = _.sample(smallests);\n current.set(randomSmallest[0], randomSmallest[1]);\n } while (true);\n // Return the dijkstra map for the whole grid\n return {\n distance: tentativeDistance,\n col: tentativeSourceCol,",
"score": 20.5580635477173
},
{
"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": 20.499460689783714
},
{
"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": 19.792037621914044
}
] | 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/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": 39.29711244939045
},
{
"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": 36.72791345647079
},
{
"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": 31.97196935280879
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " for (const w of walls) {\n if (w.from.equals(from) && w.to.equals(to)) {\n alreadyExists = true;\n break;\n }\n }\n if (alreadyExists) continue;\n prospective = new Wall(from, to);\n }\n // If we can't flood fill, skip!",
"score": 31.18720538933973
},
{
"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": 29.981397805187882
}
] | 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": " 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": 25.466454430529645
},
{
"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": 24.508150912747677
},
{
"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": 22.839632390843615
},
{
"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": 22.070013010996668
},
{
"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": 20.26105158565443
}
] | 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": 23.0875872706743
},
{
"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": 17.59674595266845
},
{
"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": 16.56731384873077
},
{
"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": 16.440062437697556
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " this.dimension = dimension;\n this.edgeSize = 28 * this.dimension;\n }\n get cellSize(): number {\n return this.edgeSize / this.dimension;\n }\n inBounds(col: number | Coords, row: number = null) {\n let c = 0,\n r = 0;\n if (typeof col == \"number\") {",
"score": 16.127423802279957
}
] | 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/grid/Wall.ts",
"retrieved_chunk": " ): boolean {\n for (let i = 0; i < flood.length; i++) {\n for (let j = 0; j < flood[i].length; j++) {\n flood[i][j] = false;\n }\n }\n const Q = [];\n Q.push([0, 0]);\n while (Q.length > 0) {\n const n = Q.pop();",
"score": 48.48412823573084
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " );\n }\n for (let i = 0; i < flood.length; i++) {\n for (let j = 0; j < flood[i].length; j++) {\n if (!flood[i][j]) return false;\n }\n }\n return true;\n }\n static edges(dimension: number) {",
"score": 46.10205664025096
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " }\n set hp(hp: number) {\n this._hp = hp;\n // CHANGE WHITE/REDNESS\n for (let i = 0; i < this.heartsHolder.children.length; i++) {\n const heart = this.heartsHolder.children[i];\n (heart as PIXI.Sprite).tint = (i < this._hp) ? 0xff0000 : 0xffffff;\n }\n }\n get maxHp() {",
"score": 39.12693774916108
},
{
"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": 38.31125357111041
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " }\n }\n return walls;\n }\n static randomLayout(numWalls: number, dimension: number): Wall[] {\n const walls: Wall[] = [];\n const flood: boolean[][] = [];\n for (let i = 0; i < dimension; i++) {\n const col: boolean[] = [];\n for (let j = 0; j < dimension; j++) {",
"score": 37.88705584119256
}
] | 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/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": 51.99410508319687
},
{
"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": 36.01165151957162
},
{
"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": 34.303306620323745
},
{
"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": 33.73711357739371
},
{
"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": 31.97196935280879
}
] | 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": 48.900041300603455
},
{
"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": 28.22505170011399
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.darkOverlay.alpha = 0;\n Actions.sequence(\n Actions.delay(delay),\n Actions.fadeIn(this.darkOverlay, 0.2)\n ).play();\n }\n hideDarkOverlay(delay: number = 0) {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {",
"score": 26.76786851898083
},
{
"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": 24.307204115950224
},
{
"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": 23.701917268011282
}
] | 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/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": 36.718611875811604
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Snazzy animation too, if I could handle it!\n this.nextLevel();\n } else if (moveResult.didMove) {\n this.postMove(moveResult.delay);\n } else {\n this.readyToMove = false;\n // After a delay, let the player move again\n Actions.sequence(\n Actions.delay(moveResult.delay),\n Actions.runFunc(() => {",
"score": 30.62827970683732
},
{
"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": 29.00103184441611
},
{
"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": 26.87227786308082
},
{
"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": 24.38854002598998
}
] | 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": 53.207760598876874
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " for (const w of walls) {\n if (w.from.equals(from) && w.to.equals(to)) {\n alreadyExists = true;\n break;\n }\n }\n if (alreadyExists) continue;\n prospective = new Wall(from, to);\n }\n // If we can't flood fill, skip!",
"score": 47.349771031766416
},
{
"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": 44.918969398971235
},
{
"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": 41.7041381266114
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " const row = n[1] + dy;\n const from = new Coords(n[0], n[1]);\n // If not in bounds, don't add to Q\n if (col < 0 || row < 0) return;\n if (col >= dimension || row >= dimension) return;\n // If already flooded, don't add\n if (flood[col][row]) return;\n // If a wall blocks, don't add\n for (const w of walls) {\n if (w.blocks(from, dx, dy)) return;",
"score": 32.13557622167688
}
] | 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/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": 36.70864808749756
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " return {\n characters: this.serialiseCharacters(dungeonGrid.characters),\n walls: this.serialiseWalls(dungeonGrid.walls),\n edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),\n dimension: dungeonGrid.dimension,\n exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),\n exitDir: this.serialiseCoords(dungeonGrid.exitDir),\n };\n }\n private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {",
"score": 29.09525758039797
},
{
"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": 25.930780927660916
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " }\n }\n return walls;\n }\n static randomLayout(numWalls: number, dimension: number): Wall[] {\n const walls: Wall[] = [];\n const flood: boolean[][] = [];\n for (let i = 0; i < dimension; i++) {\n const col: boolean[] = [];\n for (let j = 0; j < dimension; j++) {",
"score": 21.752543696066972
},
{
"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": 21.629548154312175
}
] | typescript | let walls: Wall[] = Wall.edges(this.dimension); |
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": 33.950463962295316
},
{
"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": 31.971969352808795
},
{
"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": 31.761850076988
},
{
"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": 31.260917468274634
},
{
"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": 27.268794473468436
}
] | typescript | character.alpha = 0; |
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/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": 43.41885445937868
},
{
"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": 29.315630967907378
},
{
"filename": "src/helpers.ts",
"retrieved_chunk": " if (\n typeof value === \"object\" &&\n value !== null &&\n \"ok\" in value &&\n \"err\" in value\n ) {\n const r = value as Result;\n return typeof r.ok === \"boolean\" && typeof r.err === \"boolean\";\n }\n return false;",
"score": 28.90278461290157
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " const c = ok({ value: 3 });\n expect(from([a, b, c])).toEqual(ok([1, 2, { value: 3 }]));\n });\n it(\"should extract all inner data if there are any ok(ok()) values\", () => {\n const a = ok(1);\n const b = ok(ok(\"yes\"));\n const c = ok(ok(ok({ value: \"no\" })));\n expect(from([a, b, c])).toEqual(ok([1, \"yes\", { value: \"no\" }]));\n });\n it(\"should return a Err result if one or more input values are Err instances\", () => {",
"score": 27.912423317777176
},
{
"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": 27.846848524554336
}
] | 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.dungeonGrid.position.y + dy\n );\n nextGrid.alpha = 0;\n Actions.parallel(\n Actions.fadeIn(nextGrid, 0.2),\n Actions.moveTo(\n nextGrid,\n this.dungeonGrid.position.x,\n this.dungeonGrid.position.y,\n 0.5",
"score": 33.236413569512365
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " }\n }\n // Centre stage\n if (Game.MAINTAIN_RATIO) {\n this.stage.position.set(\n resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,\n resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2\n );\n if (this.innerBackgroundSprite) {\n this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);",
"score": 31.50837294077651
},
{
"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": 30.61745588645128
},
{
"filename": "src/screens/game/GameOverModal.ts",
"retrieved_chunk": " this.addChild(button);\n // Clicker\n const clicker = PIXI.Sprite.from(PIXI.Texture.WHITE);\n clicker.tint = 0xff0000;\n clicker.alpha = 0;\n clicker.anchor.set(0.5, 0.5);\n clicker.width = button.width * 1.5;\n clicker.height = button.height * 2;\n clicker.position.set(button.position.x, button.position.y);\n this.addChild(clicker);",
"score": 28.487880998983517
},
{
"filename": "src/ui/Button.ts",
"retrieved_chunk": " theLabel.tint = 0;\n theLabel.anchor.set(0.5);\n theLabel.position.x = 0;\n theLabel.position.y = 0;\n this.label = theLabel;\n // Background\n const holderBackground = PIXI.Sprite.from(PIXI.Texture.WHITE);\n holderBackground.width = 200;\n holderBackground.height = 25;\n holderBackground.position.set(",
"score": 28.39228789323263
}
] | 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/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": 34.75594779121322
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " const c = ok({ value: 3 });\n expect(from([a, b, c])).toEqual(ok([1, 2, { value: 3 }]));\n });\n it(\"should extract all inner data if there are any ok(ok()) values\", () => {\n const a = ok(1);\n const b = ok(ok(\"yes\"));\n const c = ok(ok(ok({ value: \"no\" })));\n expect(from([a, b, c])).toEqual(ok([1, \"yes\", { value: \"no\" }]));\n });\n it(\"should return a Err result if one or more input values are Err instances\", () => {",
"score": 30.237664367655125
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " expect(from([err()]).err).toBeTruthy();\n expect(from([err(), ok()]).err).toBeTruthy();\n });\n it(\"should collect expose all the input values on errContext if any errors are detected\", () => {\n const a = ok(1);\n const b = err(2);\n const c = err(\"fail\");\n const result = from([a, b, c]);\n assertIsErr(result);\n expect(result.err).toBeTruthy();",
"score": 26.27241737109041
},
{
"filename": "src/helpers.ts",
"retrieved_chunk": " if (\n typeof value === \"object\" &&\n value !== null &&\n \"ok\" in value &&\n \"err\" in value\n ) {\n const r = value as Result;\n return typeof r.ok === \"boolean\" && typeof r.err === \"boolean\";\n }\n return false;",
"score": 23.66664388157906
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " return value ? ok(value) : err();\n }\n switch (typeof value) {\n case \"boolean\":\n return value ? ok(value) : err();\n case \"number\":\n return value === 0 ? err() : ok(value);\n case \"string\":\n return value === \"\" ? err() : ok(value);\n default:",
"score": 21.16445876516591
}
] | typescript | if (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/GameScreen.ts",
"retrieved_chunk": " // Snazzy animation too, if I could handle it!\n this.nextLevel();\n } else if (moveResult.didMove) {\n this.postMove(moveResult.delay);\n } else {\n this.readyToMove = false;\n // After a delay, let the player move again\n Actions.sequence(\n Actions.delay(moveResult.delay),\n Actions.runFunc(() => {",
"score": 40.52529111786171
},
{
"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": 39.1857378450176
},
{
"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": 32.88540406761032
},
{
"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": 30.020640323475014
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " this.addChild(this.heartsHolder);\n }\n get isEnemy() {\n return false;\n }\n get isPlayer() {\n return false;\n }\n get hp() {\n return this._hp;",
"score": 29.00382101760551
}
] | 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/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": 42.65309038387659
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " const c = ok({ value: 3 });\n expect(from([a, b, c])).toEqual(ok([1, 2, { value: 3 }]));\n });\n it(\"should extract all inner data if there are any ok(ok()) values\", () => {\n const a = ok(1);\n const b = ok(ok(\"yes\"));\n const c = ok(ok(ok({ value: \"no\" })));\n expect(from([a, b, c])).toEqual(ok([1, \"yes\", { value: \"no\" }]));\n });\n it(\"should return a Err result if one or more input values are Err instances\", () => {",
"score": 27.83902134229864
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " expect(from([err()]).err).toBeTruthy();\n expect(from([err(), ok()]).err).toBeTruthy();\n });\n it(\"should collect expose all the input values on errContext if any errors are detected\", () => {\n const a = ok(1);\n const b = err(2);\n const c = err(\"fail\");\n const result = from([a, b, c]);\n assertIsErr(result);\n expect(result.err).toBeTruthy();",
"score": 25.329523281995048
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " errCode: 555,\n errContext: { old: \"data\" },\n });\n // message and number\n assertResultEquals(err(e, \"super fail\", 999), {\n errMessage: \"super fail\",\n errCode: 999,\n errContext: { old: \"data\" },\n });\n // message, number and context",
"score": 21.148725250158623
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " errCode: 123,\n errMessage: \"not good\",\n errContext: { some: \"data\" },\n errException: e,\n },\n );\n });\n it(\"should allow the entire object as data to be passed in but use the exception's error message if not overridden\", () => {\n const e = new Error(\"error123: fail\");\n assertResultEquals(",
"score": 20.930069831958097
}
] | 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": 94.19064424140826
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type Result<\n D extends unknown = unknown,\n C extends unknown = number | string,\n> = Ok<D> | Err<C>;\nexport interface Ok<D extends unknown = null> {\n ok: true;\n err: false;\n data: D;\n}\nexport interface Err<",
"score": 42.037122149677344
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " T extends { ok: false; errCode?: C } | { err: true; errCode?: C },\n>(value: T): Err<T[\"errCode\"]>;\nexport function toResult<D extends false | \"\" | 0 | null | undefined>(\n value: D,\n): Err;\nexport function toResult<\n D extends true | unknown[] | Record<string, unknown> | number | string,\n>(value: D): Ok<D>;\nexport function toResult(value: unknown): Result {\n if (value === undefined || value === null) {",
"score": 38.7363594028274
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": "import type { Err, Ok, Result } from \"./api\";\nimport { err } from \"./err\";\nimport { ok } from \"./ok\";\nimport { isJsError } from \"./shared\";\nexport function toResult<\n D extends unknown,\n T extends { ok: true; data?: D } | { err: false; data?: D },\n>(value: T): Ok<T>;\nexport function toResult<\n C extends unknown,",
"score": 23.359727793097576
},
{
"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": 18.635311114198004
}
] | 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/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": 30.2491537445172
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " const c = ok({ value: 3 });\n expect(from([a, b, c])).toEqual(ok([1, 2, { value: 3 }]));\n });\n it(\"should extract all inner data if there are any ok(ok()) values\", () => {\n const a = ok(1);\n const b = ok(ok(\"yes\"));\n const c = ok(ok(ok({ value: \"no\" })));\n expect(from([a, b, c])).toEqual(ok([1, \"yes\", { value: \"no\" }]));\n });\n it(\"should return a Err result if one or more input values are Err instances\", () => {",
"score": 28.44497443913266
},
{
"filename": "src/from.spec.ts",
"retrieved_chunk": " expect(from([err()]).err).toBeTruthy();\n expect(from([err(), ok()]).err).toBeTruthy();\n });\n it(\"should collect expose all the input values on errContext if any errors are detected\", () => {\n const a = ok(1);\n const b = err(2);\n const c = err(\"fail\");\n const result = from([a, b, c]);\n assertIsErr(result);\n expect(result.err).toBeTruthy();",
"score": 24.768197851665136
},
{
"filename": "src/helpers.ts",
"retrieved_chunk": " if (\n typeof value === \"object\" &&\n value !== null &&\n \"ok\" in value &&\n \"err\" in value\n ) {\n const r = value as Result;\n return typeof r.ok === \"boolean\" && typeof r.err === \"boolean\";\n }\n return false;",
"score": 23.66664388157906
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " return value ? ok(value) : err();\n }\n switch (typeof value) {\n case \"boolean\":\n return value ? ok(value) : err();\n case \"number\":\n return value === 0 ? err() : ok(value);\n case \"string\":\n return value === \"\" ? err() : ok(value);\n default:",
"score": 21.16445876516591
}
] | typescript | 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/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": 51.31599705204205
},
{
"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": 33.242289974272275
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " errCode: 555,\n errContext: { old: \"data\" },\n });\n // message and number\n assertResultEquals(err(e, \"super fail\", 999), {\n errMessage: \"super fail\",\n errCode: 999,\n errContext: { old: \"data\" },\n });\n // message, number and context",
"score": 31.786403651253735
},
{
"filename": "src/helpers.ts",
"retrieved_chunk": " if (\n typeof value === \"object\" &&\n value !== null &&\n \"ok\" in value &&\n \"err\" in value\n ) {\n const r = value as Result;\n return typeof r.ok === \"boolean\" && typeof r.err === \"boolean\";\n }\n return false;",
"score": 29.982721121354388
},
{
"filename": "src/err.spec.ts",
"retrieved_chunk": " errMessage: \"fail\",\n });\n });\n it(\"should return an Err result with a string/number/context\", () => {\n const ctx = { some: \"data\" };\n assertResultEquals(err(\"fail\", 123, ctx), {\n errCode: 123,\n errMessage: \"fail\",\n errContext: ctx,\n });",
"score": 28.491633136730155
}
] | 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": " ok: false,\n err: true,\n errCode: code,\n errContext: context,\n errMessage: message,\n errException: exception,\n };\n}\nfunction isValidString(value: unknown): value is string {\n return typeof value === \"string\" && value.length !== 0;",
"score": 9.10716451510564
},
{
"filename": "src/helpers.spec.ts",
"retrieved_chunk": " });\n it(\"should return true for an Err result\", () => {\n expect(isResult(err())).toBeTruthy();\n });\n it(\"should return true for any non Result input value\", () => {\n expect(isResult(null)).toBeFalsy();\n expect(isResult(undefined)).toBeFalsy();\n expect(isResult(false)).toBeFalsy();\n expect(isResult(true)).toBeFalsy();\n expect(isResult({})).toBeFalsy();",
"score": 8.979911001526078
},
{
"filename": "src/helpers.ts",
"retrieved_chunk": " if (\n typeof value === \"object\" &&\n value !== null &&\n \"ok\" in value &&\n \"err\" in value\n ) {\n const r = value as Result;\n return typeof r.ok === \"boolean\" && typeof r.err === \"boolean\";\n }\n return false;",
"score": 8.412835951306887
},
{
"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": 7.902637624623817
},
{
"filename": "src/helpers.spec.ts",
"retrieved_chunk": " expect(isOkResult(err())).toBeFalsy();\n });\n it(\"should return true for any non Result input value\", () => {\n expect(isOkResult(null)).toBeFalsy();\n expect(isOkResult(undefined)).toBeFalsy();\n expect(isOkResult(false)).toBeFalsy();\n expect(isOkResult(true)).toBeFalsy();\n expect(isOkResult({})).toBeFalsy();\n expect(isOkResult([])).toBeFalsy();\n expect(isOkResult(0)).toBeFalsy();",
"score": 7.812454733251857
}
] | 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": " * 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": 85.00718525139757
},
{
"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": 65.78916985838238
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " }\n /**\n * Process a phrase of a given locale, calculating the sentiment analysis.\n * @param {String} locale Locale of the phrase.\n * @param {String} phrase Phrase to calculate the sentiment.\n * @returns {Promise Object} Promise sentiment analysis of the phrase.\n */\n async process(locale: string, phrase: string) {\n const sentiment = await this.analyzer.getSentiment(\n phrase,",
"score": 33.270549366897285
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " }\n /**\n * Process an utterance using the NLP manager. This is done using a given context\n * as the context object.\n * @param {Object} srcContext Source context\n * @param {String} locale Locale of the utterance.\n * @param {String} utterance Locale of the utterance.\n */\n public async process(\n srcContext: Record<string, unknown>,",
"score": 33.0370750878397
},
{
"filename": "src/recognizer/index.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport Recognizer from './recognizer';\nimport ConversationContext from './conversation-context'\nimport MemoryConversationContext from './memory-conversation-context'\nexport {\n Recognizer,\n ConversationContext,\n MemoryConversationContext,\n};",
"score": 27.253170397700334
}
] | 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/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": 31.691653331603426
},
{
"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": 26.760031756703082
},
{
"filename": "src/types/@nlpjs/xtables.d.ts",
"retrieved_chunk": " clearRows(): void;\n }\n export class XDoc {\n tables: XDocTable[];\n read(fileName: string): void;\n getTable(name: string): XDocTable;\n }\n}",
"score": 22.624048182328636
},
{
"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": 20.26001371006864
},
{
"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": 19.793316042585314
}
] | 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/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": 62.29615270342009
},
{
"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": 60.35731523513401
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { containerBootstrap } from '@nlpjs/core-loader';\nimport { LangAll } from '@nlpjs/lang-all';\nimport { NluNeural } from '@nlpjs/nlu';\nclass BrainNLU {\n private container: any;\n private nlu: NluNeural | undefined;\n private readonly corpus: any[];\n private readonly settings: any;",
"score": 47.551856595461054
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport SentimentAnalyzer from './sentiment-analyzer';\n/**\n * Class for the sentiment analysis manager, able to manage\n * several languages at the same time.\n */\nclass SentimentManager {\n private readonly settings: any\n private languages: {}",
"score": 44.67913051566815
},
{
"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": 42.768761341710444
}
] | 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/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": 47.507766191843544
},
{
"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": 41.20744901488014
},
{
"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": 28.35500550512026
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " private analyzer: SentimentAnalyzer\n /**\n * Constructor of the class.\n */\n constructor(settings?: any) {\n this.settings = settings || {};\n this.languages = {};\n this.analyzer = new SentimentAnalyzer();\n }\n addLanguage() {",
"score": 23.76214134517255
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport SentimentAnalyzer from './sentiment-analyzer';\n/**\n * Class for the sentiment analysis manager, able to manage\n * several languages at the same time.\n */\nclass SentimentManager {\n private readonly settings: any\n private languages: {}",
"score": 19.197016098177233
}
] | 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/xtables.d.ts",
"retrieved_chunk": " export class XTable {\n static CSV: string;\n static TSV: string;\n constructor();\n load(data: string, type?: string): void;\n save(type?: string): string;\n getTable(name: string): XTable;\n getRows(): Record<string, string>[];\n addRow(row: Record<string, string>): void;\n addRows(rows: Record<string, string>[]): void;",
"score": 51.04120019140281
},
{
"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": 27.637676072169278
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " evaluator.evaluate(condition, context) === true\n );\n }\n return true;\n }\n findAllAnswers(locale?: string, intent?: string, context?: any): {answer: string, opts: string}[] | any {\n if (typeof locale === 'string') {\n const found = super.findAllAnswers(locale, intent, context);\n const filtered = super.filterAnswers(found);\n return filtered.answers.map((x: {answer: string, opts: string}) => ({",
"score": 25.211389177794874
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n /**\n * Load NLP manager information from a string.\n * @param {String|Object} data JSON string or object to load NLP manager information from.\n */\n import(data: string | Record<string, unknown>): void {\n const clone = typeof data === 'string' ? JSON.parse(data) : data;\n this.fromObj(clone);\n }\n /**",
"score": 23.793125858593775
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " * @param srcFileName\n */\n load(srcFileName?: string): void {\n const fileName = srcFileName || 'model.nlp';\n const data = fs.readFileSync(fileName, 'utf8');\n this.import(data);\n }\n /**\n * Load the NLP manager information from an Excel file.\n * @param fileName",
"score": 18.448320301646724
}
] | 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": 84.49829361212151
},
{
"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": 66.790157197331
},
{
"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": 56.29349215200405
},
{
"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": 53.03708583803492
},
{
"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": 38.88691031595479
}
] | 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/types/@nlpjs/xtables.d.ts",
"retrieved_chunk": " export class XTable {\n static CSV: string;\n static TSV: string;\n constructor();\n load(data: string, type?: string): void;\n save(type?: string): string;\n getTable(name: string): XTable;\n getRows(): Record<string, string>[];\n addRow(row: Record<string, string>): void;\n addRows(rows: Record<string, string>[]): void;",
"score": 66.1160411971247
},
{
"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": 28.02796407034638
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n /**\n * Load NLP manager information from a string.\n * @param {String|Object} data JSON string or object to load NLP manager information from.\n */\n import(data: string | Record<string, unknown>): void {\n const clone = typeof data === 'string' ? JSON.parse(data) : data;\n this.fromObj(clone);\n }\n /**",
"score": 26.32981992605972
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " evaluator.evaluate(condition, context) === true\n );\n }\n return true;\n }\n findAllAnswers(locale?: string, intent?: string, context?: any): {answer: string, opts: string}[] | any {\n if (typeof locale === 'string') {\n const found = super.findAllAnswers(locale, intent, context);\n const filtered = super.filterAnswers(found);\n return filtered.answers.map((x: {answer: string, opts: string}) => ({",
"score": 23.72453841433416
},
{
"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": 22.36850543506081
}
] | 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": " * 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": 85.00718525139757
},
{
"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": 65.78916985838238
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " }\n /**\n * Process a phrase of a given locale, calculating the sentiment analysis.\n * @param {String} locale Locale of the phrase.\n * @param {String} phrase Phrase to calculate the sentiment.\n * @returns {Promise Object} Promise sentiment analysis of the phrase.\n */\n async process(locale: string, phrase: string) {\n const sentiment = await this.analyzer.getSentiment(\n phrase,",
"score": 33.270549366897285
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " }\n /**\n * Process an utterance using the NLP manager. This is done using a given context\n * as the context object.\n * @param {Object} srcContext Source context\n * @param {String} locale Locale of the utterance.\n * @param {String} utterance Locale of the utterance.\n */\n public async process(\n srcContext: Record<string, unknown>,",
"score": 33.0370750878397
},
{
"filename": "src/recognizer/index.ts",
"retrieved_chunk": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport Recognizer from './recognizer';\nimport ConversationContext from './conversation-context'\nimport MemoryConversationContext from './memory-conversation-context'\nexport {\n Recognizer,\n ConversationContext,\n MemoryConversationContext,\n};",
"score": 27.253170397700334
}
] | 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/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": 95.10826831892012
},
{
"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": 94.71438776312534
},
{
"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": 92.2366918721896
},
{
"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": 83.41440843882889
},
{
"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": 56.63531651812295
}
] | typescript | if (session?._activity?.conversation) { |
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": 81.67616863278737
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " }\n removeAnswer(locale: string, intent: string, answer: any, opts?: any): void {\n return this.remove(locale, intent, answer, opts);\n }\n isValid(condition: string | undefined, context: any): boolean {\n const evaluator = this.container.get('Evaluator');\n if (evaluator) {\n return (\n !condition ||\n condition === '' ||",
"score": 81.27923139660723
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " }\n return {\n score: sentiment.score,\n comparative: sentiment.average,\n vote,\n numWords: sentiment.numWords,\n numHits: sentiment.numHits,\n type: sentiment.type,\n language: sentiment.locale,\n };",
"score": 80.26576740320075
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " evaluator.evaluate(condition, context) === true\n );\n }\n return true;\n }\n findAllAnswers(locale?: string, intent?: string, context?: any): {answer: string, opts: string}[] | any {\n if (typeof locale === 'string') {\n const found = super.findAllAnswers(locale, intent, context);\n const filtered = super.filterAnswers(found);\n return filtered.answers.map((x: {answer: string, opts: string}) => ({",
"score": 78.70758734351854
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " // do nothing\n }\n translate(sentiment: {score: number, average: number, type: string, numHits: number, numWords: number, locale: string}) {\n let vote;\n if (sentiment.score > 0) {\n vote = 'positive';\n } else if (sentiment.score < 0) {\n vote = 'negative';\n } else {\n vote = 'neutral';",
"score": 78.55974042228917
}
] | typescript | .translate(sentiment.sentiment); |
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": 9.658877754809476
},
{
"filename": "src/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {",
"score": 4.733507846183725
},
{
"filename": "src/types/general.ts",
"retrieved_chunk": " params: {\n API_KEY: string\n [key: string]: any\n }\n}\nexport { ExporioMiddlewareOptions, RequestJson }",
"score": 2.690837462715257
},
{
"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": 2.195530015750635
},
{
"filename": "src/htmlRewriterClasses/AppendGlobalCode.ts",
"retrieved_chunk": "class AppendGlobalCode {\n htmlTag?: string\n content: string\n constructor(htmlTag: string, content: string) {\n this.htmlTag = htmlTag\n this.content = content\n }\n element(element: Element) {\n const contentWithTags = `<${this.htmlTag}>${this.content}</${this.htmlTag}>`\n element.append(contentWithTags, { html: true })",
"score": 1.7322915288081508
}
] | typescript | const buildRequestJson = (c: Context, apiKey: string): RequestJson => { |
/*
* 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": 72.76968230782198
},
{
"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": 53.37015330459982
},
{
"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": 44.275218348234425
},
{
"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": 34.9055386164178
},
{
"filename": "src/nlp/nlp-util.ts",
"retrieved_chunk": " zh: false,\n };\n /**\n * Given a locale, get the 2 character one.\n * @param {String} locale Locale of the language.\n * @returns {String} Locale in 2 character length.\n */\n static getTruncatedLocale(locale: string): string | undefined {\n return locale ? locale.substring(0, 2).toLowerCase() : undefined;\n }",
"score": 34.2040143705603
}
] | typescript | public getConversationId(session: Session): string | undefined { |
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/xtables.d.ts",
"retrieved_chunk": " export class XTable {\n static CSV: string;\n static TSV: string;\n constructor();\n load(data: string, type?: string): void;\n save(type?: string): string;\n getTable(name: string): XTable;\n getRows(): Record<string, string>[];\n addRow(row: Record<string, string>): void;\n addRows(rows: Record<string, string>[]): void;",
"score": 107.1073473847129
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " }\n /**\n * Load NLP manager information from a string.\n * @param {String|Object} data JSON string or object to load NLP manager information from.\n */\n import(data: string | Record<string, unknown>): void {\n const clone = typeof data === 'string' ? JSON.parse(data) : data;\n this.fromObj(clone);\n }\n /**",
"score": 40.83384114838016
},
{
"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": 35.97213096769996
},
{
"filename": "src/types/@nlpjs/nlg.d.ts",
"retrieved_chunk": " removeAnswer(locale: string, intent: string, answer: string, opts?: Record<string, any>): void;\n isValid(condition: string, context?: Record<string, any>): boolean;\n container: Container;\n }\n interface ActionManagerSettings {\n container?: Container;\n tag?: string;\n }\n interface ActionBundle {\n action: string;",
"score": 33.632566810687955
},
{
"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": 31.040219555976435
}
] | typescript | this.manager.addAnswer(row.language, row.intent, row.response, row.condition); |
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": 18.870492957003744
},
{
"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": 12.37042256077587
},
{
"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": 12.04464424923945
},
{
"filename": "src/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {",
"score": 4.2635031777414945
},
{
"filename": "src/htmlRewriterClasses/AppendGlobalCode.ts",
"retrieved_chunk": "class AppendGlobalCode {\n htmlTag?: string\n content: string\n constructor(htmlTag: string, content: string) {\n this.htmlTag = htmlTag\n this.content = content\n }\n element(element: Element) {\n const contentWithTags = `<${this.htmlTag}>${this.content}</${this.htmlTag}>`\n element.append(contentWithTags, { html: true })",
"score": 3.4645830576163017
}
] | typescript | const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
} |
/*
* 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": 100.60990556789184
},
{
"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": 76.38686728402854
},
{
"filename": "src/sentiment/sentiment-manager.ts",
"retrieved_chunk": " }\n /**\n * Process a phrase of a given locale, calculating the sentiment analysis.\n * @param {String} locale Locale of the phrase.\n * @param {String} phrase Phrase to calculate the sentiment.\n * @returns {Promise Object} Promise sentiment analysis of the phrase.\n */\n async process(locale: string, phrase: string) {\n const sentiment = await this.analyzer.getSentiment(\n phrase,",
"score": 37.025253439638384
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " }\n /**\n * Process an utterance using the NLP manager. This is done using a given context\n * as the context object.\n * @param {Object} srcContext Source context\n * @param {String} locale Locale of the utterance.\n * @param {String} utterance Locale of the utterance.\n */\n public async process(\n srcContext: Record<string, unknown>,",
"score": 33.0370750878397
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " return response;\n }\n /**\n * Given an utterance and the locale, returns the recognition of the utterance.\n * @param {String} utterance Utterance to be recognized.\n * @param {String} model Model of the utterance.\n * @param {Function} cb Callback Function.\n */\n public async recognizeUtterance(utterance: string, model: {locale: string}, cb: Function): Promise<any> {\n const response = await this.process(",
"score": 28.834464838375954
}
] | typescript | conversationId = this.getConversationId(session); |
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": 25.497620640319226
},
{
"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": 17.782120473311622
},
{
"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": 15.431263879197935
},
{
"filename": "src/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": " const styleProperties = currentStyleAttribute.split(';')\n styleProperties.forEach((property) => {\n if (property.includes(`${this.propertyName}:`)) {\n currentStyleAttribute = currentStyleAttribute.replace(\n property,\n `${this.propertyName}:${this.propertyValue}`\n )\n }\n })\n } else {",
"score": 8.99701102392522
},
{
"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": 8.560028988661875
}
] | typescript | instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.