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 { validators, x as xPointsRaw, questions } from "./initialData.json"
import type { Pair, ScoredValidator, ValidatorData } from "./types"
import { linearInterpolation } from "./linearInterpolation"
type DataPoints = [Array<number>, Array<number>, Array<number>, Array<number>]
function getValidatorDataFromIdx(idx: number): ValidatorData {
const [votes, clusterSize, commission, avgEraPoints, selfStake] =
validators[idx]
return { votes, clusterSize, commission, avgEraPoints, selfStake }
}
const add = (a: number, b: number) => a + b
export function getPair(id: number): Pair {
const [questionIdxs, quality] = questions[id] as [
[number, number] | string,
number,
]
return {
id,
pair: Array.isArray(questionIdxs)
? {
a: getValidatorDataFromIdx(questionIdxs[0]),
b: getValidatorDataFromIdx(questionIdxs[1]),
}
: null,
quality: quality === -1 ? 0 : Math.max(0.0001, quality) / 0.75,
}
}
export const maxQuestionsIdx = questions.length - 1
function getScoreFunctionForQuestionId(yPoints: DataPoints) {
const xPoints = xPointsRaw as DataPoints
const pointsByField = yPoints.map((ys, idxField) =>
ys.map((y, idx) => ({ y, x: xPoints[idxField][idx] })),
)
const fns = pointsByField.map(linearInterpolation)
return (validator: ValidatorData) =>
Object.values(validator)
| .map((val, idx) => fns[idx](val))
.reduce(add)
} |
const sortingDataPromise = import("./sortingData.json").then(
(mod) => mod.default,
) as Promise<Array<DataPoints>>
const validatorsP = import("./validators").then((x) => x.validators)
export async function ranking(
questionId: number,
): Promise<Array<ScoredValidator>> {
const [sortingData, validators] = await Promise.all([
sortingDataPromise,
validatorsP,
])
const getScore = getScoreFunctionForQuestionId(sortingData[questionId])
return Object.entries(validators)
.map(([address, validator]) => ({
address,
score: getScore(validator),
...validator,
}))
.sort((a, b) => b.score - a.score)
}
| src/api/api.ts | w3f-validator-selection-tool-e904b57 | [
{
"filename": "src/api/validators/getPoints.ts",
"retrieved_chunk": " }))\n return validators.map((validator) => {\n return Math.round(\n allEraPointsWithAvg\n .map((era) => {\n const points = era.pointsPerValidator.has(validator)\n ? era.pointsPerValidator.get(validator)!\n : era.avgPoints\n return points * era.avgMultiplier\n })",
"score": 0.8074362277984619
},
{
"filename": "src/api/linearInterpolation.ts",
"retrieved_chunk": " return diff > 0\n ? binarySearch(target, sortedValues, mid, toIdx)\n : binarySearch(target, sortedValues, fromIdx, mid)\n}\nexport const linearInterpolation = (\n sortedPoints: Array<{ x: number; y: number }>,\n): ((x: number) => number) => {\n const sortedX = sortedPoints.map(({ x }) => x)\n const findLimits = (x: number): number | [number, number] => {\n if (x <= sortedX[0]) return 0",
"score": 0.7965865135192871
},
{
"filename": "src/api/validators/getCommissions.ts",
"retrieved_chunk": "import { getStakingValidators } from \"./chain\"\nexport const getComissions = (validators: string[]) =>\n Promise.all(validators.map(getStakingValidators)).then((validators) =>\n validators.map(\n (v) => v && Math.round((v.commission as number) / 1_000) / 10_000,\n ),\n )",
"score": 0.7872140407562256
},
{
"filename": "src/api/validators/getPoints.ts",
"retrieved_chunk": " let totalScorers = 0\n const allEraPointsWithAvg = allEraPoints\n .map((eraPoints) => {\n const nScorersInEra = eraPoints!.individual.length\n totalScorers += nScorersInEra\n const avgPoints =\n eraPoints!.individual.reduce((a, b) => a + b.points, 0) / nScorersInEra\n const pointsPerValidator = new Map(\n eraPoints!.individual.map((x) => [x.account, x.points] as const),\n )",
"score": 0.7740141749382019
},
{
"filename": "src/api/linearInterpolation.ts",
"retrieved_chunk": " const lastIdx = sortedX.length - 1\n if (x >= sortedX[lastIdx]) return lastIdx\n return binarySearch(x, sortedX, 0, lastIdx)\n }\n return (x: number) => {\n const limits = findLimits(x)\n if (!Array.isArray(limits)) return sortedPoints[limits].y\n const [fromIdx, toIdx] = limits\n const yDelta = sortedPoints[toIdx].y - sortedPoints[fromIdx].y\n const xDelta = sortedPoints[toIdx].x - sortedPoints[fromIdx].x",
"score": 0.7546843886375427
}
] | typescript | .map((val, idx) => fns[idx](val))
.reduce(add)
} |
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": 0.9171918034553528
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8677249550819397
},
{
"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": 0.8630054593086243
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " }\n const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =\n getLabelFromAriaAttribute({\n attributeName,\n container,\n node,\n });\n if (labelFromAriaAttribute) {\n labels[attributeName] = {\n label: labelFromAriaAttribute,",
"score": 0.8569773435592651
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": "export const getLabelFromHtmlEquivalentAttribute = ({\n attributeName,\n container,\n node,\n}: {\n attributeName: string;\n container: Node;\n node: HTMLElement;\n}) => {\n const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];",
"score": 0.8552793264389038
}
] | typescript | childNode = getNodeByIdRef({ container, idRef }); |
import { getIdRefsByAttribute } from "./getIdRefsByAttribute";
import { getNodeAccessibilityData } from "./getNodeAccessibilityData";
import { getNodeByIdRef } from "./getNodeByIdRef";
import { HTMLElementWithValue } from "./getNodeAccessibilityData/getAccessibleValue";
import { isElement } from "./isElement";
import { isInaccessible } from "dom-accessibility-api";
export interface AccessibilityNode {
accessibleAttributeLabels: string[];
accessibleDescription: string;
accessibleName: string;
accessibleValue: string;
allowedAccessibilityChildRoles: string[][];
alternateReadingOrderParents: Node[];
childrenPresentational: boolean;
node: Node;
parent: Node | null;
role: string;
spokenRole: string;
}
interface AccessibilityNodeTree extends AccessibilityNode {
children: AccessibilityNodeTree[];
}
interface AccessibilityContext {
alternateReadingOrderMap: Map<Node, Set<Node>>;
container: Node;
ownedNodes: Set<Node>;
visitedNodes: Set<Node>;
}
function addAlternateReadingOrderNodes(
node: Element,
alternateReadingOrderMap: Map<Node, Set<Node>>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-flowto",
node,
});
idRefs.forEach((idRef) => {
const childNode = getNodeByIdRef({ container, idRef });
if (!childNode) {
return;
}
const currentParentNodes =
alternateReadingOrderMap.get(childNode) ?? new Set<Node>();
currentParentNodes.add(node);
alternateReadingOrderMap.set(childNode, currentParentNodes);
});
}
function mapAlternateReadingOrder(node: Node) {
const alternateReadingOrderMap = new Map<Node, Set<Node>>();
if (!isElement(node)) {
return alternateReadingOrderMap;
}
node
.querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
);
return alternateReadingOrderMap;
}
function addOwnedNodes(
node: Element,
ownedNodes: Set<Node>,
container: Element
) {
const idRefs = getIdRefsByAttribute({
attributeName: "aria-owns",
node,
});
idRefs.forEach((idRef) => {
const ownedNode = getNodeByIdRef({ container, idRef });
if (!!ownedNode && !ownedNodes.has(ownedNode)) {
ownedNodes.add(ownedNode);
}
});
}
function getAllOwnedNodes(node: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node)) {
return ownedNodes;
}
node
.querySelectorAll("[aria-owns]")
.forEach((owningNode) => addOwnedNodes(owningNode, ownedNodes, node));
return ownedNodes;
}
function getOwnedNodes(node: Node, container: Node) {
const ownedNodes = new Set<Node>();
if (!isElement(node) || !isElement(container)) {
return ownedNodes;
}
addOwnedNodes(node, ownedNodes, container);
return ownedNodes;
}
function isHiddenFromAccessibilityTree(node: Node) {
if (!node) {
return true;
}
if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {
return false;
}
return !isElement(node) || isInaccessible(node);
}
function shouldIgnoreChildren(tree: AccessibilityNodeTree) {
const { accessibleName, node } = tree;
if (!accessibleName) {
return false;
}
return (
// TODO: improve comparison on whether the children are superfluous
// to include.
accessibleName ===
(
node.textContent ||
`${(node as HTMLElementWithValue).value}` ||
""
)?.trim()
);
}
function flattenTree(tree: AccessibilityNodeTree): AccessibilityNode[] {
const { children, ...treeNode } = tree;
const isAnnounced =
!!treeNode.accessibleName ||
!!treeNode.accessibleDescription ||
treeNode.accessibleAttributeLabels.length > 0 ||
!!treeNode.spokenRole;
const ignoreChildren = shouldIgnoreChildren(tree);
const flattenedTree = ignoreChildren
? []
: [...children.flatMap((child) => flattenTree(child))];
const isRoleContainer =
!!flattenedTree.length && !ignoreChildren && !!treeNode.spokenRole;
if (isAnnounced) {
flattenedTree.unshift(treeNode);
}
if (isRoleContainer) {
flattenedTree.push({
accessibleAttributeLabels: treeNode.accessibleAttributeLabels,
accessibleDescription: treeNode.accessibleDescription,
accessibleName: treeNode.accessibleName,
accessibleValue: treeNode.accessibleValue,
allowedAccessibilityChildRoles: treeNode.allowedAccessibilityChildRoles,
alternateReadingOrderParents: treeNode.alternateReadingOrderParents,
childrenPresentational: treeNode.childrenPresentational,
node: treeNode.node,
parent: treeNode.parent,
role: treeNode.role,
spokenRole: `end of ${treeNode.spokenRole}`,
});
}
return flattenedTree;
}
function growTree(
node: Node,
tree: AccessibilityNodeTree,
{
alternateReadingOrderMap,
container,
ownedNodes,
visitedNodes,
}: AccessibilityContext
): AccessibilityNodeTree {
/**
* Authors MUST NOT create circular references with aria-owns. In the case of
* authoring error with aria-owns, the user agent MAY ignore some aria-owns
* element references in order to build a consistent model of the content.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
if (visitedNodes.has(node)) {
return tree;
}
visitedNodes.add(node);
node.childNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
// REF: https://github.com/w3c/aria/issues/1817#issuecomment-1261602357
if (ownedNodes.has(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
| } = getNodeAccessibilityData({ |
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
/**
* If an element has both aria-owns and DOM children then the order of the
* child elements with respect to the parent/child relationship is the DOM
* children first, then the elements referenced in aria-owns. If the author
* intends that the DOM children are not first, then list the DOM children in
* aria-owns in the desired order. Authors SHOULD NOT use aria-owns as a
* replacement for the DOM hierarchy. If the relationship is represented in
* the DOM, do not use aria-owns.
*
* REF: https://w3c.github.io/aria/#aria-owns
*/
const ownedChildNodes = getOwnedNodes(node, container);
ownedChildNodes.forEach((childNode) => {
if (isHiddenFromAccessibilityTree(childNode)) {
return;
}
const alternateReadingOrderParents = alternateReadingOrderMap.has(childNode)
? Array.from(alternateReadingOrderMap.get(childNode))
: [];
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,
alternateReadingOrderParents,
container,
node: childNode,
inheritedImplicitPresentational: tree.childrenPresentational,
});
tree.children.push(
growTree(
childNode,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents,
children: [],
childrenPresentational,
node: childNode,
parent: node,
role,
spokenRole,
},
{ alternateReadingOrderMap, container, ownedNodes, visitedNodes }
)
);
});
return tree;
}
export function createAccessibilityTree(node: Node) {
if (isHiddenFromAccessibilityTree(node)) {
return [];
}
const alternateReadingOrderMap = mapAlternateReadingOrder(node);
const ownedNodes = getAllOwnedNodes(node);
const visitedNodes = new Set<Node>();
const {
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
} = getNodeAccessibilityData({
allowedAccessibilityRoles: [],
alternateReadingOrderParents: [],
container: node,
node,
inheritedImplicitPresentational: false,
});
const tree = growTree(
node,
{
accessibleAttributeLabels,
accessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
alternateReadingOrderParents: [],
children: [],
childrenPresentational,
node,
parent: null,
role,
spokenRole,
},
{
alternateReadingOrderMap,
container: node,
ownedNodes,
visitedNodes,
}
);
return flattenTree(tree);
}
| src/createAccessibilityTree.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " const { explicitRole, implicitRole, role } = getRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node,\n });\n const accessibleAttributeLabels = getAccessibleAttributeLabels({\n accessibleValue,\n alternateReadingOrderParents,\n container,",
"score": 0.8941531181335449
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " accessibleAttributeLabels,\n accessibleDescription: amendedAccessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n };\n}",
"score": 0.8825515508651733
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8797132968902588
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " }\n }\n return role;\n};\nexport function getNodeAccessibilityData({\n allowedAccessibilityRoles,\n alternateReadingOrderParents,\n container,\n inheritedImplicitPresentational,\n node,",
"score": 0.8565380573272705
},
{
"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": 0.8236227035522461
}
] | 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/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8890931010246277
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.8871867656707764
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " alternateReadingOrderMap: Map<Node, Set<Node>>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-flowto\",\n node,\n });\n idRefs.forEach((idRef) => {\n const childNode = getNodeByIdRef({ container, idRef });\n if (!childNode) {",
"score": 0.8797985315322876
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.8687824010848999
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8569492101669312
}
] | 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/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "].join(\", \");\nfunction isFocusable(node: HTMLElement) {\n return node.matches(FOCUSABLE_SELECTOR);\n}\nfunction hasGlobalStateOrProperty(node: HTMLElement) {\n return globalStatesAndProperties.some((global) => node.hasAttribute(global));\n}\nfunction getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,",
"score": 0.771440863609314
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n addOwnedNodes(node, ownedNodes, container);\n return ownedNodes;\n}\nfunction isHiddenFromAccessibilityTree(node: Node) {\n if (!node) {\n return true;\n }\n if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {\n return false;",
"score": 0.7595176696777344
},
{
"filename": "src/commands/getElementNode.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nimport { isElement } from \"../isElement\";\nexport function getElementNode(accessibilityNode: AccessibilityNode) {\n const { node } = accessibilityNode;\n if (node && isElement(node)) {\n return node;\n }\n return accessibilityNode.parent;\n}",
"score": 0.7553853988647461
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.748725414276123
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.742485761642456
}
] | typescript | const spokenPhrase = getSpokenPhrase(accessibilityNode); |
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
// REF: https://www.w3.org/TR/html-aria/#docconformance-attr
const ariaToHTMLAttributeMapping: Record<
string,
Array<{ name: string; negative?: boolean }>
> = {
"aria-checked": [{ name: "checked" }],
"aria-disabled": [{ name: "disabled" }],
// "aria-hidden": [{ name: "hidden" }],
"aria-placeholder": [{ name: "placeholder" }],
"aria-valuemax": [{ name: "max" }],
"aria-valuemin": [{ name: "min" }],
"aria-readonly": [
{ name: "readonly" },
{ name: "contenteditable", negative: true },
],
"aria-required": [{ name: "required" }],
"aria-colspan": [{ name: "colspan" }],
"aria-rowspan": [{ name: "rowspan" }],
};
export const getLabelFromHtmlEquivalentAttribute = ({
attributeName,
container,
node,
}: {
attributeName: string;
container: Node;
node: HTMLElement;
}) => {
const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];
if (!htmlAttribute?.length) {
return { label: "", value: "" };
}
for (const { name, negative = false } of htmlAttribute) {
const attributeValue = node.getAttribute(name);
const label | = mapAttributeNameAndValueToLabel({ |
attributeName,
attributeValue,
container,
negative,
});
if (label) {
return { label, value: attributeValue };
}
}
return { label: "", value: "" };
};
| src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.905383825302124
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.8903006315231323
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.8694416880607605
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.868389368057251
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " }\n const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =\n getLabelFromAriaAttribute({\n attributeName,\n container,\n node,\n });\n if (labelFromAriaAttribute) {\n labels[attributeName] = {\n label: labelFromAriaAttribute,",
"score": 0.8668642640113831
}
] | 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/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8937003016471863
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.8786908388137817
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.8617070317268372
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8507423400878906
},
{
"filename": "src/getNodeAccessibilityData/index.ts",
"retrieved_chunk": " const { explicitRole, implicitRole, role } = getRole({\n accessibleName,\n allowedAccessibilityRoles,\n inheritedImplicitPresentational,\n node,\n });\n const accessibleAttributeLabels = getAccessibleAttributeLabels({\n accessibleValue,\n alternateReadingOrderParents,\n container,",
"score": 0.8405925035476685
}
] | typescript | const processedLabels = postProcessLabels({ labels, role }).filter(Boolean); |
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/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.7705103158950806
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7542755007743835
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " *\n * @param {string} command Screen reader command.\n * @param {object} [options] Command options.\n */\n async perform<\n T extends VirtualCommandKey,\n K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>\n >(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {\n this.#checkContainer();\n await tick();",
"score": 0.7501554489135742
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " );\n }\n #getCurrentIndexByNode(tree: AccessibilityNode[]) {\n return tree.findIndex(({ node }) => node === this.#activeNode?.node);\n }\n /**\n * Getter for screen reader commands.\n *\n * Use with `await virtual.perform(command)`.\n */",
"score": 0.7159031629562378
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": "import { getElementNode } from \"./getElementNode\";\nimport { getIdRefsByAttribute } from \"../getIdRefsByAttribute\";\nimport { getNodeByIdRef } from \"../getNodeByIdRef\";\nimport { isElement } from \"../isElement\";\nimport { VirtualCommandArgs } from \"./types\";\nexport interface GetNextIndexByIdRefsAttributeArgs extends VirtualCommandArgs {\n attributeName: string;\n index?: number;\n}\nexport function getNextIndexByIdRefsAttribute({",
"score": 0.7152682542800903
}
] | typescript | >}`]: (args: VirtualCommandArgs) => number | null; |
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": " if (isHiddenFromAccessibilityTree(node)) {\n return [];\n }\n const alternateReadingOrderMap = mapAlternateReadingOrder(node);\n const ownedNodes = getAllOwnedNodes(node);\n const visitedNodes = new Set<Node>();\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,",
"score": 0.8849577307701111
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8823864459991455
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8656790256500244
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8628538250923157
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.862826943397522
}
] | typescript | const { explicitRole, implicitRole, role } = getRole({ |
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/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.8194438219070435
},
{
"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": 0.81227707862854
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.8026738166809082
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleValue.ts",
"retrieved_chunk": "];\nfunction getSelectValue(node: HTMLSelectElement) {\n const selectedOptions = [...node.options].filter(\n (optionElement) => optionElement.selected\n );\n if (node.multiple) {\n return [...selectedOptions]\n .map((optionElement) => getValue(optionElement))\n .join(\"; \");\n }",
"score": 0.7904230356216431
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.7801133394241333
}
] | 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/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": 0.9065427780151367
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " accessibleValue: string;\n allowedAccessibilityChildRoles: string[][];\n alternateReadingOrderParents: Node[];\n childrenPresentational: boolean;\n node: Node;\n parent: Node | null;\n role: string;\n spokenRole: string;\n}\ninterface AccessibilityNodeTree extends AccessibilityNode {",
"score": 0.8902081847190857
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8827535510063171
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": " inheritedImplicitPresentational,\n node,\n}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: HTMLElement;\n}) {\n const rawRoles = node.getAttribute(\"role\")?.trim().split(\" \") ?? [];\n const authorErrorFilteredRoles = rawRoles",
"score": 0.8818381428718567
},
{
"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": 0.863580584526062
}
] | typescript | const accessibleDescription = getAccessibleDescription(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/createAccessibilityTree.ts",
"retrieved_chunk": " alternateReadingOrderMap: Map<Node, Set<Node>>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-flowto\",\n node,\n });\n idRefs.forEach((idRef) => {\n const childNode = getNodeByIdRef({ container, idRef });\n if (!childNode) {",
"score": 0.8928695321083069
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.8826053142547607
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": "function addOwnedNodes(\n node: Element,\n ownedNodes: Set<Node>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-owns\",\n node,\n });\n idRefs.forEach((idRef) => {",
"score": 0.8787572383880615
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8683136701583862
},
{
"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": 0.8548793196678162
}
] | 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": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8975239992141724
},
{
"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": 0.8737202882766724
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " if (isHiddenFromAccessibilityTree(node)) {\n return [];\n }\n const alternateReadingOrderMap = mapAlternateReadingOrder(node);\n const ownedNodes = getAllOwnedNodes(node);\n const visitedNodes = new Set<Node>();\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,",
"score": 0.8657144904136658
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8565447926521301
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 0.8494136333465576
}
] | typescript | const isExplicitPresentational = presentationRoles.includes(explicitRole); |
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
[ | moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
}; |
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
| src/commands/index.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7729381918907166
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.7672704458236694
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " modifiers.push(rawKey);\n } else {\n keys.push(rawKey);\n }\n });\n const keyboardCommand = [\n ...modifiers.map((modifier) => `{${modifier}>}`),\n ...keys.map((key) => `{${key}}`),\n ...modifiers.reverse().map((modifier) => `{/${modifier}}`),\n ].join(\"\");",
"score": 0.7239300608634949
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.7149165272712708
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.7067564725875854
}
] | 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/commands/getElementNode.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nimport { isElement } from \"../isElement\";\nexport function getElementNode(accessibilityNode: AccessibilityNode) {\n const { node } = accessibilityNode;\n if (node && isElement(node)) {\n return node;\n }\n return accessibilityNode.parent;\n}",
"score": 0.7619126439094543
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n addOwnedNodes(node, ownedNodes, container);\n return ownedNodes;\n}\nfunction isHiddenFromAccessibilityTree(node: Node) {\n if (!node) {\n return true;\n }\n if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {\n return false;",
"score": 0.7613136768341064
},
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "].join(\", \");\nfunction isFocusable(node: HTMLElement) {\n return node.matches(FOCUSABLE_SELECTOR);\n}\nfunction hasGlobalStateOrProperty(node: HTMLElement) {\n return globalStatesAndProperties.some((global) => node.hasAttribute(global));\n}\nfunction getExplicitRole({\n accessibleName,\n allowedAccessibilityRoles,",
"score": 0.7514066696166992
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.7500801086425781
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.7445182800292969
}
] | typescript | const itemText = getItemText(accessibilityNode); |
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
| if (!isElement(node)) { |
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = commands[command]?.({
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
| src/Virtual.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.7898448705673218
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " alternateReadingOrderMap: Map<Node, Set<Node>>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-flowto\",\n node,\n });\n idRefs.forEach((idRef) => {\n const childNode = getNodeByIdRef({ container, idRef });\n if (!childNode) {",
"score": 0.7779735326766968
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": "function addOwnedNodes(\n node: Element,\n ownedNodes: Set<Node>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-owns\",\n node,\n });\n idRefs.forEach((idRef) => {",
"score": 0.7763183116912842
},
{
"filename": "src/commands/getElementNode.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"../createAccessibilityTree\";\nimport { isElement } from \"../isElement\";\nexport function getElementNode(accessibilityNode: AccessibilityNode) {\n const { node } = accessibilityNode;\n if (node && isElement(node)) {\n return node;\n }\n return accessibilityNode.parent;\n}",
"score": 0.774793267250061
},
{
"filename": "src/commands/jumpToDetailsElement.ts",
"retrieved_chunk": " * be helpful to jump directly to the reference or have it conveyed.\n *\n * REF: https://a11ysupport.io/tech/aria/aria-details_attribute\n */\nexport function jumpToDetailsElement({\n container,\n currentIndex,\n tree,\n}: VirtualCommandArgs) {\n return getNextIndexByIdRefsAttribute({",
"score": 0.7680624127388
}
] | typescript | if (!isElement(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/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.7619741559028625
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.7557564377784729
},
{
"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": 0.7468451261520386
},
{
"filename": "src/commands/index.ts",
"retrieved_chunk": " moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),\n};\nexport type VirtualCommands = {\n [K in keyof typeof commands]: (typeof commands)[K];\n};\nexport type VirtualCommandKey = keyof VirtualCommands;",
"score": 0.7452991008758545
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7429546117782593
}
] | typescript | ) as { [K in VirtualCommandKey]: K }; |
import {
AccessibilityNode,
createAccessibilityTree,
} from "./createAccessibilityTree";
import {
CommandOptions,
MacOSModifiers,
ScreenReader,
WindowsModifiers,
} from "@guidepup/guidepup";
import { commands, VirtualCommandKey, VirtualCommands } from "./commands";
import {
ERR_VIRTUAL_MISSING_CONTAINER,
ERR_VIRTUAL_NOT_STARTED,
} from "./errors";
import { getItemText } from "./getItemText";
import { getSpokenPhrase } from "./getSpokenPhrase";
import { isElement } from "./isElement";
import userEvent from "@testing-library/user-event";
import { VirtualCommandArgs } from "./commands/types";
export interface StartOptions extends CommandOptions {
/**
* The bounding HTML element to use the Virtual Screen Reader in.
*
* To use the entire page pass `document.body`.
*/
container: Node;
}
const defaultUserEventOptions = {
delay: null,
skipHover: true,
};
/**
* TODO: handle live region roles:
*
* - alert
* - log
* - marquee
* - status
* - timer
* - alertdialog
*
* And handle live region attributes:
*
* - aria-atomic
* - aria-busy
* - aria-live
* - aria-relevant
*
* When live regions are marked as polite, assistive technologies SHOULD
* announce updates at the next graceful opportunity, such as at the end of
* speaking the current sentence or when the user pauses typing. When live
* regions are marked as assertive, assistive technologies SHOULD notify the
* user immediately.
*
* REF:
*
* - https://w3c.github.io/aria/#live_region_roles
* - https://w3c.github.io/aria/#window_roles
* - https://w3c.github.io/aria/#attrs_liveregions
* - https://w3c.github.io/aria/#aria-live
*/
/**
* TODO: When a modal element is displayed, assistive technologies SHOULD
* navigate to the element unless focus has explicitly been set elsewhere. Some
* assistive technologies limit navigation to the modal element's contents. If
* focus moves to an element outside the modal element, assistive technologies
* SHOULD NOT limit navigation to the modal element.
*
* REF: https://w3c.github.io/aria/#aria-modal
*/
const observeDOM = (function () {
const MutationObserver = window.MutationObserver;
return function observeDOM(
node: Node,
onChange: MutationCallback
): () => void {
if (!isElement(node)) {
return;
}
if (MutationObserver) {
const mutationObserver = new MutationObserver(onChange);
mutationObserver.observe(node, {
attributes: true,
childList: true,
subtree: true,
});
return () => {
mutationObserver.disconnect();
};
}
return () => {
// gracefully fallback to not supporting Accessibility Tree refreshes if
// the DOM changes.
};
};
})();
async function tick() {
return await new Promise<void>((resolve) => setTimeout(() => resolve()));
}
/**
* TODO: When an assistive technology reading cursor moves from one article to
* another, assistive technologies SHOULD set user agent focus on the article
* that contains the reading cursor. If the reading cursor lands on a focusable
* element inside the article, the assistive technology MAY set focus on that
* element in lieu of setting focus on the containing article.
*
* REF: https://w3c.github.io/aria/#feed
*/
export class Virtual implements ScreenReader {
#activeNode: AccessibilityNode | null = null;
#container: Node | null = null;
#itemTextLog: string[] = [];
#spokenPhraseLog: string[] = [];
#treeCache: AccessibilityNode[] | null = null;
#disconnectDOMObserver: () => void | null = null;
#checkContainer() {
if (!this.#container) {
throw new Error(ERR_VIRTUAL_NOT_STARTED);
}
}
#getAccessibilityTree() {
if (!this.#treeCache) {
this.#treeCache = createAccessibilityTree(this.#container);
this.#attachFocusListeners();
}
return this.#treeCache;
}
#invalidateTreeCache() {
this.#detachFocusListeners();
this.#treeCache = null;
}
#attachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.addEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
#detachFocusListeners() {
this.#getAccessibilityTree().forEach((treeNode) => {
treeNode.node.removeEventListener(
"focus",
this.#handleFocusChange.bind(this)
);
});
}
async #handleFocusChange({ target }: FocusEvent) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const nextIndex = tree.findIndex(({ node }) => node === target);
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode, true);
}
#focusActiveElement() {
if (!this.#activeNode || !isElement(this.#activeNode.node)) {
return;
}
this.#activeNode.node.focus();
}
#updateState(accessibilityNode: AccessibilityNode, ignoreIfNoChange = false) {
const spokenPhrase = getSpokenPhrase(accessibilityNode);
const itemText = getItemText(accessibilityNode);
this.#activeNode = accessibilityNode;
if (
ignoreIfNoChange &&
spokenPhrase === this.#spokenPhraseLog.at(-1) &&
itemText === this.#itemTextLog.at(-1)
) {
return;
}
this.#itemTextLog.push(itemText);
this.#spokenPhraseLog.push(spokenPhrase);
}
async #refreshState(ignoreIfNoChange) {
await tick();
this.#invalidateTreeCache();
const tree = this.#getAccessibilityTree();
const currentIndex = this.#getCurrentIndexByNode(tree);
const newActiveNode = tree.at(currentIndex);
this.#updateState(newActiveNode, ignoreIfNoChange);
}
#getCurrentIndex(tree: AccessibilityNode[]) {
return tree.findIndex(
({
accessibleDescription,
accessibleName,
accessibleValue,
node,
role,
spokenRole,
}) =>
accessibleDescription === this.#activeNode?.accessibleDescription &&
accessibleName === this.#activeNode?.accessibleName &&
accessibleValue === this.#activeNode?.accessibleValue &&
node === this.#activeNode?.node &&
role === this.#activeNode?.role &&
spokenRole === this.#activeNode?.spokenRole
);
}
#getCurrentIndexByNode(tree: AccessibilityNode[]) {
return tree.findIndex(({ node }) => node === this.#activeNode?.node);
}
/**
* Getter for screen reader commands.
*
* Use with `await virtual.perform(command)`.
*/
get commands() {
return Object.fromEntries<VirtualCommandKey>(
Object.keys(commands).map((command: VirtualCommandKey) => [
command,
command,
])
) as { [K in VirtualCommandKey]: K };
}
/**
* Detect whether the screen reader is supported for the current OS.
*
* @returns {Promise<boolean>}
*/
async detect() {
return true;
}
/**
* Detect whether the screen reader is the default screen reader for the current OS.
*
* @returns {Promise<boolean>}
*/
async default() {
return false;
}
/**
* Turn the screen reader on.
*
* @param {object} [options] Additional options.
*/
async start({ container }: StartOptions = { container: null }) {
if (!container) {
throw new Error(ERR_VIRTUAL_MISSING_CONTAINER);
}
this.#container = container;
this.#disconnectDOMObserver = observeDOM(
container,
this.#invalidateTreeCache.bind(this)
);
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
this.#updateState(tree[0]);
return;
}
/**
* Turn the screen reader off.
*/
async stop() {
this.#disconnectDOMObserver?.();
this.#invalidateTreeCache();
this.#activeNode = null;
this.#container = null;
this.#itemTextLog = [];
this.#spokenPhraseLog = [];
return;
}
/**
* Move the screen reader cursor to the previous location.
*/
async previous() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex = currentIndex === -1 ? 0 : currentIndex - 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Move the screen reader cursor to the next location.
*/
async next() {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const nextIndex =
currentIndex === -1 || currentIndex === tree.length - 1
? 0
: currentIndex + 1;
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Perform the default action for the item in the screen reader cursor.
*/
async act() {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
// TODO: verify that is appropriate for all default actions
await userEvent.click(target, defaultUserEventOptions);
return;
}
/**
* Interact with the item under the screen reader cursor.
*/
async interact() {
this.#checkContainer();
return;
}
/**
* Stop interacting with the current item.
*/
async stopInteracting() {
this.#checkContainer();
return;
}
/**
* Press a key on the active item.
*
* `key` can specify the intended [keyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
* value or a single character to generate the text for. A superset of the `key` values can be found
* [on the MDN key values page](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values). Examples of the keys are:
*
* `F1` - `F20`, `Digit0` - `Digit9`, `KeyA` - `KeyZ`, `Backquote`, `Minus`, `Equal`, `Backslash`, `Backspace`, `Tab`,
* `Delete`, `Escape`, `ArrowDown`, `End`, `Enter`, `Home`, `Insert`, `PageDown`, `PageUp`, `ArrowRight`, `ArrowUp`, etc.
*
* Following modification shortcuts are also supported: `Shift`, `Control`, `Alt`, `Meta` (OS permitting).
*
* Holding down `Shift` will type the text that corresponds to the `key` in the upper case.
*
* If `key` is a single character, it is case-sensitive, so the values `a` and `A` will generate different respective
* texts.
*
* Shortcuts such as `key: "Control+f"` or `key: "Control+Shift+f"` are supported as well. When specified with the
* modifier, modifier is pressed and being held while the subsequent key is being pressed.
*
* ```ts
* await virtual.press("Control+f");
* ```
*
* @param {string} key Name of the key to press or a character to generate, such as `ArrowLeft` or `a`.
*/
async press(key: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const rawKeys = key.replaceAll("{", "{{").replaceAll("[", "[[").split("+");
const modifiers = [];
const keys = [];
rawKeys.forEach((rawKey) => {
if (
typeof MacOSModifiers[rawKey] !== "undefined" ||
typeof WindowsModifiers[rawKey] !== "undefined"
) {
modifiers.push(rawKey);
} else {
keys.push(rawKey);
}
});
const keyboardCommand = [
...modifiers.map((modifier) => `{${modifier}>}`),
...keys.map((key) => `{${key}}`),
...modifiers.reverse().map((modifier) => `{/${modifier}}`),
].join("");
this.#focusActiveElement();
await userEvent.keyboard(keyboardCommand, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Type text into the active item.
*
* To press a special key, like `Control` or `ArrowDown`, use `virtual.press(key)`.
*
* ```ts
* await virtual.type("my-username");
* await virtual.press("Enter");
* ```
*
* @param {string} text Text to type into the active item.
*/
async type(text: string) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const target = this.#activeNode.node as HTMLElement;
await userEvent.type(target, text, defaultUserEventOptions);
await this.#refreshState(true);
return;
}
/**
* Perform a screen reader command.
*
* @param {string} command Screen reader command.
* @param {object} [options] Command options.
*/
async perform<
T extends VirtualCommandKey,
K extends Omit<Parameters<VirtualCommands[T]>[0], keyof VirtualCommandArgs>
>(command: T, options?: { [L in keyof K]: K[L] } & CommandOptions) {
this.#checkContainer();
await tick();
const tree = this.#getAccessibilityTree();
if (!tree.length) {
return;
}
const currentIndex = this.#getCurrentIndex(tree);
const | nextIndex = commands[command]?.({ |
...options,
container: this.#container,
currentIndex,
tree,
});
if (typeof nextIndex !== "number") {
return;
}
const newActiveNode = tree.at(nextIndex);
this.#updateState(newActiveNode);
return;
}
/**
* Click the mouse.
*
* @param {object} [options] Click options.
*/
async click({ button = "left", clickCount = 1 } = {}) {
this.#checkContainer();
await tick();
if (!this.#activeNode) {
return;
}
const key = `[Mouse${button[0].toUpperCase()}${button.slice(1)}]`;
const keys = key.repeat(clickCount);
const target = this.#activeNode.node as HTMLElement;
await userEvent.pointer(
[{ target }, { keys, target }],
defaultUserEventOptions
);
return;
}
/**
* Get the last spoken phrase.
*
* @returns {Promise<string>} The last spoken phrase.
*/
async lastSpokenPhrase() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog.at(-1) ?? "";
}
/**
* Get the text of the item in the screen reader cursor.
*
* @returns {Promise<string>} The item's text.
*/
async itemText() {
this.#checkContainer();
await tick();
return this.#itemTextLog.at(-1) ?? "";
}
/**
* Get the log of all spoken phrases for this screen reader instance.
*
* @returns {Promise<string[]>} The spoken phrase log.
*/
async spokenPhraseLog() {
this.#checkContainer();
await tick();
return this.#spokenPhraseLog;
}
/**
* Get the log of all visited item text for this screen reader instance.
*
* @returns {Promise<string[]>} The item text log.
*/
async itemTextLog() {
this.#checkContainer();
await tick();
return this.#itemTextLog;
}
}
| src/Virtual.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " attributeName,\n index = 0,\n container,\n currentIndex,\n tree,\n}: GetNextIndexByIdRefsAttributeArgs) {\n if (!isElement(container)) {\n return;\n }\n const currentAccessibilityNode = tree.at(currentIndex);",
"score": 0.8318747878074646
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.7830216288566589
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.779563307762146
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7749965190887451
},
{
"filename": "src/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.7734789252281189
}
] | 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/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": 0.818123459815979
},
{
"filename": "src/commands/moveToPreviousAlternateReadingOrderElement.ts",
"retrieved_chunk": " */\nexport function moveToPreviousAlternateReadingOrderElement({\n index = 0,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n if (!isElement(container)) {\n return;\n }",
"score": 0.7811734676361084
},
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7804195284843445
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.7739335298538208
},
{
"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": 0.7688832879066467
}
] | typescript | querySelectorAll("[aria-flowto]")
.forEach((parentNode) =>
addAlternateReadingOrderNodes(parentNode, alternateReadingOrderMap, node)
); |
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/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8815750479698181
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.8567892909049988
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.8559827208518982
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8193281888961792
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.8120763301849365
}
] | typescript | const labelFromImplicitAriaAttributeValue = mapAttributeNameAndValueToLabel(
{ |
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/commands/getNextIndexByIdRefsAttribute.ts",
"retrieved_chunk": " const currentNode = getElementNode(currentAccessibilityNode);\n const idRefs = getIdRefsByAttribute({\n attributeName,\n node: currentNode,\n });\n const idRef = idRefs[index];\n const targetNode = getNodeByIdRef({ container, idRef });\n if (!targetNode) {\n return;\n }",
"score": 0.8855770230293274
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.8787106275558472
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": " if (!htmlAttribute?.length) {\n return { label: \"\", value: \"\" };\n }\n for (const { name, negative = false } of htmlAttribute) {\n const attributeValue = node.getAttribute(name);\n const label = mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n negative,",
"score": 0.875290036201477
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " alternateReadingOrderMap: Map<Node, Set<Node>>,\n container: Element\n) {\n const idRefs = getIdRefsByAttribute({\n attributeName: \"aria-flowto\",\n node,\n });\n idRefs.forEach((idRef) => {\n const childNode = getNodeByIdRef({ container, idRef });\n if (!childNode) {",
"score": 0.8704673051834106
},
{
"filename": "src/getItemText.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getItemText = (\n accessibilityNode: Pick<\n AccessibilityNode,\n \"accessibleName\" | \"accessibleValue\"\n >\n) => {\n const { accessibleName, accessibleValue } = accessibilityNode;\n const announcedValue =\n accessibleName === accessibleValue ? \"\" : accessibleValue;",
"score": 0.8584908246994019
}
] | typescript | const itemText = getItemText({ accessibleName, accessibleValue }); |
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": 0.9052568674087524
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8652063012123108
},
{
"filename": "src/commands/moveToNextAlternateReadingOrderElement.ts",
"retrieved_chunk": "export function moveToNextAlternateReadingOrderElement({\n index,\n container,\n currentIndex,\n tree,\n}: MoveToNextAlternateReadingOrderElement) {\n return getNextIndexByIdRefsAttribute({\n attributeName: \"aria-flowto\",\n index,\n container,",
"score": 0.8643432259559631
},
{
"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": 0.8556809425354004
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts",
"retrieved_chunk": "export const getLabelFromHtmlEquivalentAttribute = ({\n attributeName,\n container,\n node,\n}: {\n attributeName: string;\n container: Node;\n node: HTMLElement;\n}) => {\n const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];",
"score": 0.851809561252594
}
] | typescript | const childNode = getNodeByIdRef({ container, idRef }); |
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
| [moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
}; |
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
| src/commands/index.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7850948572158813
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.7779809236526489
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " modifiers.push(rawKey);\n } else {\n keys.push(rawKey);\n }\n });\n const keyboardCommand = [\n ...modifiers.map((modifier) => `{${modifier}>}`),\n ...keys.map((key) => `{${key}}`),\n ...modifiers.reverse().map((modifier) => `{/${modifier}}`),\n ].join(\"\");",
"score": 0.7374082803726196
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.72922682762146
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.7219216823577881
}
] | typescript | [moveToNextCommand]: getNextIndexByRole([role]),
[moveToPreviousCommand]: getPreviousIndexByRole([role]),
}; |
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role } = getRole({
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const | isExplicitPresentational = presentationRoles.includes(explicitRole); |
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
| src/getNodeAccessibilityData/index.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8538670539855957
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8507848978042603
},
{
"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": 0.8416956067085266
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({\n allowedAccessibilityRoles: tree.allowedAccessibilityChildRoles,\n alternateReadingOrderParents,\n container,\n node: childNode,\n inheritedImplicitPresentational: tree.childrenPresentational,\n });",
"score": 0.8410382270812988
},
{
"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": 0.8393276929855347
}
] | typescript | isExplicitPresentational = presentationRoles.includes(explicitRole); |
import { getNextIndexByRole } from "./getNextIndexByRole";
import { getPreviousIndexByRole } from "./getPreviousIndexByRole";
import { jumpToControlledElement } from "./jumpToControlledElement";
import { jumpToDetailsElement } from "./jumpToDetailsElement";
import { moveToNextAlternateReadingOrderElement } from "./moveToNextAlternateReadingOrderElement";
import { moveToPreviousAlternateReadingOrderElement } from "./moveToPreviousAlternateReadingOrderElement";
import { VirtualCommandArgs } from "./types";
const quickLandmarkNavigationRoles = [
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role banner.
*
* REF: https://w3c.github.io/aria/#banner
*/
"banner",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role complementary.
*
* REF: https://w3c.github.io/aria/#complementary
*/
"complementary",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role contentinfo.
*
* REF: https://w3c.github.io/aria/#contentinfo
*/
"contentinfo",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* figures.
*
* REF: https://w3c.github.io/aria/#figure
*/
"figure",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role form.
*
* REF: https://w3c.github.io/aria/#form
*/
"form",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role main.
*
* REF: https://w3c.github.io/aria/#main
*/
"main",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role navigation.
*
* REF: https://w3c.github.io/aria/#navigation
*/
"navigation",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role region.
*
* REF: https://w3c.github.io/aria/#region
*/
"region",
/**
* Assistive technologies SHOULD enable users to quickly navigate to
* elements with role search.
*
* REF: https://w3c.github.io/aria/#search
*/
"search",
] as const;
const quickLandmarkNavigationCommands = quickLandmarkNavigationRoles.reduce<
Record<string, unknown>
>((accumulatedCommands, role) => {
const moveToNextCommand = `moveToNext${role.at(0).toUpperCase()}${role.slice(
1
)}`;
const moveToPreviousCommand = `moveToPrevious${role
.at(0)
.toUpperCase()}${role.slice(1)}`;
return {
...accumulatedCommands,
[moveToNextCommand]: getNextIndexByRole([role]),
| [moveToPreviousCommand]: getPreviousIndexByRole([role]),
}; |
}, {}) as {
[K in
| `moveToNext${Capitalize<(typeof quickLandmarkNavigationRoles)[number]>}`
| `moveToPrevious${Capitalize<
(typeof quickLandmarkNavigationRoles)[number]
>}`]: (args: VirtualCommandArgs) => number | null;
};
export const commands = {
jumpToControlledElement,
jumpToDetailsElement,
moveToNextAlternateReadingOrderElement,
moveToPreviousAlternateReadingOrderElement,
...quickLandmarkNavigationCommands,
moveToNextLandmark: getNextIndexByRole(quickLandmarkNavigationRoles),
moveToPreviousLandmark: getPreviousIndexByRole(quickLandmarkNavigationRoles),
};
export type VirtualCommands = {
[K in keyof typeof commands]: (typeof commands)[K];
};
export type VirtualCommandKey = keyof VirtualCommands;
| src/commands/index.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/commands/getNextIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetNextIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getNextIndexByRole(roles: Readonly<string[]>) {\n return function getNextIndex({ currentIndex, tree }: GetNextIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(currentIndex + 1)\n .concat(tree.slice(0, currentIndex + 1));\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")",
"score": 0.7850948572158813
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": "import { VirtualCommandArgs } from \"./types\";\nexport type GetPreviousIndexByRoleArgs = Omit<VirtualCommandArgs, \"container\">;\nexport function getPreviousIndexByRole(roles: Readonly<string[]>) {\n return function getPreviousIndex({\n currentIndex,\n tree,\n }: GetPreviousIndexByRoleArgs) {\n const reorderedTree = tree\n .slice(0, currentIndex)\n .reverse()",
"score": 0.7779809236526489
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " modifiers.push(rawKey);\n } else {\n keys.push(rawKey);\n }\n });\n const keyboardCommand = [\n ...modifiers.map((modifier) => `{${modifier}>}`),\n ...keys.map((key) => `{${key}}`),\n ...modifiers.reverse().map((modifier) => `{/${modifier}}`),\n ].join(\"\");",
"score": 0.7374082803726196
},
{
"filename": "src/commands/getPreviousIndexByRole.ts",
"retrieved_chunk": " .concat(tree.slice(currentIndex).reverse());\n const accessibilityNode = reorderedTree.find(\n (node) =>\n roles.includes(node.role) && !node.spokenRole.startsWith(\"end of\")\n );\n if (!accessibilityNode) {\n return null;\n }\n return tree.findIndex((node) => node === accessibilityNode);\n };",
"score": 0.72922682762146
},
{
"filename": "src/Virtual.ts",
"retrieved_chunk": " const tree = this.#getAccessibilityTree();\n if (!tree.length) {\n return;\n }\n const currentIndex = this.#getCurrentIndex(tree);\n const nextIndex = commands[command]?.({\n ...options,\n container: this.#container,\n currentIndex,\n tree,",
"score": 0.7219216823577881
}
] | typescript | [moveToPreviousCommand]: getPreviousIndexByRole([role]),
}; |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy | (targetCharacter: EnemyCharacter) { |
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8671929836273193
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8381689786911011
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8352928161621094
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " const dx = horizontal ? 1 : 0;\n const dy = horizontal ? 0 : 1;\n let startX = null,\n startY = null;\n startX = _.random(horizontal ? 0 : 1, dimension - 1);\n startY = _.random(horizontal ? 1 : 0, dimension - 1);\n const from = new Coords(startX, startY);\n const to = from.clone().add(dx, dy);\n // If there is already a wall here, skip!\n let alreadyExists = false;",
"score": 0.8115845918655396
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.doMove(this.queuedMove.dx, this.queuedMove.dy);\n this.queuedMove = null;\n }\n }\n doMove(dx: number, dy: number) {\n if (this.state != \"play\") {\n // Can't move!\n return;\n }\n // 1. If you aren't yet ready to move, then queue the direction",
"score": 0.8032995462417603
}
] | 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/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8957343101501465
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8840599656105042
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.8707337975502014
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,\n childrenPresentational,\n role,\n spokenRole,\n } = getNodeAccessibilityData({",
"score": 0.864489734172821
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " if (isHiddenFromAccessibilityTree(node)) {\n return [];\n }\n const alternateReadingOrderMap = mapAlternateReadingOrder(node);\n const ownedNodes = getAllOwnedNodes(node);\n const visitedNodes = new Set<Node>();\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,",
"score": 0.8635337352752686
}
] | typescript | = getAccessibleAttributeLabels({ |
import { mapAttributeNameAndValueToLabel } from "./mapAttributeNameAndValueToLabel";
// REF: https://www.w3.org/TR/html-aria/#docconformance-attr
const ariaToHTMLAttributeMapping: Record<
string,
Array<{ name: string; negative?: boolean }>
> = {
"aria-checked": [{ name: "checked" }],
"aria-disabled": [{ name: "disabled" }],
// "aria-hidden": [{ name: "hidden" }],
"aria-placeholder": [{ name: "placeholder" }],
"aria-valuemax": [{ name: "max" }],
"aria-valuemin": [{ name: "min" }],
"aria-readonly": [
{ name: "readonly" },
{ name: "contenteditable", negative: true },
],
"aria-required": [{ name: "required" }],
"aria-colspan": [{ name: "colspan" }],
"aria-rowspan": [{ name: "rowspan" }],
};
export const getLabelFromHtmlEquivalentAttribute = ({
attributeName,
container,
node,
}: {
attributeName: string;
container: Node;
node: HTMLElement;
}) => {
const htmlAttribute = ariaToHTMLAttributeMapping[attributeName];
if (!htmlAttribute?.length) {
return { label: "", value: "" };
}
for (const { name, negative = false } of htmlAttribute) {
const attributeValue = node.getAttribute(name);
const | label = mapAttributeNameAndValueToLabel({ |
attributeName,
attributeValue,
container,
negative,
});
if (label) {
return { label, value: attributeValue };
}
}
return { label: "", value: "" };
};
| src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromHtmlEquivalentAttribute.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " if (!isElement(node)) {\n return [];\n }\n const labels: Record<string, { label: string; value: string }> = {};\n const attributes = getAttributesByRole({ accessibleValue, role });\n attributes.forEach(([attributeName, implicitAttributeValue]) => {\n const {\n label: labelFromHtmlEquivalentAttribute,\n value: valueFromHtmlEquivalentAttribute,\n } = getLabelFromHtmlEquivalentAttribute({",
"score": 0.9047266840934753
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/mapAttributeNameAndValueToLabel.ts",
"retrieved_chunk": "}) => {\n if (typeof attributeValue !== \"string\") {\n return null;\n }\n const mapper = ariaPropertyToVirtualLabelMap[attributeName];\n return mapper?.({ attributeValue, container, negative }) ?? null;\n};",
"score": 0.8914823532104492
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromAriaAttribute.ts",
"retrieved_chunk": " const attributeValue = node.getAttribute(attributeName);\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue,\n container,\n }),\n value: attributeValue,\n };\n};",
"score": 0.8697656989097595
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/getLabelFromImplicitHtmlElementValue.ts",
"retrieved_chunk": " const { localName } = node;\n const implicitValue = mapLocalNameToImplicitValue[attributeName]?.[localName];\n return {\n label: mapAttributeNameAndValueToLabel({\n attributeName,\n attributeValue: implicitValue,\n container,\n }),\n value: implicitValue,\n };",
"score": 0.8684595227241516
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleAttributeLabels/index.ts",
"retrieved_chunk": " }\n const { label: labelFromAriaAttribute, value: valueFromAriaAttribute } =\n getLabelFromAriaAttribute({\n attributeName,\n container,\n node,\n });\n if (labelFromAriaAttribute) {\n labels[attributeName] = {\n label: labelFromAriaAttribute,",
"score": 0.8665156364440918
}
] | typescript | label = mapAttributeNameAndValueToLabel({ |
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/createAccessibilityTree.ts",
"retrieved_chunk": " }\n addOwnedNodes(node, ownedNodes, container);\n return ownedNodes;\n}\nfunction isHiddenFromAccessibilityTree(node: Node) {\n if (!node) {\n return true;\n }\n if (node.nodeType === Node.TEXT_NODE && !!node.textContent.trim()) {\n return false;",
"score": 0.8424100875854492
},
{
"filename": "src/getNodeAccessibilityData/getAccessibleName.ts",
"retrieved_chunk": "import { computeAccessibleName } from \"dom-accessibility-api\";\nimport { isElement } from \"../isElement\";\nexport function getAccessibleName(node: Node) {\n return isElement(node)\n ? computeAccessibleName(node).trim()\n : node.textContent.trim();\n}",
"score": 0.8245329260826111
},
{
"filename": "src/getNodeByIdRef.ts",
"retrieved_chunk": "import { isElement } from \"./isElement\";\nexport function getNodeByIdRef({ container, idRef }) {\n if (!isElement(container) || !idRef) {\n return null;\n }\n return container.querySelector(`#${idRef}`);\n}",
"score": 0.8200290203094482
},
{
"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": 0.8199259042739868
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.7980683445930481
}
] | typescript | switch (node.localName) { |
import { ARIARoleDefinitionKey, roles } from "aria-query";
import { getRole, presentationRoles } from "./getRole";
import { getAccessibleAttributeLabels } from "./getAccessibleAttributeLabels";
import { getAccessibleDescription } from "./getAccessibleDescription";
import { getAccessibleName } from "./getAccessibleName";
import { getAccessibleValue } from "./getAccessibleValue";
import { isElement } from "../isElement";
const childrenPresentationalRoles = roles
.entries()
.filter(([, { childrenPresentational }]) => childrenPresentational)
.map(([key]) => key) as string[];
const getSpokenRole = ({ isGeneric, isPresentational, node, role }) => {
if (isPresentational || isGeneric) {
return "";
}
if (isElement(node)) {
/**
* Assistive technologies SHOULD use the value of aria-roledescription when
* presenting the role of an element, but SHOULD NOT change other
* functionality based on the role of an element that has a value for
* aria-roledescription. For example, an assistive technology that provides
* functions for navigating to the next region or button SHOULD allow those
* functions to navigate to regions and buttons that have an
* aria-roledescription.
*
* REF: https://w3c.github.io/aria/#aria-roledescription
*/
const roledescription = node.getAttribute("aria-roledescription");
if (roledescription) {
return roledescription;
}
}
return role;
};
export function getNodeAccessibilityData({
allowedAccessibilityRoles,
alternateReadingOrderParents,
container,
inheritedImplicitPresentational,
node,
}: {
allowedAccessibilityRoles: string[][];
alternateReadingOrderParents: Node[];
container: Node;
inheritedImplicitPresentational: boolean;
node: Node;
}) {
const accessibleDescription = getAccessibleDescription(node);
const accessibleName = getAccessibleName(node);
const accessibleValue = getAccessibleValue(node);
const { explicitRole, implicitRole, role | } = getRole({ |
accessibleName,
allowedAccessibilityRoles,
inheritedImplicitPresentational,
node,
});
const accessibleAttributeLabels = getAccessibleAttributeLabels({
accessibleValue,
alternateReadingOrderParents,
container,
node,
role,
});
const amendedAccessibleDescription =
accessibleDescription === accessibleName ? "" : accessibleDescription;
const isExplicitPresentational = presentationRoles.includes(explicitRole);
const isPresentational = presentationRoles.includes(role);
const isGeneric = role === "generic";
const spokenRole = getSpokenRole({
isGeneric,
isPresentational,
node,
role,
});
const { requiredOwnedElements: allowedAccessibilityChildRoles } = (roles.get(
role as ARIARoleDefinitionKey
) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
const { requiredOwnedElements: implicitAllowedAccessibilityChildRoles } =
(roles.get(implicitRole as ARIARoleDefinitionKey) as unknown as {
requiredOwnedElements: string[][];
}) ?? { requiredOwnedElements: [] };
/**
* Any descendants of elements that have the characteristic "Children
* Presentational: True" unless the descendant is not allowed to be
* presentational because it meets one of the conditions for exception
* described in Presentational Roles Conflict Resolution. However, the text
* content of any excluded descendants is included.
*
* REF: https://w3c.github.io/aria/#tree_exclusion
*/
const isChildrenPresentationalRole =
childrenPresentationalRoles.includes(role);
/**
* When an explicit or inherited role of presentation is applied to an
* element with the implicit semantic of a WAI-ARIA role that has Allowed
* Accessibility Child Roles, in addition to the element with the explicit
* role of presentation, the user agent MUST apply an inherited role of
* presentation to any owned elements that do not have an explicit role
* defined. Also, when an explicit or inherited role of presentation is
* applied to a host language element which has specifically allowed children
* as defined by the host language specification, in addition to the element
* with the explicit role of presentation, the user agent MUST apply an
* inherited role of presentation to any specifically allowed children that
* do not have an explicit role defined.
*
* REF: https://w3c.github.io/aria/#presentational-role-inheritance
*/
const isExplicitOrInheritedPresentation =
isExplicitPresentational || inheritedImplicitPresentational;
const isElementWithImplicitAllowedAccessibilityChildRoles =
!!implicitAllowedAccessibilityChildRoles.length;
const childrenInheritPresentationExceptAllowedRoles =
isExplicitOrInheritedPresentation &&
isElementWithImplicitAllowedAccessibilityChildRoles;
const childrenPresentational =
isChildrenPresentationalRole ||
childrenInheritPresentationExceptAllowedRoles;
return {
accessibleAttributeLabels,
accessibleDescription: amendedAccessibleDescription,
accessibleName,
accessibleValue,
allowedAccessibilityChildRoles,
childrenPresentational,
role,
spokenRole,
};
}
| src/getNodeAccessibilityData/index.ts | guidepup-virtual-screen-reader-1b0a234 | [
{
"filename": "src/getNodeAccessibilityData/getRole.ts",
"retrieved_chunk": "}: {\n accessibleName: string;\n allowedAccessibilityRoles: string[][];\n inheritedImplicitPresentational: boolean;\n node: Node;\n}) {\n if (!isElement(node)) {\n return { explicitRole: \"\", implicitRole: \"\", role: \"\" };\n }\n const target = node.cloneNode() as HTMLElement;",
"score": 0.8836638927459717
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " }\n return !isElement(node) || isInaccessible(node);\n}\nfunction shouldIgnoreChildren(tree: AccessibilityNodeTree) {\n const { accessibleName, node } = tree;\n if (!accessibleName) {\n return false;\n }\n return (\n // TODO: improve comparison on whether the children are superfluous",
"score": 0.8740643858909607
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " if (isHiddenFromAccessibilityTree(node)) {\n return [];\n }\n const alternateReadingOrderMap = mapAlternateReadingOrder(node);\n const ownedNodes = getAllOwnedNodes(node);\n const visitedNodes = new Set<Node>();\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,",
"score": 0.8730373382568359
},
{
"filename": "src/getSpokenPhrase.ts",
"retrieved_chunk": "import { AccessibilityNode } from \"./createAccessibilityTree\";\nexport const getSpokenPhrase = (accessibilityNode: AccessibilityNode) => {\n const {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n spokenRole,\n } = accessibilityNode;\n const announcedValue =",
"score": 0.8708531856536865
},
{
"filename": "src/createAccessibilityTree.ts",
"retrieved_chunk": " inheritedImplicitPresentational: false,\n });\n const tree = growTree(\n node,\n {\n accessibleAttributeLabels,\n accessibleDescription,\n accessibleName,\n accessibleValue,\n allowedAccessibilityChildRoles,",
"score": 0.8683961629867554
}
] | 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/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return false;\n }\n moveEnemies() {\n let delay = 0;\n // 1. Dijkstra the grid, ignoring enemies\n // Pick the closest character\n const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const enemiesAndDistances = [];\n for (const char of this.characters) {\n if (char.isEnemy) {",
"score": 0.855136513710022
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " let atLeastOneMove = false;\n for (let tries = 0; tries < 5; tries++) {\n const tryAgainLater = [];\n for (const e of sortedEnemies) {\n const char = e.char;\n const dijks = this.dijkstra(\n this.gameScreen.playerCharacter.coords,\n true,\n char.coords\n );",
"score": 0.8529929518699646
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n if (withEnemiesAsObstacles) {\n const char = this.getCharacterAt(coords.col + dx, coords.row + dy);\n if (char && char.isEnemy) {\n // There is a monster on the target square, ignore!\n return;\n }\n }\n const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;\n if (",
"score": 0.8461934328079224
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8424697518348694
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n clearEnemies() {\n for (let i = this.characters.length - 1; i >= 0; i--) {\n const c = this.characters[i];\n if (!c.isPlayer) {\n Actions.fadeOutAndRemove(c, 0.2).play();\n this.characters.splice(i, 1);\n }\n }\n }",
"score": 0.8196141123771667
}
] | 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": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8250401020050049
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8238565325737
},
{
"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": 0.8177306056022644
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8155522346496582
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.813626766204834
}
] | 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/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.7859463691711426
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.7794787287712097
},
{
"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": 0.7746701240539551
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.7745629549026489
},
{
"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": 0.7693262696266174
}
] | typescript | this.setPositionTo(w, w.from, true); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find | (c => c.isPlayer); |
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8548793792724609
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7765325307846069
},
{
"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": 0.7632758617401123
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7603830695152283
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7541179656982422
}
] | typescript | (c => c.isPlayer); |
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/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": 0.8627506494522095
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8448541760444641
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " exitDir: Coords = null;\n constructor(gameScreen: GameScreen, dimension: number) {\n super(dimension);\n this.gameScreen = gameScreen;\n // Add cell backgrounds\n const background = PIXI.Sprite.from(PIXI.Texture.WHITE);\n background.tint = 0xd3c8a2;\n background.width = this.edgeSize;\n background.height = this.edgeSize;\n background.alpha = 1;",
"score": 0.8414949178695679
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.queuedMove = null;\n this.level = 0;\n this.score = 0;\n this.gameContainer = new PIXI.Container();\n this.addChild(this.gameContainer);\n // Score\n this.scoreLabel = new PIXI.BitmapText(\"0\", Font.makeFontOptions(\"small\"));\n this.scoreLabel.anchor.set(0.5);\n this.scoreLabel.tint = 0xffffff;\n this.gameContainer.addChild(this.scoreLabel);",
"score": 0.8300784826278687
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " sprite: PIXI.Sprite;\n heartsHolder: PIXI.Container;\n constructor(backgroundPath: string) {\n super();\n this.coords = new Coords(0, 0);\n this.sprite = PIXI.Sprite.from(Game.tex(backgroundPath));\n this.sprite.anchor.set(0.5, 1);\n this.addChild(this.sprite);\n // Add holder for hearts\n this.heartsHolder = new PIXI.Container();",
"score": 0.8229416608810425
}
] | typescript | if (Save.hasGameState()) { |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
| targetCharacter.position.x += this.position.x; |
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8210713863372803
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8034780621528625
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const modals = [this.gameOverModal];\n for (const m of modals) {\n if (m) {\n // Centre it!\n const x = (width - Game.TARGET_WIDTH) / 2;\n const y = (height - Game.TARGET_HEIGHT) / 2;\n m.position.set(x, y);\n }\n }\n }",
"score": 0.7978965044021606
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.7956043481826782
},
{
"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": 0.7950841188430786
}
] | typescript | targetCharacter.position.x += this.position.x; |
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
Save.initialise();
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (!Save.loadGameState(gameScreen)) {
gameScreen.nextLevel();
}
this. | setScreen(gameScreen); |
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
if (Save.hasGameState()) {
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
| src/Game.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " // Save game state...\n const data = this.serialiseGameState(gameScreen);\n this.engine.save(\"currentGameState\", data);\n }\n static loadGameState(gameScreen: GameScreen) {\n // Save game state...\n const data = this.engine.load(\"currentGameState\");\n if (data) {\n // Load data into gameScreen...\n this.deserialiseGameState(gameScreen, data);",
"score": 0.8413233757019043
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " Actions.delay(delay),\n Actions.runFunc(() => {\n this.readyToMove = true;\n this.pumpQueuedMove();\n })\n ).play();\n if (this.state == \"play\")\n Save.saveGameState(this);\n }\n resizeAgain() {",
"score": 0.8176581263542175
},
{
"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": 0.811534583568573
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8108047246932983
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.darkOverlay.visible = false;\n this.darkOverlay.alpha = 0;\n })\n ).play();\n }\n gameOver() {\n this.state = \"gameover\";\n Save.clearGameState();\n this.showDarkOverlay(0.5);\n this.gameOverModal = new GameOverModal(this);",
"score": 0.795304536819458
}
] | 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": " // Delete all old walls\n for (const w of this.walls) {\n Actions.fadeOutAndRemove(w, 0.2).play();\n }\n this.walls = Wall.randomLayout(numWalls, this.dimension);\n // Add some new walls... they must generate any closed areas\n this.drawWalls(this.walls);\n }\n drawWalls(walls: Wall[]) {\n for (const w of walls) {",
"score": 0.7666460275650024
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " if (\n !this.getCharacterAt(coord) &&\n (!dijks || dijks.distance[coord.col][coord.row] > 1)\n ) {\n return coord;\n }\n }\n return null;\n }\n generateWalls(numWalls: number) {",
"score": 0.7529826760292053
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " let prospective: Wall = null;\n if (walls.length > 0 && Math.random() < Wall.CONNECTION_PREFERRED_RATIO) {\n // Try to join onto an existing wall\n const prevWall = _.sample(walls);\n const connectingWalls = [];\n if (prevWall.isHorizontal) {\n connectingWalls.push(\n // 2 parallel\n [prevWall.from.clone().add(-1, 0), prevWall.to.clone().add(-1, 0)],\n [prevWall.from.clone().add(1, 0), prevWall.to.clone().add(1, 0)],",
"score": 0.7435232400894165
},
{
"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": 0.7424074411392212
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7410944700241089
}
] | typescript | private static serialiseCharacters(characters: Character[]) { |
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": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.812124490737915
},
{
"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": 0.8078460097312927
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.7986191511154175
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.7958348989486694
},
{
"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": 0.7853662967681885
}
] | 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": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8256714940071106
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8255137801170349
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8171567916870117
},
{
"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": 0.8168152570724487
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8155026435852051
}
] | typescript | new EnemyCharacter(type); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
| private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) { |
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // 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": 0.7884331345558167
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7877545356750488
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7766662836074829
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7553399801254272
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.7475717067718506
}
] | typescript | private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) { |
import * as PIXI from "pixi.js";
import { Sound, sound } from "@pixi/sound";
import { Actions } from "pixi-actions";
import { Screen, GameScreen, MenuScreen } from "screens";
import { Font } from "utils";
import Save from "./save/Save";
import * as _ from "underscore";
export default class Game {
// Display options
static TARGET_WIDTH = 225;
static TARGET_HEIGHT = 345;
static INTEGER_SCALING = false;
static MAINTAIN_RATIO = false;
static BACKGROUND_COLOUR = 0x333333;
// Mouse
static HOLD_INITIAL_TIME_MS = 500;
static HOLD_REPEAT_TIME_MS = 400;
static SWIPE_TRIGGER_THRESHOLD = 10;
static SWIPE_MAX_TIME_MS = 500;
// Game options
static EXIT_TYPE: "stairs" | "door" = "door";
static DIMENSION = 5;
// Debug stuff
static DEBUG_SHOW_FRAMERATE = true;
// Helpers
static instance: Game;
resources: any;
spritesheet: PIXI.Spritesheet;
app: PIXI.Application;
stage: PIXI.Container;
fpsLabel: PIXI.BitmapText;
backgroundSprite: PIXI.Sprite;
innerBackgroundSprite: PIXI.Sprite;
// Full size of app
width: number = window.innerWidth;
height: number = window.innerHeight;
// Size of stage (on mobile, may include inset areas)
stageWidth: number = window.innerWidth;
stageHeight: number = window.innerHeight;
scale: number = 1;
currentScreen: Screen;
startTouch: { x: number; y: number };
startTouchTime: number;
touchPosition: { x: number; y: number } = {x: 0, y: 0};
previousHoldPosition: { x: number; y: number } = {x: 0, y: 0};
isHoldRepeating: boolean = false;
playerHash: string;
playerName: string;
muted: boolean;
stretchDisplay: boolean;
fpsAverageShort: number[] = [];
fpsAverageLong: number[] = [];
constructor(app: PIXI.Application) {
this.app = app;
this.muted = false;
this.stretchDisplay = !Game.INTEGER_SCALING;
this.stage = new PIXI.Container();
this.app.stage.addChild(this.stage);
Save.initialise();
this.resize();
this.init();
}
setStretchDisplay(s: boolean) {
this.stretchDisplay = s;
this.resize();
}
static tex(name: string): PIXI.Texture {
return Game.instance.spritesheet.textures[name];
}
init() {
sound.init();
Game.instance = this;
PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.LINEAR;
PIXI.settings.ROUND_PIXELS = false;
PIXI.Loader.shared
.add("spritesheet", "packed.json")
.add("Kaph", "font/kaph.fnt")
.add("sound-attack", "sound/attack.wav")
.add("sound-bump", "sound/bump.wav")
.add("sound-step1", "sound/step1.wav")
.add("sound-step2", "sound/step2.wav")
.add("sound-step3", "sound/step3.wav")
.add("sound-step4", "sound/step4.wav")
.use((resource, next) => {
// Load sounds into sound system
if (resource) {
if (["wav", "ogg", "mp3", "mpeg"].includes(resource.extension)) {
sound.add(resource.name, Sound.from(resource.data));
}
}
next();
})
.load((_, resources) => {
this.resources = resources;
this.spritesheet = this.resources["spritesheet"].spritesheet;
this.postInit();
});
}
gotoGameScreen() {
const gameScreen = new GameScreen();
if (! | Save.loadGameState(gameScreen)) { |
gameScreen.nextLevel();
}
this.setScreen(gameScreen);
}
gotoMenuScreen() {
this.setScreen(new MenuScreen());
}
setScreen(screen: Screen) {
if (this.currentScreen != null) {
// Remove it!
Actions.fadeOutAndRemove(this.currentScreen, 0.2).play();
}
// Add new one
screen.alpha = 0;
Actions.fadeIn(screen, 0.2).play();
this.currentScreen = screen;
this.stage.addChild(screen);
this.notifyScreensOfSize();
}
postInit() {
// FPS label
this.fpsLabel = new PIXI.BitmapText(
"0",
Font.makeFontOptions("medium", "left")
);
this.fpsLabel.anchor.set(0);
this.fpsLabel.position.set(10, 10);
this.fpsLabel.tint = 0xffffff;
if (Game.DEBUG_SHOW_FRAMERATE) {
this.app.stage.addChild(this.fpsLabel);
}
// Add background
this.backgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.backgroundSprite.tint = 0xffffff;
this.backgroundSprite.width = this.width;
this.backgroundSprite.height = this.height;
this.app.stage.addChildAt(this.backgroundSprite, 0);
// Inner background
this.innerBackgroundSprite = PIXI.Sprite.from(PIXI.Texture.WHITE);
this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;
this.innerBackgroundSprite.width = Game.TARGET_WIDTH;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;
this.stage.addChild(this.innerBackgroundSprite);
if (Save.hasGameState()) {
this.gotoGameScreen();
} else {
this.gotoMenuScreen();
}
this.resize();
this.notifyScreensOfSize();
// Register swipe listeners
// EventEmitter types issue - see https://github.com/pixijs/pixijs/issues/7429
const stage = this.backgroundSprite as any;
stage.interactive = true;
stage.on("pointerdown", (e: any) => {
this.isHoldRepeating = false;
this.startTouch = { x: e.data.global.x, y: e.data.global.y };
this.startTouchTime = Date.now();
});
stage.on("pointermove", (e: any) => {
if (!this.startTouch) return;
this.touchPosition.x = e.data.global.x;
this.touchPosition.y = e.data.global.y;
});
stage.on("pointerup", (e: any) => {
if (!this.startTouch) return;
if (this.isHoldRepeating) {
this.startTouch = null;
return;
}
const deltaTime = Date.now() - this.startTouchTime;
if (deltaTime > Game.SWIPE_MAX_TIME_MS) return;
const deltaX = e.data.global.x - this.startTouch.x;
const deltaY = e.data.global.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouch = null;
});
this.app.ticker.add((delta: number) => this.tick(delta));
}
playSound(name: string | string[]) {
if (this.muted) return;
const theName = Array.isArray(name) ? _.sample(name) : name;
const resource = this.resources["sound-" + theName];
if (resource?.sound) {
resource.sound.play();
}
}
performSwipe(deltaX: number, deltaY: number) {
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
const absMin = Math.min(absDeltaX, absDeltaY);
const absMax = Math.max(absDeltaX, absDeltaY);
// The other axis must be smaller than this to avoid a diagonal swipe
const confusionThreshold = absMax / 2;
if (absMin < confusionThreshold) {
if (absMax > Game.SWIPE_TRIGGER_THRESHOLD) {
if (absMax == absDeltaX) {
// Right or left
this.keydown(deltaX > 0 ? "KeyD" : "KeyA");
} else {
// Up or down
this.keydown(deltaY > 0 ? "KeyS" : "KeyW");
}
}
}
}
tick(delta: number) {
// delta is in frames
let elapsedSeconds = delta / 60;
Actions.tick(elapsedSeconds);
// If pointer is held down, trigger movements.
if (this.startTouch) {
const elapsed = Date.now() - this.startTouchTime;
if (this.isHoldRepeating) {
if (elapsed > Game.HOLD_REPEAT_TIME_MS) {
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
this.startTouchTime = Date.now();
}
} else if (elapsed > Game.HOLD_INITIAL_TIME_MS) {
// Held down for some time Trigger a swipe!
const deltaX = this.touchPosition.x - this.startTouch.x;
const deltaY = this.touchPosition.y - this.startTouch.y;
this.performSwipe(deltaX, deltaY);
// From now on, when we pass HOLD_REPEAT_TIME_MS, we perform another swipe
this.isHoldRepeating = true;
this.startTouchTime = Date.now();
}
}
this.fpsAverageShort.push(this.app.ticker.FPS);
this.fpsAverageLong.push(this.app.ticker.FPS);
// Keep most recent only
if (this.fpsAverageShort.length > 100) {
this.fpsAverageShort.shift();
}
if (this.fpsAverageLong.length > 1000) {
this.fpsAverageLong.shift();
}
const avgShort =
_.reduce(this.fpsAverageShort, (a, b) => a + b, 0) /
(this.fpsAverageShort.length === 0 ? 1 : this.fpsAverageShort.length);
const avgLong =
_.reduce(this.fpsAverageLong, (a, b) => a + b, 0) /
(this.fpsAverageLong.length === 0 ? 1 : this.fpsAverageLong.length);
this.fpsLabel.text =
"" +
Math.round(this.app.ticker.FPS) +
"\n" +
Math.round(avgShort) +
"\n" +
Math.round(avgLong) +
"\n";
}
notifyScreensOfSize() {
// Let screens now
for (const s of this.stage.children) {
if (s instanceof Screen) {
if (Game.MAINTAIN_RATIO) {
s.resize(Game.TARGET_WIDTH, Game.TARGET_HEIGHT);
} else {
s.resize(this.width / this.scale, this.height / this.scale);
}
}
}
}
resize() {
const rootStyle = getComputedStyle(document.documentElement);
const resizeInfo = {
width: window.innerWidth,
height: window.innerHeight,
safeInsets: {
left: parseInt(rootStyle.getPropertyValue('--safe-area-left')) || 0,
right: parseInt(rootStyle.getPropertyValue('--safe-area-right')) || 0,
top: parseInt(rootStyle.getPropertyValue('--safe-area-top')) || 0,
bottom: parseInt(rootStyle.getPropertyValue('--safe-area-bottom')) || 0
}
};
//this part resizes the canvas but keeps ratio the same
this.app.renderer.view.style.width = resizeInfo.width + "px";
this.app.renderer.view.style.height = resizeInfo.height + "px";
this.width = resizeInfo.width;
this.height = resizeInfo.height;
if (this.backgroundSprite) {
this.backgroundSprite.width = resizeInfo.width;
this.backgroundSprite.height = resizeInfo.height;
this.backgroundSprite.alpha = Game.MAINTAIN_RATIO ? 1 : 0;
}
this.app.renderer.resize(resizeInfo.width, resizeInfo.height);
// Ensure stage can fit inside the view!
// Scale it if it's not snug
// Stage side sits inside the safe insets
this.stageWidth = resizeInfo.width - resizeInfo.safeInsets.left - resizeInfo.safeInsets.right;
this.stageHeight = resizeInfo.height - resizeInfo.safeInsets.top - resizeInfo.safeInsets.bottom;
const targetScaleX = resizeInfo.width / Game.TARGET_WIDTH;
const targetScaleY = resizeInfo.height / Game.TARGET_HEIGHT;
const smoothScaling = Math.min(targetScaleX, targetScaleY);
// Pick integer scale which best fits
this.scale = !this.stretchDisplay
? Math.max(1, Math.floor(smoothScaling))
: smoothScaling;
this.stage.scale.set(this.scale, this.scale);
if (this.innerBackgroundSprite) {
if (Game.MAINTAIN_RATIO) {
this.innerBackgroundSprite.width = Game.TARGET_WIDTH * this.scale;
this.innerBackgroundSprite.height = Game.TARGET_HEIGHT * this.scale;
} else {
this.innerBackgroundSprite.width = resizeInfo.width;
this.innerBackgroundSprite.height = resizeInfo.height;
}
}
// Centre stage
if (Game.MAINTAIN_RATIO) {
this.stage.position.set(
resizeInfo.safeInsets.left + (this.stageWidth - Game.TARGET_WIDTH * this.scale) / 2,
resizeInfo.safeInsets.top + (this.stageHeight - Game.TARGET_HEIGHT * this.scale) / 2
);
if (this.innerBackgroundSprite) {
this.innerBackgroundSprite.position.set(this.stage.position.x, this.stage.position.y);
}
} else {
this.stage.position.set(resizeInfo.safeInsets.left, resizeInfo.safeInsets.top);
}
this.notifyScreensOfSize();
}
keydown(code: string) {
if (this.currentScreen) this.currentScreen.keydown(code);
}
}
| src/Game.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " // Save game state...\n const data = this.serialiseGameState(gameScreen);\n this.engine.save(\"currentGameState\", data);\n }\n static loadGameState(gameScreen: GameScreen) {\n // Save game state...\n const data = this.engine.load(\"currentGameState\");\n if (data) {\n // Load data into gameScreen...\n this.deserialiseGameState(gameScreen, data);",
"score": 0.8604611158370972
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " Actions.delay(delay),\n Actions.runFunc(() => {\n this.readyToMove = true;\n this.pumpQueuedMove();\n })\n ).play();\n if (this.state == \"play\")\n Save.saveGameState(this);\n }\n resizeAgain() {",
"score": 0.8245213031768799
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.7793013453483582
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " dungeonGrid.updateExitCoords();\n return dungeonGrid;\n }\n // Game state\n private static serialiseGameState(gameScreen: GameScreen) {\n return {\n level: gameScreen.level,\n state: gameScreen.state,\n score: gameScreen.score,\n dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),",
"score": 0.7755954265594482
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.7755798101425171
}
] | typescript | Save.loadGameState(gameScreen)) { |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
| if (!this.inBounds(targetCoord)) { |
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8526530265808105
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " }\n setPositionTo(\n actor: PIXI.Container,\n coords: Coords,\n isWall: boolean = false\n ) {\n if (isWall) {\n if ((actor as Wall).isHorizontal) {\n actor.position.set(\n this.cellSize * coords.col + (this.cellSize - actor.width) / 2,",
"score": 0.8421751856803894
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8282034993171692
},
{
"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": 0.8263617753982544
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " const dx = horizontal ? 1 : 0;\n const dy = horizontal ? 0 : 1;\n let startX = null,\n startY = null;\n startX = _.random(horizontal ? 0 : 1, dimension - 1);\n startY = _.random(horizontal ? 1 : 0, dimension - 1);\n const from = new Coords(startX, startY);\n const to = from.clone().add(dx, dy);\n // If there is already a wall here, skip!\n let alreadyExists = false;",
"score": 0.8239759802818298
}
] | typescript | if (!this.inBounds(targetCoord)) { |
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": 0.862179160118103
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " state: GameState = \"play\";\n modals: PIXI.Container[] = [];\n score: number;\n scoreLabel: PIXI.BitmapText;\n prevWidth: number = 0;\n prevHeight: number = 0;\n constructor() {\n super();\n // Setup\n this.readyToMove = true;",
"score": 0.846015453338623
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.8299211263656616
},
{
"filename": "src/screens/game/character/Character.ts",
"retrieved_chunk": " sprite: PIXI.Sprite;\n heartsHolder: PIXI.Container;\n constructor(backgroundPath: string) {\n super();\n this.coords = new Coords(0, 0);\n this.sprite = PIXI.Sprite.from(Game.tex(backgroundPath));\n this.sprite.anchor.set(0.5, 1);\n this.addChild(this.sprite);\n // Add holder for hearts\n this.heartsHolder = new PIXI.Container();",
"score": 0.8205705881118774
},
{
"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": 0.8205116987228394
}
] | typescript | Save.initialise(); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c. | coords = coords; |
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8291405439376831
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.8202337026596069
},
{
"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": 0.8171087503433228
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.815744936466217
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8146945238113403
}
] | typescript | coords = coords; |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
| private static createCharacter(type: CharacterType, hp: number, coords: Coords) { |
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/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": 0.8004150986671448
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.7967543601989746
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.7869408130645752
},
{
"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": 0.7770119309425354
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " withEnemiesAsObstacles: boolean,\n stopAt: Coords = null\n ): { distance: number[][]; col: number[][]; row: number[][] } {\n const current = target.clone();\n const visited: boolean[][] = [];\n const tentativeDistance: number[][] = [];\n const tentativeSourceCol: number[][] = [];\n const tentativeSourceRow: number[][] = [];\n for (let i = 0; i < this.dimension; i++) {\n // col",
"score": 0.7722089886665344
}
] | 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": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8440471291542053
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n return { didMove: true, delay };\n }\n addPotentialNeighbour(\n list: Coords[],\n coords: Coords,\n dx: number,\n dy: number\n ) {\n if (!this.inBounds(coords.col + dx, coords.row + dy)) {",
"score": 0.8164815306663513
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " state: GameState = \"play\";\n modals: PIXI.Container[] = [];\n score: number;\n scoreLabel: PIXI.BitmapText;\n prevWidth: number = 0;\n prevHeight: number = 0;\n constructor() {\n super();\n // Setup\n this.readyToMove = true;",
"score": 0.8116793632507324
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " this.sprite.width = this.isHorizontal ? withSize : againstSize;\n this.sprite.height = this.isHorizontal ? againstSize : withSize;\n }\n blocks(start: Coords, dx: number, dy: number) {\n if (this.isHorizontal) {\n if (dy == 0) return false;\n if (dy < 0 && this.from.equals(start)) {\n // Hitting a wall\n return true;\n }",
"score": 0.8105736970901489
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Animate to the new position\n this.makeMoveTo(character).play();\n return { didMove: true, delay: 0.05, wentThroughExit: false };\n }\n doesWallSeparate(start: Coords, dx: number, dy: number) {\n for (const w of this.walls) {\n if (w.blocks(start, dx, dy)) {\n return true;\n }\n }",
"score": 0.8044633865356445
}
] | typescript | ((actor as Wall).isHorizontal) { |
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": " // 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": 0.8007919788360596
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7913181185722351
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7632904648780823
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Delete all old walls\n for (const w of this.walls) {\n Actions.fadeOutAndRemove(w, 0.2).play();\n }\n this.walls = Wall.randomLayout(numWalls, this.dimension);\n // Add some new walls... they must generate any closed areas\n this.drawWalls(this.walls);\n }\n drawWalls(walls: Wall[]) {\n for (const w of walls) {",
"score": 0.7498642206192017
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7389565706253052
}
] | typescript | dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
}; |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
| exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
}; |
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // 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": 0.8007919788360596
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7913181185722351
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7632904648780823
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Delete all old walls\n for (const w of this.walls) {\n Actions.fadeOutAndRemove(w, 0.2).play();\n }\n this.walls = Wall.randomLayout(numWalls, this.dimension);\n // Add some new walls... they must generate any closed areas\n this.drawWalls(this.walls);\n }\n drawWalls(walls: Wall[]) {\n for (const w of walls) {",
"score": 0.7498642206192017
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7389565706253052
}
] | 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": 0.8295907974243164
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " unsetExitCell() {\n this.exitCoords = null;\n this.updateExitCoords();\n }\n setExitCell(minDistanceFromPlayer: number = 7) {\n const possibles = [];\n const backups = [];\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n for (let i = 0; i < this.dimension; i++) {",
"score": 0.8193467855453491
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8131169080734253
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7980122566223145
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7928845286369324
}
] | typescript | dungeonGrid.addCharacter(c); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
| exitDir: this.serialiseCoords(dungeonGrid.exitDir),
}; |
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // 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": 0.8007919788360596
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7913181185722351
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7632904648780823
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Delete all old walls\n for (const w of this.walls) {\n Actions.fadeOutAndRemove(w, 0.2).play();\n }\n this.walls = Wall.randomLayout(numWalls, this.dimension);\n // Add some new walls... they must generate any closed areas\n this.drawWalls(this.walls);\n }\n drawWalls(walls: Wall[]) {\n for (const w of walls) {",
"score": 0.7498642206192017
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7389565706253052
}
] | 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.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.7873222231864929
},
{
"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": 0.7729741334915161
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " this.walls.push(...walls);\n this.edgeWalls.push(...walls);\n }\n }\n getRandomEmptyCell(): Coords {\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const shuffledCoords = _.shuffle(this.coords);\n for (const coord of shuffledCoords) {\n if (this.exitCoords && this.exitCoords.equals(coord)) continue;",
"score": 0.7634408473968506
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7521052956581116
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7297278642654419
}
] | typescript | drawWalls(dungeonGrid.walls); |
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": " stair.height = this.cellSize * 0.8;\n const offset2 = (this.cellSize - stair.width) / 2;\n stair.position.set(\n i * this.cellSize + offset2,\n j * this.cellSize + offset2\n );\n stair.visible = false;\n col2.push(stair);\n this.addChild(stair);\n }",
"score": 0.7909524440765381
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.7844423055648804
},
{
"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": 0.7786159515380859
},
{
"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": 0.7751359939575195
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " dungeonGrid.updateExitCoords();\n return dungeonGrid;\n }\n // Game state\n private static serialiseGameState(gameScreen: GameScreen) {\n return {\n level: gameScreen.level,\n state: gameScreen.state,\n score: gameScreen.score,\n dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),",
"score": 0.7693142890930176
}
] | typescript | position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
| state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
}; |
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.7928367257118225
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.7811821699142456
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.7767413854598999
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.77203369140625
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " unsetExitCell() {\n this.exitCoords = null;\n this.updateExitCoords();\n }\n setExitCell(minDistanceFromPlayer: number = 7) {\n const possibles = [];\n const backups = [];\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n for (let i = 0; i < this.dimension; i++) {",
"score": 0.7676249742507935
}
] | typescript | state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: 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": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.8103916049003601
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8079735636711121
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.8019789457321167
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " w.alpha = 0;\n Actions.fadeIn(w, 0.2).play();\n this.wallsHolder.addChild(w);\n w.setCellSize(this.cellSize);\n // Place in the correct place\n this.setPositionTo(w, w.from, true);\n }\n }\n addCharacter(character: Character) {\n character.scale.set(0.2);",
"score": 0.8019408583641052
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.8015235662460327
}
] | typescript | const nextGrid = new DungeonGrid(this, Game.DIMENSION); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid | : this.serialiseDungeonGrid(gameScreen.dungeonGrid),
}; |
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.7706601619720459
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.7606630921363831
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.7591499090194702
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.755050778388977
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " unsetExitCell() {\n this.exitCoords = null;\n this.updateExitCoords();\n }\n setExitCell(minDistanceFromPlayer: number = 7) {\n const possibles = [];\n const backups = [];\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n for (let i = 0; i < this.dimension; i++) {",
"score": 0.7545474171638489
}
] | typescript | : this.serialiseDungeonGrid(gameScreen.dungeonGrid),
}; |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
| score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
}; |
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": "type GameState = \"play\" | \"gameover\";\nexport default class GameScreen extends Screen {\n playerCharacter: PlayerCharacter;\n dungeonGrid: DungeonGrid;\n darkOverlay: PIXI.Container;\n gameContainer: PIXI.Container;\n gameOverModal: GameOverModal;\n readyToMove: boolean;\n queuedMove: { dx: number; dy: number };\n level: number;",
"score": 0.7928367257118225
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.7811821699142456
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " if (!Save.loadGameState(gameScreen)) {\n gameScreen.nextLevel();\n }\n this.setScreen(gameScreen);\n }\n gotoMenuScreen() {\n this.setScreen(new MenuScreen());\n }\n setScreen(screen: Screen) {\n if (this.currentScreen != null) {",
"score": 0.7767413854598999
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.77203369140625
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " unsetExitCell() {\n this.exitCoords = null;\n this.updateExitCoords();\n }\n setExitCell(minDistanceFromPlayer: number = 7) {\n const possibles = [];\n const backups = [];\n let dijks = null;\n dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n for (let i = 0; i < this.dimension; i++) {",
"score": 0.7676249742507935
}
] | 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": 0.8167204260826111
},
{
"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": 0.7896029949188232
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7837750911712646
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7795907855033875
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.7788361310958862
}
] | typescript | .gameContainer.removeChild(gameScreen.dungeonGrid); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
| Actions.clear(this.playerCharacter); |
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
| src/screens/game/GameScreen.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n if (withEnemiesAsObstacles) {\n const char = this.getCharacterAt(coords.col + dx, coords.row + dy);\n if (char && char.isEnemy) {\n // There is a monster on the target square, ignore!\n return;\n }\n }\n const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;\n if (",
"score": 0.8160518407821655
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " this.cellSize * coords.row + -actor.height / 2\n );\n } else {\n actor.position.set(\n this.cellSize * coords.col + -actor.width / 2,\n this.cellSize * coords.row + (this.cellSize - actor.height) / 2\n );\n }\n } else {\n actor.position.set(",
"score": 0.8015614748001099
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.alpha = 0;\n Actions.fadeIn(character, 0.2).play();\n this.characters.push(character);\n this.charactersHolder.addChild(character);\n // Place in the correct place!\n this.setPositionTo(character, character.coords);\n }\n getCharacterAt(col: number | Coords, row: number = null): Character {\n let c = 0;\n let r = 0;",
"score": 0.7888531684875488
},
{
"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": 0.7824646234512329
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " startCoords.row = edge == 0 ? 0 : dimension;\n endCoords.row = startCoords.row;\n } else {\n // Left/right\n startCoords.row = i;\n endCoords.row = i + 1;\n startCoords.col = edge == 1 ? 0 : dimension;\n endCoords.col = startCoords.col;\n }\n walls.push(new Wall(startCoords, endCoords));",
"score": 0.7815247774124146
}
] | typescript | Actions.clear(this.playerCharacter); |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);
gameScreen. | playerCharacter = pc; |
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8539369106292725
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7938092947006226
},
{
"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": 0.7715553045272827
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7706478834152222
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7591102719306946
}
] | typescript | playerCharacter = pc; |
import Engine from "./engine/Engine";
import LocalStorageEngine from "./engine/LocalStorageEngine";
import MemoryEngine from "./engine/MemoryEngine";
import GameScreen from "../screens/game/GameScreen";
import DungeonGrid from "../screens/game/grid/DungeonGrid";
import Wall from "../screens/game/grid/Wall";
import { PlayerCharacter, EnemyCharacter, Character } from "../screens/game/character";
import type { CharacterType } from "../screens/game/character/Character";
import { Coords } from "utils";
export default class Save {
static engine: Engine;
static initialise() {
if (LocalStorageEngine.isSupported()) {
this.engine = new LocalStorageEngine();
} else {
this.engine = new MemoryEngine();
}
}
// Coords
private static serialiseCoords(coords: Coords) {
if (!coords) return null;
return [coords.col, coords.row];
}
private static deserialiseCoords(coords: any): Coords {
if (!coords) return null;
return new Coords(coords[0], coords[1]);
}
// Walls
private static serialiseWalls(walls: Wall[]) {
return walls.map((w) => {
return {
from: this.serialiseCoords(w.from),
to: this.serialiseCoords(w.to),
};
});
}
private static deserialiseWalls(walls: any): Wall[] {
return walls.map(
(w: any) =>
new Wall(this.deserialiseCoords(w.from), this.deserialiseCoords(w.to))
);
}
// Characters
private static serialiseCharacters(characters: Character[]) {
return characters.map((c) => {
return {
type: c.type,
coords: this.serialiseCoords(c.coords),
hp: c.hp,
};
});
}
private static deserialiseCharacters(characters: any): Character[] {
return characters.map(
(c: any) => this.createCharacter(c.type, c.hp, this.deserialiseCoords(c.coords))
);
}
private static createCharacter(type: CharacterType, hp: number, coords: Coords) {
let c;
if (type === "player") {
c = new PlayerCharacter();
} else {
c = new EnemyCharacter(type);
}
c.coords = coords;
c.hp = hp;
return c;
}
// Dungeon grid
private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {
return {
characters: this.serialiseCharacters(dungeonGrid.characters),
walls: this.serialiseWalls(dungeonGrid.walls),
edgeWalls: this.serialiseWalls(dungeonGrid.edgeWalls),
dimension: dungeonGrid.dimension,
exitCoords: this.serialiseCoords(dungeonGrid.exitCoords),
exitDir: this.serialiseCoords(dungeonGrid.exitDir),
};
}
private static deserialiseDungeonGrid(gameScreen: GameScreen, data: any) {
const dungeonGrid = new DungeonGrid(gameScreen, data.dimension);
const chars = this.deserialiseCharacters(data.characters);
for (const c of chars) {
dungeonGrid.addCharacter(c);
}
dungeonGrid.walls = this.deserialiseWalls(data.walls);
dungeonGrid.edgeWalls = this.deserialiseWalls(data.edgeWalls);
dungeonGrid.exitCoords = this.deserialiseCoords(data.exitCoords);
dungeonGrid.exitDir = this.deserialiseCoords(data.exitDir);
dungeonGrid.drawWalls(dungeonGrid.walls);
dungeonGrid.updateExitCoords();
return dungeonGrid;
}
// Game state
private static serialiseGameState(gameScreen: GameScreen) {
return {
level: gameScreen.level,
state: gameScreen.state,
score: gameScreen.score,
dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),
};
}
private static deserialiseGameState(gameScreen: GameScreen, data: any) {
gameScreen.level = data.level;
gameScreen.state = data.state;
gameScreen.score = data.score;
// Remove the old dungeon grid:
if (gameScreen.dungeonGrid) {
gameScreen.gameContainer.removeChild(gameScreen.dungeonGrid);
}
gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);
gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);
| const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer); |
gameScreen.playerCharacter = pc;
gameScreen.incScore(0);
}
static hasGameState() {
return !!this.engine.load("currentGameState");
}
static saveGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.serialiseGameState(gameScreen);
this.engine.save("currentGameState", data);
}
static loadGameState(gameScreen: GameScreen) {
// Save game state...
const data = this.engine.load("currentGameState");
if (data) {
// Load data into gameScreen...
this.deserialiseGameState(gameScreen, data);
return true;
}
return false;
}
static clearGameState() {
this.engine.remove("currentGameState");
}
}
| src/save/Save.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.resizeAgain();\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n }\n this.dungeonGrid = nextGrid;\n this.dungeonGrid.addCharacter(this.playerCharacter);\n this.dungeonGrid.clearEnemies();\n this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));\n this.dungeonGrid.setExitCell();\n this.gameContainer.addChild(this.dungeonGrid);",
"score": 0.8611597418785095
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7870186567306519
},
{
"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": 0.7767688035964966
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7694371342658997
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.level++;\n this.readyToMove = true;\n const nextGrid = new DungeonGrid(this, Game.DIMENSION);\n if (this.dungeonGrid) {\n // Slide the new one in!\n if (Game.EXIT_TYPE == \"door\" && this.dungeonGrid.exitDir) {\n const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;\n const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;\n nextGrid.position.set(\n this.dungeonGrid.position.x + dx,",
"score": 0.7673404216766357
}
] | typescript | const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
| character.scale.set(0.2); |
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.8294328451156616
},
{
"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": 0.8042875528335571
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.8021049499511719
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.gameOverModal.alpha = 0;\n Actions.sequence(\n Actions.delay(2),\n Actions.fadeIn(this.gameOverModal, 0.2)\n ).play();\n this.addChild(this.gameOverModal);\n this.resizeAgain();\n }\n nextLevel() {\n this.incScore(1);",
"score": 0.7894330024719238
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7778452634811401
}
] | 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": " }\n if (withEnemiesAsObstacles) {\n const char = this.getCharacterAt(coords.col + dx, coords.row + dy);\n if (char && char.isEnemy) {\n // There is a monster on the target square, ignore!\n return;\n }\n }\n const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;\n if (",
"score": 0.7702193260192871
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.7616532444953918
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return false;\n }\n moveEnemies() {\n let delay = 0;\n // 1. Dijkstra the grid, ignoring enemies\n // Pick the closest character\n const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const enemiesAndDistances = [];\n for (const char of this.characters) {\n if (char.isEnemy) {",
"score": 0.7577351331710815
},
{
"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": 0.749512791633606
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;\n this.stage.addChild(this.innerBackgroundSprite);\n if (Save.hasGameState()) {\n this.gotoGameScreen();\n } else {\n this.gotoMenuScreen();\n }\n this.resize();",
"score": 0.7421592473983765
}
] | 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": " const player = targetCharacter as PlayerCharacter;\n // Take a damage!\n if (player.damage(1)) {\n this.gameScreen.gameOver();\n }\n return { didMove: true, delay, wentThroughExit: false };\n } else {\n return { didMove: false, delay, wentThroughExit: false };\n }\n }",
"score": 0.8476585745811462
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.8470388650894165
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " try {\n const targetCharacter = this.getCharacterAt(targetCoord);\n if (targetCharacter) {\n let delay = this.bumpAnimation(character, dx, dy);\n if (character.isPlayer && targetCharacter.isEnemy) {\n // Attack the character\n Game.instance.playSound(\"attack\");\n delay += this.damageEnemy(targetCharacter as EnemyCharacter);\n return { didMove: true, delay, wentThroughExit: false };\n } else if (character.isEnemy && targetCharacter.isPlayer) {",
"score": 0.8432832360267639
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return false;\n }\n moveEnemies() {\n let delay = 0;\n // 1. Dijkstra the grid, ignoring enemies\n // Pick the closest character\n const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const enemiesAndDistances = [];\n for (const char of this.characters) {\n if (char.isEnemy) {",
"score": 0.8423224091529846
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8162705898284912
}
] | typescript | const enemyMoveResult = this.dungeonGrid.moveEnemies(); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
| const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
); |
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
| src/screens/game/GameScreen.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8660547733306885
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Hitting a wall?\n if (this.doesWallSeparate(character.coords, dx, dy)) {\n Game.instance.playSound(\"bump\");\n const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Is there another character here?",
"score": 0.8527398109436035
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return time;\n }\n damageEnemy(targetCharacter: EnemyCharacter) {\n let delay = 0;\n const didDie = targetCharacter.damage(1);\n if (didDie) {\n // Remove from characters array\n const index = this.characters.indexOf(targetCharacter);\n if (index >= 0) {\n this.characters.splice(index, 1);",
"score": 0.8508711457252502
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " // Out of bounds, ignore!\n return;\n }\n if (this.doesWallSeparate(coords, dx, dy)) {\n // There is no path, ignore!\n return;\n }\n const char = this.getCharacterAt(coords.col + dx, coords.row + dy);\n if (char && char.isEnemy) {\n // There is a monster on the target square, ignore!",
"score": 0.8490538597106934
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n }\n return null;\n }\n bumpAnimation(character: Character, dx: number, dy: number) {\n const time = 0.1;\n Actions.sequence(\n this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),\n this.makeMoveTo(character, 0, 0, time / 2)\n ).play();",
"score": 0.8425398468971252
}
] | typescript | const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8));
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
| if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) { |
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
| src/screens/game/GameScreen.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character.coords.equals(this.exitCoords) &&\n Game.EXIT_TYPE == \"door\" &&\n this.exitDir &&\n this.exitDir.equals(dx, dy)\n ) {\n // We are going through the exit!\n return { didMove: true, delay: 0, wentThroughExit: true };\n }\n // Hitting the edge of the grid\n Game.instance.playSound(\"bump\");",
"score": 0.8822339773178101
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Hitting a wall?\n if (this.doesWallSeparate(character.coords, dx, dy)) {\n Game.instance.playSound(\"bump\");\n const delay = this.bumpAnimation(character, dx, dy);\n return { didMove: false, delay, wentThroughExit: false };\n }\n // Is there another character here?",
"score": 0.8640118837356567
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " const player = targetCharacter as PlayerCharacter;\n // Take a damage!\n if (player.damage(1)) {\n this.gameScreen.gameOver();\n }\n return { didMove: true, delay, wentThroughExit: false };\n } else {\n return { didMove: false, delay, wentThroughExit: false };\n }\n }",
"score": 0.8567696809768677
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " }\n this.updateExitCoords();\n }\n updateExitCoords() {\n if (Game.EXIT_TYPE == \"stairs\") {\n this.cellStairs.forEach((a, i) =>\n a.forEach(\n (stairs, j) =>\n (stairs.visible =\n this.exitCoords &&",
"score": 0.8518494963645935
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " character: Character,\n dx: number,\n dy: number\n ): { didMove: boolean; delay: number; wentThroughExit: boolean } {\n // Check the target space is available\n const targetCoord = character.coords.clone().add(dx, dy);\n // Edge of grid!\n if (!this.inBounds(targetCoord)) {\n if (\n this.exitCoords &&",
"score": 0.8505221605300903
}
] | typescript | if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) { |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import Game from "Game";
import Screen from "../Screen";
import { Font } from "utils";
import Save from "../../save/Save";
import DungeonGrid from "./grid/DungeonGrid";
import { PlayerCharacter, EnemyCharacter } from "./character";
import GameOverModal from "./GameOverModal";
import * as _ from "underscore";
type GameState = "play" | "gameover";
export default class GameScreen extends Screen {
playerCharacter: PlayerCharacter;
dungeonGrid: DungeonGrid;
darkOverlay: PIXI.Container;
gameContainer: PIXI.Container;
gameOverModal: GameOverModal;
readyToMove: boolean;
queuedMove: { dx: number; dy: number };
level: number;
state: GameState = "play";
modals: PIXI.Container[] = [];
score: number;
scoreLabel: PIXI.BitmapText;
prevWidth: number = 0;
prevHeight: number = 0;
constructor() {
super();
// Setup
this.readyToMove = true;
this.queuedMove = null;
this.level = 0;
this.score = 0;
this.gameContainer = new PIXI.Container();
this.addChild(this.gameContainer);
// Score
this.scoreLabel = new PIXI.BitmapText("0", Font.makeFontOptions("small"));
this.scoreLabel.anchor.set(0.5);
this.scoreLabel.tint = 0xffffff;
this.gameContainer.addChild(this.scoreLabel);
// Add a character
this.playerCharacter = new PlayerCharacter();
this.playerCharacter.coords.set(2, 4);
// Dark overlay
this.darkOverlay = new PIXI.Container();
this.darkOverlay.visible = false;
{
const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);
rect.tint = 0;
rect.alpha = 0.8;
this.darkOverlay.addChild(rect);
}
this.addChild(this.darkOverlay);
}
incScore(amt: number) {
this.score += amt;
this.scoreLabel.text = "" + this.score;
}
showDarkOverlay(delay: number = 0) {
this.darkOverlay.visible = true;
this.darkOverlay.alpha = 0;
Actions.sequence(
Actions.delay(delay),
Actions.fadeIn(this.darkOverlay, 0.2)
).play();
}
hideDarkOverlay(delay: number = 0) {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.darkOverlay.visible = false;
this.darkOverlay.alpha = 0;
})
).play();
}
gameOver() {
this.state = "gameover";
Save.clearGameState();
this.showDarkOverlay(0.5);
this.gameOverModal = new GameOverModal(this);
this.gameOverModal.alpha = 0;
Actions.sequence(
Actions.delay(2),
Actions.fadeIn(this.gameOverModal, 0.2)
).play();
this.addChild(this.gameOverModal);
this.resizeAgain();
}
nextLevel() {
this.incScore(1);
this.level++;
this.readyToMove = true;
const nextGrid = new DungeonGrid(this, Game.DIMENSION);
if (this.dungeonGrid) {
// Slide the new one in!
if (Game.EXIT_TYPE == "door" && this.dungeonGrid.exitDir) {
const dx = this.dungeonGrid.exitDir.col * this.dungeonGrid.edgeSize;
const dy = this.dungeonGrid.exitDir.row * this.dungeonGrid.edgeSize;
nextGrid.position.set(
this.dungeonGrid.position.x + dx,
this.dungeonGrid.position.y + dy
);
nextGrid.alpha = 0;
Actions.parallel(
Actions.fadeIn(nextGrid, 0.2),
Actions.moveTo(
nextGrid,
this.dungeonGrid.position.x,
this.dungeonGrid.position.y,
0.5
)
).play();
Actions.sequence(
Actions.parallel(
Actions.fadeOut(this.dungeonGrid, 0.2),
Actions.moveTo(
this.dungeonGrid,
this.dungeonGrid.position.x - dx,
this.dungeonGrid.position.y - dy,
0.5
)
),
Actions.remove(this.dungeonGrid)
).play();
// Move the player to opposite side of the dungeon
if (this.dungeonGrid.exitDir.col != 0) {
this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;
} else {
this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;
}
// Ensure that any pending animations don't intefere with positioning in next level
Actions.clear(this.playerCharacter);
} else {
nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();
}
} else {
// If this is the first grid, we need to place it in the correct place
this.resizeAgain();
nextGrid.alpha = 0;
Actions.fadeIn(nextGrid, 0.5).play();
}
this.dungeonGrid = nextGrid;
this.dungeonGrid.addCharacter(this.playerCharacter);
this.dungeonGrid.clearEnemies();
| this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8)); |
this.dungeonGrid.setExitCell();
this.gameContainer.addChild(this.dungeonGrid);
const monsterLevel = Math.min(this.level, 20);
const numEnemies =
2 +
Math.min(5, Math.floor(monsterLevel / 5)) +
Math.min(10, Math.max(0, monsterLevel - 40));
this.spawnEnemy(numEnemies);
Save.saveGameState(this);
}
spawnEnemy(n: number) {
for (let i = 0; i < n; i++) {
const enemyCharacter = new EnemyCharacter("enemy1");
// Random empty cell
const coord = this.dungeonGrid.getRandomEmptyCell();
if (!coord) return;
enemyCharacter.coords.set(coord.col, coord.row);
this.dungeonGrid.addCharacter(enemyCharacter);
}
}
pumpQueuedMove() {
if (this.queuedMove) {
this.doMove(this.queuedMove.dx, this.queuedMove.dy);
this.queuedMove = null;
}
}
doMove(dx: number, dy: number) {
if (this.state != "play") {
// Can't move!
return;
}
// 1. If you aren't yet ready to move, then queue the direction
if (this.readyToMove) {
// 2. Otherwise, do the move
const moveResult = this.dungeonGrid.moveCharacter(
this.playerCharacter,
dx,
dy
);
// 3. If the move was successful, then say we aren't ready to move yet
if (moveResult.wentThroughExit) {
// Load in new level
// Snazzy animation too, if I could handle it!
this.nextLevel();
} else if (moveResult.didMove) {
this.postMove(moveResult.delay);
} else {
this.readyToMove = false;
// After a delay, let the player move again
Actions.sequence(
Actions.delay(moveResult.delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
}
} else {
this.queuedMove = { dx, dy };
}
}
postMove(delay: number) {
this.readyToMove = false;
// Any character on exit
let onExit = false;
if (Game.EXIT_TYPE == "stairs" && this.dungeonGrid.exitCoords) {
if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {
onExit = true;
}
}
if (onExit) {
this.nextLevel();
} else {
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
if (this.state != "gameover") {
this.doEnemyMove();
}
})
).play();
}
if (this.state == "play")
Save.saveGameState(this);
}
doEnemyMove() {
// Move enemies, after a delay!
const enemyMoveResult = this.dungeonGrid.moveEnemies();
let delay = enemyMoveResult.delay;
// After a delay, let the player move again
// Fudge this value, I like to be able to move really soon
Actions.sequence(
Actions.delay(delay),
Actions.runFunc(() => {
this.readyToMove = true;
this.pumpQueuedMove();
})
).play();
if (this.state == "play")
Save.saveGameState(this);
}
resizeAgain() {
this.resize(this.prevWidth, this.prevHeight);
}
resize(width: number, height: number) {
if (!this.parent) return;
this.prevWidth = width;
this.prevHeight = height;
this.darkOverlay.width = Game.instance.width / Game.instance.scale;
this.darkOverlay.height = Game.instance.height / Game.instance.scale;
this.darkOverlay.position.set(
-this.parent.position.x / Game.instance.scale,
-this.parent.position.y / Game.instance.scale
);
// Dungeon grid position
let dungeonY = (height - this.dungeonGrid.edgeSize) / 2;
let dungeonX = (width - this.dungeonGrid.edgeSize) / 2;
// Grids
// Move it
this.dungeonGrid.position.set(dungeonX, dungeonY);
this.scoreLabel.position.set(dungeonX + this.dungeonGrid.edgeSize / 2, 16);
// Modals
const modals = [this.gameOverModal];
for (const m of modals) {
if (m) {
// Centre it!
const x = (width - Game.TARGET_WIDTH) / 2;
const y = (height - Game.TARGET_HEIGHT) / 2;
m.position.set(x, y);
}
}
}
keydown(code: string) {
let dx = 0;
let dy = 0;
if (code == "ArrowLeft" || code == "KeyA") {
dx = -1;
} else if (code == "ArrowRight" || code == "KeyD") {
dx = 1;
} else if (code == "ArrowUp" || code == "KeyW") {
dy = -1;
} else if (code == "ArrowDown" || code == "KeyS") {
dy = 1;
}
if (dx != 0 || dy != 0) {
// Attempted move
this.doMove(dx, dy);
}
}
}
| src/screens/game/GameScreen.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " return false;\n }\n moveEnemies() {\n let delay = 0;\n // 1. Dijkstra the grid, ignoring enemies\n // Pick the closest character\n const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);\n const enemiesAndDistances = [];\n for (const char of this.characters) {\n if (char.isEnemy) {",
"score": 0.8019746541976929
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " gameScreen.dungeonGrid = this.deserialiseDungeonGrid(gameScreen, data.dungeonGrid);\n gameScreen.gameContainer.addChild(gameScreen.dungeonGrid);\n const pc = gameScreen.dungeonGrid.characters.find(c => c.isPlayer);\n gameScreen.playerCharacter = pc;\n gameScreen.incScore(0);\n }\n static hasGameState() {\n return !!this.engine.load(\"currentGameState\");\n }\n static saveGameState(gameScreen: GameScreen) {",
"score": 0.8011934757232666
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " this.innerBackgroundSprite.tint = Game.BACKGROUND_COLOUR;\n this.innerBackgroundSprite.width = Game.TARGET_WIDTH;\n this.innerBackgroundSprite.height = Game.TARGET_HEIGHT;\n this.stage.addChild(this.innerBackgroundSprite);\n if (Save.hasGameState()) {\n this.gotoGameScreen();\n } else {\n this.gotoMenuScreen();\n }\n this.resize();",
"score": 0.7947056293487549
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " w.alpha = 0;\n Actions.fadeIn(w, 0.2).play();\n this.wallsHolder.addChild(w);\n w.setCellSize(this.cellSize);\n // Place in the correct place\n this.setPositionTo(w, w.from, true);\n }\n }\n addCharacter(character: Character) {\n character.scale.set(0.2);",
"score": 0.7943251132965088
},
{
"filename": "src/screens/game/grid/DungeonGrid.ts",
"retrieved_chunk": " } catch (e) {\n // The game is over\n this.gameScreen.gameOver();\n return { didMove: true, delay: 0, wentThroughExit: false };\n }\n // Move the character\n if (character.isPlayer) {\n Game.instance.playSound([\"step1\", \"step2\", \"step3\", \"step4\"]);\n }\n character.coords.set(targetCoord);",
"score": 0.7941692471504211
}
] | typescript | this.dungeonGrid.generateWalls(Math.min(3 + this.level, 8)); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
| dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false); |
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8262674808502197
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7760182023048401
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " dungeonGrid.updateExitCoords();\n return dungeonGrid;\n }\n // Game state\n private static serialiseGameState(gameScreen: GameScreen) {\n return {\n level: gameScreen.level,\n state: gameScreen.state,\n score: gameScreen.score,\n dungeonGrid: this.serialiseDungeonGrid(gameScreen.dungeonGrid),",
"score": 0.7754784822463989
},
{
"filename": "src/save/Save.ts",
"retrieved_chunk": " c = new PlayerCharacter();\n } else {\n c = new EnemyCharacter(type);\n }\n c.coords = coords;\n c.hp = hp;\n return c;\n }\n // Dungeon grid\n private static serialiseDungeonGrid(dungeonGrid: DungeonGrid) {",
"score": 0.7675241231918335
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.760311484336853
}
] | typescript | dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions | .fadeOutAndRemove(c, 0.2).play(); |
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const monsterLevel = Math.min(this.level, 20);\n const numEnemies =\n 2 +\n Math.min(5, Math.floor(monsterLevel / 5)) +\n Math.min(10, Math.max(0, monsterLevel - 40));\n this.spawnEnemy(numEnemies);\n Save.saveGameState(this);\n }\n spawnEnemy(n: number) {\n for (let i = 0; i < n; i++) {",
"score": 0.8442036509513855
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8380022644996643
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.8118787407875061
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.81009840965271
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.7944366931915283
}
] | 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/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": 0.8061764240264893
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.7984057664871216
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.7817696332931519
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.gameOverModal.alpha = 0;\n Actions.sequence(\n Actions.delay(2),\n Actions.fadeIn(this.gameOverModal, 0.2)\n ).play();\n this.addChild(this.gameOverModal);\n this.resizeAgain();\n }\n nextLevel() {\n this.incScore(1);",
"score": 0.7758448123931885
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Add a character\n this.playerCharacter = new PlayerCharacter();\n this.playerCharacter.coords.set(2, 4);\n // Dark overlay\n this.darkOverlay = new PIXI.Container();\n this.darkOverlay.visible = false;\n {\n const rect = PIXI.Sprite.from(PIXI.Texture.WHITE);\n rect.tint = 0;\n rect.alpha = 0.8;",
"score": 0.7752350568771362
}
] | 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/Wall.ts",
"retrieved_chunk": " viableConnectingWalls.push(w);\n }\n if (viableConnectingWalls.length > 0) {\n const coords = _.sample(viableConnectingWalls);\n prospective = new Wall(coords[0], coords[1]);\n }\n }\n if (prospective == null) {\n // Random wall\n const horizontal = Math.random() < 0.5;",
"score": 0.8221402168273926
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " let prospective: Wall = null;\n if (walls.length > 0 && Math.random() < Wall.CONNECTION_PREFERRED_RATIO) {\n // Try to join onto an existing wall\n const prevWall = _.sample(walls);\n const connectingWalls = [];\n if (prevWall.isHorizontal) {\n connectingWalls.push(\n // 2 parallel\n [prevWall.from.clone().add(-1, 0), prevWall.to.clone().add(-1, 0)],\n [prevWall.from.clone().add(1, 0), prevWall.to.clone().add(1, 0)],",
"score": 0.782285749912262
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " // Generate walls which go all around the edges\n const walls: Wall[] = [];\n for (let edge = 0; edge < 4; edge++) {\n for (let i = 0; i < dimension; i++) {\n const startCoords = new Coords(0, 0);\n const endCoords = new Coords(0, 0);\n if (edge == 0 || edge == 2) {\n // Top/bottom\n startCoords.col = i;\n endCoords.col = i + 1;",
"score": 0.7816159725189209
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " } else {\n // If it's vertical, you can't go on either edge\n if (w[0].col == 0 || w[0].col == dimension - 1) continue;\n }\n // If another wall here, don't add\n for (const w2 of walls) {\n if (w2.from.equals(w[0]) && w2.to.equals(w[1])) {\n continue outer;\n }\n }",
"score": 0.7796872854232788
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " col.push(false);\n }\n flood.push(col);\n }\n // Create N wall segments. If a wall segment would create a blockage, don't add it.\n let limit = 0;\n while (walls.length < numWalls) {\n if (limit++ > 1000) {\n break;\n }",
"score": 0.7792472243309021
}
] | 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/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8656651377677917
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8470166325569153
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " dx: number = 0,\n dy: number = 0,\n time: number = 0.1\n ): Action {\n return Actions.moveTo(\n character,\n this.cellSize * (character.coords.col + dx) + this.cellSize / 2,\n this.cellSize * (character.coords.row + dy) + this.cellSize - 3,\n time\n );",
"score": 0.8410130739212036
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const monsterLevel = Math.min(this.level, 20);\n const numEnemies =\n 2 +\n Math.min(5, Math.floor(monsterLevel / 5)) +\n Math.min(10, Math.max(0, monsterLevel - 40));\n this.spawnEnemy(numEnemies);\n Save.saveGameState(this);\n }\n spawnEnemy(n: number) {\n for (let i = 0; i < n; i++) {",
"score": 0.8152322769165039
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.doMove(this.queuedMove.dx, this.queuedMove.dy);\n this.queuedMove = null;\n }\n }\n doMove(dx: number, dy: number) {\n if (this.state != \"play\") {\n // Can't move!\n return;\n }\n // 1. If you aren't yet ready to move, then queue the direction",
"score": 0.8080491423606873
}
] | typescript | targetCharacter.damage(1); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
| if (character.isPlayer && targetCharacter.isEnemy) { |
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8679243326187134
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8440746068954468
},
{
"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": 0.8379452228546143
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.doMove(this.queuedMove.dx, this.queuedMove.dy);\n this.queuedMove = null;\n }\n }\n doMove(dx: number, dy: number) {\n if (this.state != \"play\") {\n // Can't move!\n return;\n }\n // 1. If you aren't yet ready to move, then queue the direction",
"score": 0.8151253461837769
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8130035400390625
}
] | 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/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.7879427671432495
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " }\n setPositionTo(\n actor: PIXI.Container,\n coords: Coords,\n isWall: boolean = false\n ) {\n if (isWall) {\n if ((actor as Wall).isHorizontal) {\n actor.position.set(\n this.cellSize * coords.col + (this.cellSize - actor.width) / 2,",
"score": 0.7837699055671692
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.7784011960029602
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const modals = [this.gameOverModal];\n for (const m of modals) {\n if (m) {\n // Centre it!\n const x = (width - Game.TARGET_WIDTH) / 2;\n const y = (height - Game.TARGET_HEIGHT) / 2;\n m.position.set(x, y);\n }\n }\n }",
"score": 0.7766009569168091
},
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.772515594959259
}
] | typescript | setPositionTo(w, w.from, true); |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
| character.alpha = 0; |
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
this.charactersHolder.removeChild(targetCharacter);
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/menu/MenuScreen.ts",
"retrieved_chunk": " // Start new game!\n Game.instance.gotoGameScreen();\n });\n this.addChild(this.startButton);\n }\n resize(width: number, height: number) {\n this.w = width;\n this.h = height;\n this.logo.position.set(width / 2, MenuScreen.PADDING);\n this.startButton.position.set(",
"score": 0.812944769859314
},
{
"filename": "src/screens/game/grid/Wall.ts",
"retrieved_chunk": " super();\n this.from = from;\n this.to = to;\n this.sprite = PIXI.Sprite.from(PIXI.Texture.WHITE);\n this.sprite.tint = 0x4d3206;\n this.addChild(this.sprite);\n }\n setCellSize(cellSize: number) {\n const withSize = cellSize * 1.1;\n const againstSize = 5;",
"score": 0.8113160729408264
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7953323721885681
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " // Ensure that any pending animations don't intefere with positioning in next level\n Actions.clear(this.playerCharacter);\n } else {\n nextGrid.position.set(this.dungeonGrid.position.x, this.dungeonGrid.position.y);\n nextGrid.alpha = 0;\n Actions.fadeIn(nextGrid, 0.5).play();\n Actions.fadeOutAndRemove(this.dungeonGrid, 0.5).play();\n }\n } else {\n // If this is the first grid, we need to place it in the correct place",
"score": 0.7913341522216797
},
{
"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": 0.7822383642196655
}
] | typescript | character.alpha = 0; |
import * as PIXI from "pixi.js";
import { Actions } from "pixi-actions";
import { Character, EnemyCharacter, PlayerCharacter } from "../character";
import GameScreen from "../GameScreen";
import Grid from "./Grid";
import Wall from "./Wall";
import { Coords } from "utils";
import * as _ from "underscore";
import Game from "Game";
export default class DungeonGrid extends Grid {
characters: Character[] = [];
walls: Wall[] = [];
edgeWalls: Wall[] = [];
wallsHolder: PIXI.Container = new PIXI.Container();
charactersHolder: PIXI.Container = new PIXI.Container();
gameScreen: GameScreen;
coords: Coords[] = [];
cellSquares: PIXI.Sprite[][] = [];
cellStairs: PIXI.Sprite[][] = [];
exitCoords: Coords;
exitDir: Coords = null;
constructor(gameScreen: GameScreen, dimension: number) {
super(dimension);
this.gameScreen = gameScreen;
// Add cell backgrounds
const background = PIXI.Sprite.from(PIXI.Texture.WHITE);
background.tint = 0xd3c8a2;
background.width = this.edgeSize;
background.height = this.edgeSize;
background.alpha = 1;
background.anchor.set(0, 0);
this.addChild(background);
for (let i = 0; i < this.dimension; i++) {
const col1 = [];
const col2 = [];
for (let j = 0; j < this.dimension; j++) {
const cell = PIXI.Sprite.from(PIXI.Texture.WHITE);
cell.tint = 0;
cell.alpha = (i + j) % 2 == 0 ? 0 : 0.2;
cell.width = this.cellSize;
cell.height = this.cellSize;
const offset1 = (this.cellSize - cell.width) / 2;
cell.position.set(
i * this.cellSize + offset1,
j * this.cellSize + offset1
);
col1.push(cell);
this.addChild(cell);
const stair = PIXI.Sprite.from(Game.tex("stairs.png"));
stair.width = this.cellSize * 0.8;
stair.height = this.cellSize * 0.8;
const offset2 = (this.cellSize - stair.width) / 2;
stair.position.set(
i * this.cellSize + offset2,
j * this.cellSize + offset2
);
stair.visible = false;
col2.push(stair);
this.addChild(stair);
}
this.cellSquares.push(col1);
this.cellStairs.push(col2);
}
this.addChild(this.wallsHolder);
this.addChild(this.charactersHolder);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
this.coords.push(new Coords(i, j));
}
}
}
clearEnemies() {
for (let i = this.characters.length - 1; i >= 0; i--) {
const c = this.characters[i];
if (!c.isPlayer) {
Actions.fadeOutAndRemove(c, 0.2).play();
this.characters.splice(i, 1);
}
}
}
unsetExitCell() {
this.exitCoords = null;
this.updateExitCoords();
}
setExitCell(minDistanceFromPlayer: number = 7) {
const possibles = [];
const backups = [];
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
if (dijks.distance[i][j] >= minDistanceFromPlayer) {
possibles.push(new Coords(i, j));
}
if (dijks.distance[i][j] >= 3) {
backups.push(new Coords(i, j));
}
}
}
if (possibles.length == 0) {
possibles.push(...backups);
}
if (possibles.length == 0) {
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (i == 2 && j == 2) continue;
if (
Game.EXIT_TYPE == "door" &&
![0, this.dimension - 1].includes(i) &&
![0, this.dimension - 1].includes(j)
)
continue;
const c = new Coords(i, j);
let anyCoincidence = false;
if (this.gameScreen.playerCharacter.coords.equals(c)) {
anyCoincidence = true;
break;
}
if (!anyCoincidence) {
possibles.push(c);
}
}
}
}
const coords = _.sample(possibles);
this.exitCoords = coords;
if (Game.EXIT_TYPE == "door") {
const possibleDirs = [];
if (coords.row == 0) possibleDirs.push(new Coords(0, -1));
if (coords.row == this.dimension - 1) possibleDirs.push(new Coords(0, 1));
if (coords.col == 0) possibleDirs.push(new Coords(-1, 0));
if (coords.col == this.dimension - 1) possibleDirs.push(new Coords(1, 0));
if (possibleDirs.length > 0) this.exitDir = _.sample(possibleDirs);
}
this.updateExitCoords();
}
updateExitCoords() {
if (Game.EXIT_TYPE == "stairs") {
this.cellStairs.forEach((a, i) =>
a.forEach(
(stairs, j) =>
(stairs.visible =
this.exitCoords &&
this.exitCoords.col == i &&
this.exitCoords.row == j)
)
);
} else {
// Remove other edge walls (if there are any)
for (const c of this.edgeWalls) {
this.wallsHolder.removeChild(c);
}
this.edgeWalls = [];
// Add outer wall
let walls: Wall[] = Wall.edges(this.dimension);
// Make hole where exit is
if (this.exitCoords && this.exitDir) {
walls = walls.filter(
(w) => !w.blocks(this.exitCoords, this.exitDir.col, this.exitDir.row)
);
}
// Draw walls
this.drawWalls(walls);
this.walls.push(...walls);
this.edgeWalls.push(...walls);
}
}
getRandomEmptyCell(): Coords {
let dijks = null;
dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const shuffledCoords = _.shuffle(this.coords);
for (const coord of shuffledCoords) {
if (this.exitCoords && this.exitCoords.equals(coord)) continue;
if (
!this.getCharacterAt(coord) &&
(!dijks || dijks.distance[coord.col][coord.row] > 1)
) {
return coord;
}
}
return null;
}
generateWalls(numWalls: number) {
// Delete all old walls
for (const w of this.walls) {
Actions.fadeOutAndRemove(w, 0.2).play();
}
this.walls = Wall.randomLayout(numWalls, this.dimension);
// Add some new walls... they must generate any closed areas
this.drawWalls(this.walls);
}
drawWalls(walls: Wall[]) {
for (const w of walls) {
w.alpha = 0;
Actions.fadeIn(w, 0.2).play();
this.wallsHolder.addChild(w);
w.setCellSize(this.cellSize);
// Place in the correct place
this.setPositionTo(w, w.from, true);
}
}
addCharacter(character: Character) {
character.scale.set(0.2);
character.alpha = 0;
Actions.fadeIn(character, 0.2).play();
this.characters.push(character);
this.charactersHolder.addChild(character);
// Place in the correct place!
this.setPositionTo(character, character.coords);
}
getCharacterAt(col: number | Coords, row: number = null): Character {
let c = 0;
let r = 0;
if (typeof col == "number") {
c = col;
r = row;
} else {
c = col.col;
r = col.row;
}
for (const char of this.characters) {
if (char.coords.col == c && char.coords.row == r) {
return char;
}
}
return null;
}
bumpAnimation(character: Character, dx: number, dy: number) {
const time = 0.1;
Actions.sequence(
this.makeMoveTo(character, dx * 0.1, dy * 0.1, time / 2),
this.makeMoveTo(character, 0, 0, time / 2)
).play();
return time;
}
damageEnemy(targetCharacter: EnemyCharacter) {
let delay = 0;
const didDie = targetCharacter.damage(1);
if (didDie) {
// Remove from characters array
const index = this.characters.indexOf(targetCharacter);
if (index >= 0) {
this.characters.splice(index, 1);
}
// Remove from charactersHolder
targetCharacter.position.x += this.position.x;
targetCharacter.position.y += this.position.y;
| this.charactersHolder.removeChild(targetCharacter); |
delay = 0;
}
return delay;
}
moveCharacter(
character: Character,
dx: number,
dy: number
): { didMove: boolean; delay: number; wentThroughExit: boolean } {
// Check the target space is available
const targetCoord = character.coords.clone().add(dx, dy);
// Edge of grid!
if (!this.inBounds(targetCoord)) {
if (
this.exitCoords &&
character.coords.equals(this.exitCoords) &&
Game.EXIT_TYPE == "door" &&
this.exitDir &&
this.exitDir.equals(dx, dy)
) {
// We are going through the exit!
return { didMove: true, delay: 0, wentThroughExit: true };
}
// Hitting the edge of the grid
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Hitting a wall?
if (this.doesWallSeparate(character.coords, dx, dy)) {
Game.instance.playSound("bump");
const delay = this.bumpAnimation(character, dx, dy);
return { didMove: false, delay, wentThroughExit: false };
}
// Is there another character here?
try {
const targetCharacter = this.getCharacterAt(targetCoord);
if (targetCharacter) {
let delay = this.bumpAnimation(character, dx, dy);
if (character.isPlayer && targetCharacter.isEnemy) {
// Attack the character
Game.instance.playSound("attack");
delay += this.damageEnemy(targetCharacter as EnemyCharacter);
return { didMove: true, delay, wentThroughExit: false };
} else if (character.isEnemy && targetCharacter.isPlayer) {
const player = targetCharacter as PlayerCharacter;
// Take a damage!
if (player.damage(1)) {
this.gameScreen.gameOver();
}
return { didMove: true, delay, wentThroughExit: false };
} else {
return { didMove: false, delay, wentThroughExit: false };
}
}
} catch (e) {
// The game is over
this.gameScreen.gameOver();
return { didMove: true, delay: 0, wentThroughExit: false };
}
// Move the character
if (character.isPlayer) {
Game.instance.playSound(["step1", "step2", "step3", "step4"]);
}
character.coords.set(targetCoord);
// Animate to the new position
this.makeMoveTo(character).play();
return { didMove: true, delay: 0.05, wentThroughExit: false };
}
doesWallSeparate(start: Coords, dx: number, dy: number) {
for (const w of this.walls) {
if (w.blocks(start, dx, dy)) {
return true;
}
}
return false;
}
moveEnemies() {
let delay = 0;
// 1. Dijkstra the grid, ignoring enemies
// Pick the closest character
const dijks = this.dijkstra(this.gameScreen.playerCharacter.coords, false);
const enemiesAndDistances = [];
for (const char of this.characters) {
if (char.isEnemy) {
let distance = dijks.distance[char.coords.col][char.coords.row];
enemiesAndDistances.push({
distance,
char,
});
}
}
// 2. Sort by closest to furthest
let sortedEnemies = _.sortBy(enemiesAndDistances, "distance");
// 3. For each enemy, pathfind (properly) to the player
let atLeastOneMove = false;
for (let tries = 0; tries < 5; tries++) {
const tryAgainLater = [];
for (const e of sortedEnemies) {
const char = e.char;
const dijks = this.dijkstra(
this.gameScreen.playerCharacter.coords,
true,
char.coords
);
// Move in the direction which has the lowest distance
let targetCol = dijks.col[char.coords.col][char.coords.row];
let targetRow = dijks.row[char.coords.col][char.coords.row];
if (targetCol == null || targetRow == null) {
const neighbours: Coords[] = [];
this.addPotentialNeighbour(neighbours, char.coords, 1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, 1);
this.addPotentialNeighbour(neighbours, char.coords, -1, 0);
this.addPotentialNeighbour(neighbours, char.coords, 0, -1);
if (neighbours.length > 0) {
// If there is no good route, then random direction
const dir = _.sample(neighbours);
targetCol = dir.col;
targetRow = dir.row;
} else {
// If there is no route at all, then wait, we'll try again in a bit
tryAgainLater.push(e);
continue;
}
}
const dx = targetCol - char.coords.col;
const dy = targetRow - char.coords.row;
atLeastOneMove = true;
delay = Math.max(this.moveCharacter(char, dx, dy).delay, delay);
}
if (tryAgainLater.length == 0) {
break;
} else {
sortedEnemies = tryAgainLater;
}
}
return { didMove: true, delay };
}
addPotentialNeighbour(
list: Coords[],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
list.push(coords.clone().add(dx, dy));
}
updateTentativeDistance(
withEnemiesAsObstacles: boolean,
tentativeDistance: number[][],
tentativeSourceCol: number[][],
tentativeSourceRow: number[][],
coords: Coords,
dx: number,
dy: number
) {
if (!this.inBounds(coords.col + dx, coords.row + dy)) {
// Out of bounds, ignore!
return;
}
if (this.doesWallSeparate(coords, dx, dy)) {
// There is no path, ignore!
return;
}
if (withEnemiesAsObstacles) {
const char = this.getCharacterAt(coords.col + dx, coords.row + dy);
if (char && char.isEnemy) {
// There is a monster on the target square, ignore!
return;
}
}
const newTentativeDistance = tentativeDistance[coords.col][coords.row] + 1;
if (
tentativeDistance[coords.col + dx][coords.row + dy] > newTentativeDistance
) {
tentativeDistance[coords.col + dx][coords.row + dy] =
newTentativeDistance;
tentativeSourceCol[coords.col + dx][coords.row + dy] = coords.col;
tentativeSourceRow[coords.col + dx][coords.row + dy] = coords.row;
}
}
dijkstra(
target: Coords,
withEnemiesAsObstacles: boolean,
stopAt: Coords = null
): { distance: number[][]; col: number[][]; row: number[][] } {
const current = target.clone();
const visited: boolean[][] = [];
const tentativeDistance: number[][] = [];
const tentativeSourceCol: number[][] = [];
const tentativeSourceRow: number[][] = [];
for (let i = 0; i < this.dimension; i++) {
// col
const c1 = [];
const c2 = [];
const c3 = [];
const c4 = [];
for (let j = 0; j < this.dimension; j++) {
// row
c1.push(false);
if (target.row == j && target.col == i) {
c2.push(0);
} else {
c2.push(99999);
}
c3.push(null);
c4.push(null);
}
visited.push(c1);
tentativeDistance.push(c2);
tentativeSourceCol.push(c3);
tentativeSourceRow.push(c4);
}
do {
// Consider all unvisited neighbours of `current`
const utd = (dx: number, dy: number) => {
this.updateTentativeDistance(
stopAt && stopAt.equals(current.col + dx, current.row + dy)
? false
: withEnemiesAsObstacles,
tentativeDistance,
tentativeSourceCol,
tentativeSourceRow,
current,
dx,
dy
);
};
utd(1, 0);
utd(-1, 0);
utd(0, -1);
utd(0, 1);
// Mark current as visited
visited[current.col][current.row] = true;
// Stop if we've connected our two target points
if (stopAt && stopAt.equals(current)) break;
let smallestTentativeDistance = 9999999;
let smallests = [];
for (let i = 0; i < this.dimension; i++) {
for (let j = 0; j < this.dimension; j++) {
if (visited[i][j]) continue;
if (
smallests.length == 0 ||
tentativeDistance[i][j] < smallestTentativeDistance
) {
smallestTentativeDistance = tentativeDistance[i][j];
smallests = [];
}
if (tentativeDistance[i][j] == smallestTentativeDistance) {
smallests.push([i, j]);
}
}
}
// If there are no unvisited, we are done
if (smallests.length == 0) break;
// Otherwise, set current to unvisited with smallest tentative
const randomSmallest = _.sample(smallests);
current.set(randomSmallest[0], randomSmallest[1]);
} while (true);
// Return the dijkstra map for the whole grid
return {
distance: tentativeDistance,
col: tentativeSourceCol,
row: tentativeSourceRow,
};
}
}
| src/screens/game/grid/DungeonGrid.ts | MaxBittker-broughlike-c8d94d5 | [
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const modals = [this.gameOverModal];\n for (const m of modals) {\n if (m) {\n // Centre it!\n const x = (width - Game.TARGET_WIDTH) / 2;\n const y = (height - Game.TARGET_HEIGHT) / 2;\n m.position.set(x, y);\n }\n }\n }",
"score": 0.7826147079467773
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " )\n ),\n Actions.remove(this.dungeonGrid)\n ).play();\n // Move the player to opposite side of the dungeon\n if (this.dungeonGrid.exitDir.col != 0) {\n this.playerCharacter.coords.col = this.dungeonGrid.dimension - this.playerCharacter.coords.col - 1;\n } else {\n this.playerCharacter.coords.row = this.dungeonGrid.dimension - this.playerCharacter.coords.row - 1;\n }",
"score": 0.7610595226287842
},
{
"filename": "src/screens/game/grid/Grid.ts",
"retrieved_chunk": " this.cellSize * coords.row + -actor.height / 2\n );\n } else {\n actor.position.set(\n this.cellSize * coords.col + -actor.width / 2,\n this.cellSize * coords.row + (this.cellSize - actor.height) / 2\n );\n }\n } else {\n actor.position.set(",
"score": 0.7584401369094849
},
{
"filename": "src/Game.ts",
"retrieved_chunk": " Actions.tick(elapsedSeconds);\n // If pointer is held down, trigger movements.\n if (this.startTouch) {\n const elapsed = Date.now() - this.startTouchTime;\n if (this.isHoldRepeating) {\n if (elapsed > Game.HOLD_REPEAT_TIME_MS) {\n const deltaX = this.touchPosition.x - this.startTouch.x;\n const deltaY = this.touchPosition.y - this.startTouch.y;\n this.performSwipe(deltaX, deltaY);\n this.startTouchTime = Date.now();",
"score": 0.750139594078064
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " const enemyCharacter = new EnemyCharacter(\"enemy1\");\n // Random empty cell\n const coord = this.dungeonGrid.getRandomEmptyCell();\n if (!coord) return;\n enemyCharacter.coords.set(coord.col, coord.row);\n this.dungeonGrid.addCharacter(enemyCharacter);\n }\n }\n pumpQueuedMove() {\n if (this.queuedMove) {",
"score": 0.7410464286804199
}
] | 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/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.882697582244873
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8738028407096863
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n ).toEqual(\n err({\n errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,",
"score": 0.8491712212562561
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8425410389900208
},
{
"filename": "src/ok.ts",
"retrieved_chunk": "export function ok(value?: unknown): Ok<unknown> {\n let resultData: any = value;\n if (resultData === undefined) {\n // special case for undefined actually being\n // passed in as undefined\n resultData = arguments.length === 1 ? undefined : null;\n } else if (isOkResult(value)) {\n // no need for a loop since ok(ok()) does this\n // by way of the function call stack\n resultData = value.data;",
"score": 0.8385854363441467
}
] | 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": " if (this.state == \"play\")\n Save.saveGameState(this);\n }\n doEnemyMove() {\n // Move enemies, after a delay!\n const enemyMoveResult = this.dungeonGrid.moveEnemies();\n let delay = enemyMoveResult.delay;\n // After a delay, let the player move again\n // Fudge this value, I like to be able to move really soon\n Actions.sequence(",
"score": 0.8846770524978638
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " if (this.readyToMove) {\n // 2. Otherwise, do the move\n const moveResult = this.dungeonGrid.moveCharacter(\n this.playerCharacter,\n dx,\n dy\n );\n // 3. If the move was successful, then say we aren't ready to move yet\n if (moveResult.wentThroughExit) {\n // Load in new level",
"score": 0.8347824811935425
},
{
"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": 0.8241907954216003
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " } else {\n Actions.sequence(\n Actions.delay(delay),\n Actions.runFunc(() => {\n if (this.state != \"gameover\") {\n this.doEnemyMove();\n }\n })\n ).play();\n }",
"score": 0.8154029250144958
},
{
"filename": "src/screens/game/GameScreen.ts",
"retrieved_chunk": " this.readyToMove = false;\n // Any character on exit\n let onExit = false;\n if (Game.EXIT_TYPE == \"stairs\" && this.dungeonGrid.exitCoords) {\n if (this.dungeonGrid.exitCoords.equals(this.playerCharacter.coords)) {\n onExit = true;\n }\n }\n if (onExit) {\n this.nextLevel();",
"score": 0.8083977699279785
}
] | 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/ok.ts",
"retrieved_chunk": "export function ok(value?: unknown): Ok<unknown> {\n let resultData: any = value;\n if (resultData === undefined) {\n // special case for undefined actually being\n // passed in as undefined\n resultData = arguments.length === 1 ? undefined : null;\n } else if (isOkResult(value)) {\n // no need for a loop since ok(ok()) does this\n // by way of the function call stack\n resultData = value.data;",
"score": 0.8384636640548706
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8382056951522827
},
{
"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": 0.8358609676361084
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8048602938652039
},
{
"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": 0.8000052571296692
}
] | typescript | if (isJsError(a)) { |
/*
* 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": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8846039772033691
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8781781196594238
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8738341331481934
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8691976070404053
},
{
"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": 0.8509242534637451
}
] | typescript | getConversationContext(session: Session): Promise<Object> { |
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": 0.8506714105606079
},
{
"filename": "src/ok.ts",
"retrieved_chunk": "export function ok(value?: unknown): Ok<unknown> {\n let resultData: any = value;\n if (resultData === undefined) {\n // special case for undefined actually being\n // passed in as undefined\n resultData = arguments.length === 1 ? undefined : null;\n } else if (isOkResult(value)) {\n // no need for a loop since ok(ok()) does this\n // by way of the function call stack\n resultData = value.data;",
"score": 0.8406028747558594
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8405131697654724
},
{
"filename": "src/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8393568396568298
},
{
"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": 0.8288524150848389
}
] | typescript | message = typeof b === "string" ? b : a.message || ""; |
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/toResult.spec.ts",
"retrieved_chunk": " errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n ).toEqual(\n err({\n errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,",
"score": 0.8947618007659912
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " expect(\n toResult({\n ok: false,\n errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n ).toEqual(\n err({",
"score": 0.8801972270011902
},
{
"filename": "src/err.ts",
"retrieved_chunk": " ? errMessage\n : exception\n ? exception.message\n : \"\";\n context = isErrContext(d) ? d : errContext ?? null;\n }\n break;\n }\n }\n return {",
"score": 0.8791661262512207
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n );\n expect(\n toResult({\n err: true,\n errMessage: \"it broke\",",
"score": 0.8768303394317627
},
{
"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": 0.874575138092041
}
] | typescript | value ? ok(value) : err(); |
import type { Err } from "./api";
import { isJsError } from "./shared";
// this is used to make sure that at least one of the
// properties of an object is defined (becausePartial
// makes all properties optional))
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> &
U[keyof U];
/**
* Creates an Err result.
*/
export function err(): Err;
export function err(err: null | undefined | boolean): Err;
export function err<T extends Err>(err: T): T;
export function err<C extends number>(errCode: C): Err<C>;
export function err(errMessage: string): Err;
export function err<C extends unknown = number | string>(
errMessage: string,
errCode: C,
): Err<C>;
export function err<
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(errMessage: string, errCode: C, errContext: X): Err<number, Error, X>;
export function err<
E extends Err,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: AtLeastOne<Partial<E>>,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, | NonNullable<E["errException"]>, X>; |
export function err<
E extends Error,
C extends unknown = string | number,
X extends { [key: string]: unknown } = { [key: string]: unknown },
>(
e: E | { stack: string; message: string } | unknown,
errMessage?: string,
errCode?: C,
errContext?: X,
): Err<C, E, X>;
export function err(a?: unknown, b?: unknown, c?: unknown, d?: unknown): Err {
let code: number | string = 0;
let message: string = "";
let context: { [key: string]: unknown } | null = null;
let exception: Error | null = null;
// err()
// err(null | undefined)
// --
// otherwise...
if (a !== null && a !== undefined) {
switch (typeof a) {
// err(number)
case "number":
code = a;
break;
// err(string, number?, context?)
case "string":
message = a;
if (typeof b === "number" || typeof b === "string") {
code = b;
}
if (c && typeof c === "object") {
context = c as { [key: string]: unknown };
}
break;
case "object":
if (isJsError(a)) {
// err(Error, message?, code?, context?)
exception = a;
message = typeof b === "string" ? b : a.message || "";
code = typeof c === "number" || typeof c === "string" ? c : 0;
context =
typeof d === "object" ? (d as { [key: string]: unknown }) : null;
} else {
// err({ errMessage?, errCode?, errContext?, errException? })
const { errCode, errMessage, errContext, errException } =
a as Partial<Err>;
exception = errException ?? null;
code =
typeof c === "number"
? c
: typeof errCode === "number"
? errCode
: 0;
message = isValidString(b)
? b
: isValidString(errMessage)
? errMessage
: exception
? exception.message
: "";
context = isErrContext(d) ? d : errContext ?? null;
}
break;
}
}
return {
ok: false,
err: true,
errCode: code,
errContext: context,
errMessage: message,
errException: exception,
};
}
function isValidString(value: unknown): value is string {
return typeof value === "string" && value.length !== 0;
}
function isErrContext(value: unknown): value is { [key: string]: unknown } {
return typeof value === "object" && value !== null;
}
| src/err.ts | yearofmoo-okej-03a1277 | [
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8926596641540527
},
{
"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": 0.8565273880958557
},
{
"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": 0.8213616609573364
},
{
"filename": "src/from.ts",
"retrieved_chunk": " } else {\n const context = { results };\n return err({ errContext: context });\n }\n}\nexport async function fromPromise<D extends unknown>(\n promise: Promise<D>,\n): Promise<Result<D>> {\n try {\n const data = await promise;",
"score": 0.7971988916397095
},
{
"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": 0.7778255343437195
}
] | 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/ok.ts",
"retrieved_chunk": "export function ok(value?: unknown): Ok<unknown> {\n let resultData: any = value;\n if (resultData === undefined) {\n // special case for undefined actually being\n // passed in as undefined\n resultData = arguments.length === 1 ? undefined : null;\n } else if (isOkResult(value)) {\n // no need for a loop since ok(ok()) does this\n // by way of the function call stack\n resultData = value.data;",
"score": 0.8448001742362976
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8433651924133301
},
{
"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": 0.8329375982284546
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.816478431224823
},
{
"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": 0.8144403696060181
}
] | 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/toResult.ts",
"retrieved_chunk": " const errContext = e.errContext ?? null;\n const errException = isJsError(e.errException) ? e.errException : null;\n return err({\n errCode,\n errMessage,\n errContext,\n errException,\n });\n }\n // fallback for any {} object",
"score": 0.8873133063316345
},
{
"filename": "src/api.ts",
"retrieved_chunk": " C extends unknown = number | string,\n E extends Error = Error,\n X extends { [key: string]: unknown } = { [key: string]: unknown },\n> {\n ok: false;\n err: true;\n errCode: C;\n errMessage: string;\n errException: E | null;\n errContext: X | null;",
"score": 0.8641911745071411
},
{
"filename": "src/shared.ts",
"retrieved_chunk": "export function isJsError(e: unknown): e is Error {\n return (\n e instanceof Error ||\n (typeof e === \"object\" &&\n e !== null &&\n typeof (e as { message?: unknown }).message === \"string\")\n );\n}",
"score": 0.8488916754722595
},
{
"filename": "src/ok.ts",
"retrieved_chunk": "export function ok(value?: unknown): Ok<unknown> {\n let resultData: any = value;\n if (resultData === undefined) {\n // special case for undefined actually being\n // passed in as undefined\n resultData = arguments.length === 1 ? undefined : null;\n } else if (isOkResult(value)) {\n // no need for a loop since ok(ok()) does this\n // by way of the function call stack\n resultData = value.data;",
"score": 0.8484289050102234
},
{
"filename": "src/toResult.spec.ts",
"retrieved_chunk": " errCode: 999,\n errContext: ctx,\n errException: e,\n }),\n ).toEqual(\n err({\n errMessage: \"it broke\",\n errCode: 999,\n errContext: ctx,\n errException: e,",
"score": 0.8391090631484985
}
] | typescript | const { errCode, errMessage, errContext, errException } =
a as Partial<Err>; |
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": 0.9084012508392334
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " * @param {String} filename Name of the file.\n */\n public load(filename: string): void {\n this.nlpManager.load(filename);\n }\n /**\n * Saves the model into a file.\n * @param {String} filename Name of the file.\n */\n public save(filename: string): void {",
"score": 0.855587899684906
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8318150043487549
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.7930826544761658
},
{
"filename": "src/nlp/nlp-excel-reader.ts",
"retrieved_chunk": "import { XDoc } from '@nlpjs/xtables';\nimport NlpManager from './nlp-manager';\nclass NlpExcelReader {\n private manager: NlpManager;\n private xdoc: XDoc;\n constructor(manager: NlpManager) {\n this.manager = manager;\n this.xdoc = new XDoc();\n }\n load(filename: string): void {",
"score": 0.7915335893630981
}
] | 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": 0.9417652487754822
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.899864673614502
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": "class NlpManager {\n private readonly settings: NlpManagerSettings;\n private container: any;\n private nlp: any;\n private sentimentManager: SentimentManager;\n constructor(settings: NlpManagerSettings) {\n this.settings = settings;\n if (!this.settings.container) {\n this.settings.container = containerBootstrap();\n }",
"score": 0.898082435131073
},
{
"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": 0.868470311164856
},
{
"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": 0.8387987017631531
}
] | 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": 0.9159930944442749
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.8937236070632935
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": "class NlpManager {\n private readonly settings: NlpManagerSettings;\n private container: any;\n private nlp: any;\n private sentimentManager: SentimentManager;\n constructor(settings: NlpManagerSettings) {\n this.settings = settings;\n if (!this.settings.container) {\n this.settings.container = containerBootstrap();\n }",
"score": 0.8813917636871338
},
{
"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": 0.8601484298706055
},
{
"filename": "src/types/@nlpjs/nlu.d.ts",
"retrieved_chunk": " }\n export class Nlu extends EventEmitter {\n constructor();\n container: Container;\n model?: INluModel;\n containerName?: string;\n locale: string;\n languages: string[];\n settings: INluOptions;\n stopWords: Set<string>;",
"score": 0.8523818850517273
}
] | 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/nlp/nlp-manager.ts",
"retrieved_chunk": " bad: 0,\n };\n const promises = [];\n const intents = [];\n for (let i = 0; i < data.length; i += 1) {\n const intentData = data[i];\n const { tests } = intentData;\n for (let j = 0; j < tests.length; j += 1) {\n promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));\n intents.push(intentData.intent);",
"score": 0.7518811821937561
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.sentimentManager.translate(sentiment.sentiment);\n }\n addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n addRegexEntity(entityName: string, languages: string[], regex: string): void {\n return this.nlp.addNerRegexRule(languages, entityName, regex);",
"score": 0.7457168102264404
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " */\n loadExcel(fileName = 'model.xls'): void {\n const reader = new NlpExcelReader(this);\n reader.load(fileName);\n }\n async testCorpus(corpus: any): Promise<any> {\n const { data } = corpus;\n const result = {\n total: 0,\n good: 0,",
"score": 0.7453956604003906
},
{
"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": 0.7374149560928345
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);",
"score": 0.732455313205719
}
] | 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 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": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8759520053863525
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8717669248580933
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8684378862380981
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8651067018508911
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * Given a session instance of a chatbot, return the conversation identifier.\n * @param {Object} session Session instance of a message of chatbot.\n * @returns {String} Identifier of the conversation.\n */\n public getConversationId(session: Session): string | undefined {\n if (session?.message?.address?.conversation) {\n return session.message.address.conversation.id;\n }\n if (session?._activity?.conversation) {\n return session._activity.conversation.id;",
"score": 0.8561235666275024
}
] | typescript | : Session): Promise<Object> { |
import { XDoc } from '@nlpjs/xtables';
import NlpManager from './nlp-manager';
class NlpExcelReader {
private manager: NlpManager;
private xdoc: XDoc;
constructor(manager: NlpManager) {
this.manager = manager;
this.xdoc = new XDoc();
}
load(filename: string): void {
this.xdoc.read(filename);
this.loadSettings();
this.loadLanguages();
this.loadNamedEntities();
this.loadRegexEntities();
this.loadIntents();
this.loadResponses();
}
loadSettings(): void {}
loadLanguages(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Languages').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addLanguage(row.iso2);
});
}
loadNamedEntities(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Named Entities').data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addNamedEntityText(row.entity, row.option, languages, [row.text]);
});
}
loadRegexEntities(): void {
const table = this.xdoc.getTable('Regex Entities');
if (table) {
const rows: Record<string, string>[] = table.data;
rows.forEach((row: Record<string, string>) => {
const languages = row.language.split(',').map((x) => x.trim());
this.manager.addRegexEntity(row.entity, languages, row.regex);
});
}
}
loadIntents(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Intents').data;
rows.forEach((row: Record<string, string>) => {
this | .manager.addDocument(row.language, row.utterance, row.intent); |
});
}
loadResponses(): void {
const rows: Record<string, string>[] = this.xdoc.getTable('Responses').data;
rows.forEach((row: Record<string, string>) => {
this.manager.addAnswer(row.language, row.intent, row.response, row.condition);
// this.manager.addAnswer(row.language, row.intent, row.response, row.condition, row.url);
});
}
}
export default NlpExcelReader;
| src/nlp/nlp-excel-reader.ts | Leoglme-node-nlp-typescript-fbee5fd | [
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " } else {\n const builtin = new BuiltinMicrosoft(this.settings.ner);\n this.container.register('extract-builtin-??', builtin, true);\n }\n }\n public addDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.addDocument(locale, utterance, intent);\n }\n public removeDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.removeDocument(locale, utterance, intent);",
"score": 0.7844960689544678
},
{
"filename": "src/nlu/brain-nlu.ts",
"retrieved_chunk": " });\n }\n this.corpus = [];\n }\n add(utterance: string, intent: string) {\n this.corpus.push({ utterance, intent });\n }\n train() {\n return this.nlu?.train(this.corpus, this.settings);\n }",
"score": 0.762993574142456
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " bad: 0,\n };\n const promises = [];\n const intents = [];\n for (let i = 0; i < data.length; i += 1) {\n const intentData = data[i];\n const { tests } = intentData;\n for (let j = 0; j < tests.length; j += 1) {\n promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));\n intents.push(intentData.intent);",
"score": 0.7392259240150452
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.sentimentManager.translate(sentiment.sentiment);\n }\n addNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.addNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n removeNamedEntityText(entityName: string, optionName: string, languages: string[], texts: string[]): void {\n return this.nlp.removeNerRuleOptionTexts(languages, entityName, optionName, texts);\n }\n addRegexEntity(entityName: string, languages: string[], regex: string): void {\n return this.nlp.addNerRegexRule(languages, entityName, regex);",
"score": 0.7348035573959351
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.nlp.addAnswer(locale, intent, answer, opts);\n }\n removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {\n return this.nlp.removeAnswer(locale, intent, answer, opts);\n }\n findAllAnswers(locale: string, intent: string): string[] {\n return this.nlp.findAllAnswers(locale, intent);\n }\n async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {\n const sentiment = await this.nlp.getSentiment(locale, utterance);",
"score": 0.720914363861084
}
] | 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 { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
public getConversationId(session: Session): string | undefined {
| if (session?.message?.address?.conversation) { |
return session.message.address.conversation.id;
}
if (session?._activity?.conversation) {
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
| src/recognizer/conversation-context.ts | Leoglme-node-nlp-typescript-fbee5fd | [
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.930800199508667
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8676208853721619
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " }\n return resolve(this.conversationContexts[conversationId]);\n });\n }\n public setConversationContext(session: Session, context: any): Promise<void> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }",
"score": 0.8476578593254089
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * @returns {Promise<Object>} Promise to resolve the conversation context.\n */\n public getConversationContext(session: Session): Promise<Object> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }\n if (!this.conversationContexts[conversationId]) {\n this.conversationContexts[conversationId] = {};",
"score": 0.8469586372375488
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8450735807418823
}
] | typescript | if (session?.message?.address?.conversation) { |
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
public getConversationId(session: Session): string | undefined {
if (session?.message?.address?.conversation) {
return session.message.address.conversation.id;
}
| if (session?._activity?.conversation) { |
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
| src/recognizer/conversation-context.ts | Leoglme-node-nlp-typescript-fbee5fd | [
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.8768191337585449
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * @returns {Promise<Object>} Promise to resolve the conversation context.\n */\n public getConversationContext(session: Session): Promise<Object> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }\n if (!this.conversationContexts[conversationId]) {\n this.conversationContexts[conversationId] = {};",
"score": 0.8592997789382935
},
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " }\n return resolve(this.conversationContexts[conversationId]);\n });\n }\n public setConversationContext(session: Session, context: any): Promise<void> {\n return new Promise((resolve, reject) => {\n const conversationId = this.getConversationId(session);\n if (!conversationId) {\n return reject(new Error('No conversation id found'));\n }",
"score": 0.8523238301277161
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " return this.add(locale, intent, answer, opts);\n }\n async findAnswer(locale: string, intent: string, context: any, settings?: any): Promise<{ response: any } | undefined> {\n const answer = await this.find(locale, intent, context, settings);\n if (!answer.answer) {\n return undefined;\n }\n return {\n response: answer.answer,\n };",
"score": 0.8103705048561096
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8095980286598206
}
] | typescript | if (session?._activity?.conversation) { |
/*
* Copyright (c) AXA Group Operations Spain S.A.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Session } from "../types/session";
/**
* Abstract class for a conversation context of a chatbot.
* The conversation context is the responsible for storing and retrieving
* the context scope variables based on the current conversation.
* The getConversationContext receive the session of the chatbot, and must return
* a promise with the context in the resolve.
*/
class ConversationContext {
private settings: object;
/**
* Constructor of the class.
* @param {Object} settings Settings for the instance.
*/
constructor(settings: object) {
this.settings = settings || {};
}
/**
* Given a session instance of a chatbot, return the conversation identifier.
* @param {Object} session Session instance of a message of chatbot.
* @returns {String} Identifier of the conversation.
*/
| public getConversationId(session: Session): string | undefined { |
if (session?.message?.address?.conversation) {
return session.message.address.conversation.id;
}
if (session?._activity?.conversation) {
return session._activity.conversation.id;
}
return undefined;
}
}
export default ConversationContext;
| src/recognizer/conversation-context.ts | Leoglme-node-nlp-typescript-fbee5fd | [
{
"filename": "src/recognizer/memory-conversation-context.ts",
"retrieved_chunk": " * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n super(settings);\n this.conversationContexts = {};\n }\n /**\n * Gets the conversation context from the session.\n * @param {Object} session Chatbot session of the conversation.",
"score": 0.9546883702278137
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8954154253005981
},
{
"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": 0.857377827167511
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " this.settings.conversationContext || new MemoryConversationContext({});\n }\n /**\n * Train the NLP manager.\n */\n public async train(): Promise<void> {\n await this.nlpManager.train();\n }\n /**\n * Loads the model from a file.",
"score": 0.8568630218505859
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " * @param {String} filename Name of the file.\n */\n public load(filename: string): void {\n this.nlpManager.load(filename);\n }\n /**\n * Saves the model into a file.\n * @param {String} filename Name of the file.\n */\n public save(filename: string): void {",
"score": 0.8568577170372009
}
] | 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/nlp/nlp-manager.ts",
"retrieved_chunk": " } else {\n const builtin = new BuiltinMicrosoft(this.settings.ner);\n this.container.register('extract-builtin-??', builtin, true);\n }\n }\n public addDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.addDocument(locale, utterance, intent);\n }\n public removeDocument(locale: string, utterance: string, intent: string) {\n return this.nlp.removeDocument(locale, utterance, intent);",
"score": 0.7553648352622986
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " bad: 0,\n };\n const promises = [];\n const intents = [];\n for (let i = 0; i < data.length; i += 1) {\n const intentData = data[i];\n const { tests } = intentData;\n for (let j = 0; j < tests.length; j += 1) {\n promises.push(this.process(corpus.locale.slice(0, 2), tests[j]));\n intents.push(intentData.intent);",
"score": 0.7371355891227722
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " async train(): Promise<void> {\n return this.nlp.train();\n }\n classify(locale: string, utterance: string, settings?: Record<string, unknown>): Promise<any> {\n return this.nlp.classify(locale, utterance, settings);\n }\n async process(locale?: string, utterance?: string, context?: Record<string, unknown>, settings?: Record<string, unknown>): Promise<any> {\n const result = await this.nlp.process(locale, utterance, context, settings);\n if (this.settings.processTransformer) {\n return this.settings.processTransformer(result);",
"score": 0.7286008596420288
},
{
"filename": "src/nlp/nlp-manager.ts",
"retrieved_chunk": " return this.nlp.addAnswer(locale, intent, answer, opts);\n }\n removeAnswer(locale: string, intent: string, answer: string, opts?: any): boolean {\n return this.nlp.removeAnswer(locale, intent, answer, opts);\n }\n findAllAnswers(locale: string, intent: string): string[] {\n return this.nlp.findAllAnswers(locale, intent);\n }\n async getSentiment(locale: string, utterance: string): Promise<{ numHits: number; score: number; comparative: number; language: string; numWords: number; type: string; vote: any }> {\n const sentiment = await this.nlp.getSentiment(locale, utterance);",
"score": 0.7249616980552673
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " locale?: string,\n utterance?: string\n ): Promise<string> {\n const context = srcContext || {};\n const response = await (locale\n ? this.nlpManager.process(locale, utterance, context)\n : this.nlpManager.process(utterance, undefined, context));\n if (response.score < this.threshold || response.intent === 'None') {\n response.answer = undefined;\n return response;",
"score": 0.7232077121734619
}
] | typescript | this.manager.addAnswer(row.language, row.intent, row.response, row.condition); |
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/sentiment/sentiment-analyzer.ts",
"retrieved_chunk": " this.container.use(Nlu);\n }\n async getSentiment(utterance: string, locale = 'en', settings: [key: string]) {\n const input = {\n utterance,\n locale,\n ...settings,\n };\n const result = await this.process(input);\n return result.sentiment;",
"score": 0.8835856318473816
},
{
"filename": "src/nlg/nlg-manager.ts",
"retrieved_chunk": " return this.add(locale, intent, answer, opts);\n }\n async findAnswer(locale: string, intent: string, context: any, settings?: any): Promise<{ response: any } | undefined> {\n const answer = await this.find(locale, intent, context, settings);\n if (!answer.answer) {\n return undefined;\n }\n return {\n response: answer.answer,\n };",
"score": 0.8810515403747559
},
{
"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": 0.8795044422149658
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " locale?: string,\n utterance?: string\n ): Promise<string> {\n const context = srcContext || {};\n const response = await (locale\n ? this.nlpManager.process(locale, utterance, context)\n : this.nlpManager.process(utterance, undefined, context));\n if (response.score < this.threshold || response.intent === 'None') {\n response.answer = undefined;\n return response;",
"score": 0.8780547380447388
},
{
"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": 0.8402739763259888
}
] | typescript | .translate(sentiment.sentiment); |
/*
* 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": " * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport { Session } from \"../types/session\";\n/**\n * Abstract class for a conversation context of a chatbot.\n * The conversation context is the responsible for storing and retrieving\n * the context scope variables based on the current conversation.\n * The getConversationContext receive the session of the chatbot, and must return\n * a promise with the context in the resolve.\n */",
"score": 0.8613895177841187
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": " * Given a session instance of a chatbot, return the conversation identifier.\n * @param {Object} session Session instance of a message of chatbot.\n * @returns {String} Identifier of the conversation.\n */\n public getConversationId(session: Session): string | undefined {\n if (session?.message?.address?.conversation) {\n return session.message.address.conversation.id;\n }\n if (session?._activity?.conversation) {\n return session._activity.conversation.id;",
"score": 0.8544456362724304
},
{
"filename": "src/recognizer/conversation-context.ts",
"retrieved_chunk": "class ConversationContext {\n private settings: object;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(settings: object) {\n this.settings = settings || {};\n }\n /**",
"score": 0.8449612855911255
},
{
"filename": "src/recognizer/recognizer.ts",
"retrieved_chunk": " private readonly conversationContext: MemoryConversationContext;\n /**\n * Constructor of the class.\n * @param {Object} settings Settings for the instance.\n */\n constructor(private readonly settings: {\n nlpManager?: NlpManager;\n container?: any;\n nerThreshold?: number;\n threshold?: number;",
"score": 0.8417863249778748
},
{
"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": 0.8397670984268188
}
] | 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": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}",
"score": 0.7874082922935486
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }",
"score": 0.7799187898635864
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'",
"score": 0.7525345087051392
},
{
"filename": "src/htmlRewriterClasses/Replace.ts",
"retrieved_chunk": "class Replace {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.replace(this.content, this.contentOptions)\n }",
"score": 0.7523806691169739
},
{
"filename": "src/htmlRewriterClasses/After.ts",
"retrieved_chunk": "class After {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.after(this.content, this.contentOptions)\n }",
"score": 0.7503727078437805
}
] | typescript | instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => { |
import { Context, MiddlewareHandler } from 'hono'
import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types'
import {
After,
Append,
AppendGlobalCode,
Before,
Prepend,
Remove,
RemoveAndKeepContent,
RemoveAttribute,
Replace,
SetAttribute,
SetInnerContent,
SetStyleProperty,
} from './htmlRewriterClasses'
export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => {
if (!options.url) {
options.url = 'https://edge-api.exporio.cloud'
}
if (!options.apiKey) {
throw new Error('Exporio middleware requires options for "apiKey"')
}
return async (c, next) => {
const exporioInstructions = await fetchExporioInstructions(c, options)
if (!exporioInstructions) {
c.set('contentUrl', c.req.url)
await next()
} else {
c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url))
await next()
applyRewriterInstruction(c, exporioInstructions)
applyCookieInstruction(c.res.headers, exporioInstructions)
}
}
}
| const buildRequestJson = (c: Context, apiKey: string): RequestJson => { |
const headersInit: HeadersInit = []
c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value]))
return {
originalRequest: {
url: c.req.url,
method: c.req.method,
headersInit: headersInit,
},
params: {
API_KEY: apiKey,
},
}
}
const fetchExporioInstructions = async (
c: Context,
options: ExporioMiddlewareOptions
): Promise<Instructions | null> => {
try {
const requestJson = buildRequestJson(c, options.apiKey)
const exporioRequest = new Request(options.url, {
method: 'POST',
body: JSON.stringify(requestJson),
headers: { 'Content-Type': 'application/json' },
})
const exporioResponse = await fetch(exporioRequest)
return await exporioResponse.json()
} catch (err) {
console.error('Failed to fetch exporio instructions', err)
return null
}
}
const getContentUrl = (instructions: Instructions, defaultUrl: string): string => {
const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
}
const applyRewriterInstruction = (c: Context, instructions: Instructions) => {
let response = new Response(c.res.body, c.res)
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
switch (method) {
// Default Methods
case 'After': {
const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Append': {
const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Before': {
const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Prepend': {
const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Remove': {
const rewriter = new HTMLRewriter().on(selector, new Remove())
response = rewriter.transform(response)
break
}
case 'RemoveAndKeepContent': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent())
response = rewriter.transform(response)
break
}
case 'RemoveAttribute': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1))
response = rewriter.transform(response)
break
}
case 'Replace': {
const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetAttribute': {
const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetInnerContent': {
const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2))
response = rewriter.transform(response)
break
}
// Custom Methods
case 'AppendGlobalCode': {
const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetStyleProperty': {
const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2))
response = rewriter.transform(response)
break
}
}
})
c.res = new Response(response.body, response)
}
const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`]
if (cookie.domain) {
cookieAttributes.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
cookieAttributes.push(`Path=${cookie.path}`)
}
if (cookie.expires) {
cookieAttributes.push(`Expires=${cookie.expires}`)
}
if (cookie.maxAge) {
cookieAttributes.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.httpOnly) {
cookieAttributes.push('HttpOnly')
}
if (cookie.secure) {
cookieAttributes.push('Secure')
}
if (cookie.sameSite) {
cookieAttributes.push(`SameSite=${cookie.sameSite}`)
}
if (cookie.partitioned) {
cookieAttributes.push('Partitioned')
}
headers.append('Set-Cookie', cookieAttributes.join('; '))
})
}
| src/index.ts | exporio-edge-sdk-hono-23bcafc | [
{
"filename": "src/types/general.ts",
"retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }",
"score": 0.7054775953292847
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'",
"score": 0.6970456838607788
},
{
"filename": "src/htmlRewriterClasses/After.ts",
"retrieved_chunk": "class After {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.after(this.content, this.contentOptions)\n }",
"score": 0.687067449092865
},
{
"filename": "src/htmlRewriterClasses/Replace.ts",
"retrieved_chunk": "class Replace {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.replace(this.content, this.contentOptions)\n }",
"score": 0.6839699745178223
},
{
"filename": "src/htmlRewriterClasses/Before.ts",
"retrieved_chunk": "class Before {\n content: string\n contentOptions?: ContentOptions\n constructor(content: string, contentOptions?: ContentOptions) {\n this.content = content\n this.contentOptions = contentOptions\n }\n element(element: Element) {\n element.before(this.content, this.contentOptions)\n }",
"score": 0.6812652945518494
}
] | typescript | const buildRequestJson = (c: Context, apiKey: string): RequestJson => { |
import { Context, MiddlewareHandler } from 'hono'
import { Instructions, ExporioMiddlewareOptions, RequestJson } from './types'
import {
After,
Append,
AppendGlobalCode,
Before,
Prepend,
Remove,
RemoveAndKeepContent,
RemoveAttribute,
Replace,
SetAttribute,
SetInnerContent,
SetStyleProperty,
} from './htmlRewriterClasses'
export const exporioMiddleware = (options: ExporioMiddlewareOptions): MiddlewareHandler => {
if (!options.url) {
options.url = 'https://edge-api.exporio.cloud'
}
if (!options.apiKey) {
throw new Error('Exporio middleware requires options for "apiKey"')
}
return async (c, next) => {
const exporioInstructions = await fetchExporioInstructions(c, options)
if (!exporioInstructions) {
c.set('contentUrl', c.req.url)
await next()
} else {
c.set('contentUrl', getContentUrl(exporioInstructions, c.req.url))
await next()
applyRewriterInstruction(c, exporioInstructions)
applyCookieInstruction(c.res.headers, exporioInstructions)
}
}
}
const buildRequestJson = (c: Context, apiKey: string): RequestJson => {
const headersInit: HeadersInit = []
c.req.headers.forEach((value: string, key: string) => headersInit.push([key, value]))
return {
originalRequest: {
url: c.req.url,
method: c.req.method,
headersInit: headersInit,
},
params: {
API_KEY: apiKey,
},
}
}
const fetchExporioInstructions = async (
c: Context,
options: ExporioMiddlewareOptions
): Promise<Instructions | null> => {
try {
const requestJson = buildRequestJson(c, options.apiKey)
const exporioRequest = new Request(options.url, {
method: 'POST',
body: JSON.stringify(requestJson),
headers: { 'Content-Type': 'application/json' },
})
const exporioResponse = await fetch(exporioRequest)
return await exporioResponse.json()
} catch (err) {
console.error('Failed to fetch exporio instructions', err)
return null
}
}
const getContentUrl = (instructions: Instructions, defaultUrl: string): string => {
| const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
} |
const applyRewriterInstruction = (c: Context, instructions: Instructions) => {
let response = new Response(c.res.body, c.res)
instructions?.rewriterInstruction?.transformations?.forEach(({ selector, argument1, argument2, method }) => {
switch (method) {
// Default Methods
case 'After': {
const rewriter = new HTMLRewriter().on(selector, new After(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Append': {
const rewriter = new HTMLRewriter().on(selector, new Append(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Before': {
const rewriter = new HTMLRewriter().on(selector, new Before(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Prepend': {
const rewriter = new HTMLRewriter().on(selector, new Prepend(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'Remove': {
const rewriter = new HTMLRewriter().on(selector, new Remove())
response = rewriter.transform(response)
break
}
case 'RemoveAndKeepContent': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAndKeepContent())
response = rewriter.transform(response)
break
}
case 'RemoveAttribute': {
const rewriter = new HTMLRewriter().on(selector, new RemoveAttribute(argument1))
response = rewriter.transform(response)
break
}
case 'Replace': {
const rewriter = new HTMLRewriter().on(selector, new Replace(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetAttribute': {
const rewriter = new HTMLRewriter().on(selector, new SetAttribute(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetInnerContent': {
const rewriter = new HTMLRewriter().on(selector, new SetInnerContent(argument1, argument2))
response = rewriter.transform(response)
break
}
// Custom Methods
case 'AppendGlobalCode': {
const rewriter = new HTMLRewriter().on(selector, new AppendGlobalCode(argument1, argument2))
response = rewriter.transform(response)
break
}
case 'SetStyleProperty': {
const rewriter = new HTMLRewriter().on(selector, new SetStyleProperty(argument1, argument2))
response = rewriter.transform(response)
break
}
}
})
c.res = new Response(response.body, response)
}
const applyCookieInstruction = (headers: Headers, instructions: Instructions) => {
instructions?.cookieInstruction?.cookies.forEach((cookie) => {
let cookieAttributes = [`${cookie.name}=${cookie.value}`]
if (cookie.domain) {
cookieAttributes.push(`Domain=${cookie.domain}`)
}
if (cookie.path) {
cookieAttributes.push(`Path=${cookie.path}`)
}
if (cookie.expires) {
cookieAttributes.push(`Expires=${cookie.expires}`)
}
if (cookie.maxAge) {
cookieAttributes.push(`Max-Age=${cookie.maxAge}`)
}
if (cookie.httpOnly) {
cookieAttributes.push('HttpOnly')
}
if (cookie.secure) {
cookieAttributes.push('Secure')
}
if (cookie.sameSite) {
cookieAttributes.push(`SameSite=${cookie.sameSite}`)
}
if (cookie.partitioned) {
cookieAttributes.push('Partitioned')
}
headers.append('Set-Cookie', cookieAttributes.join('; '))
})
}
| src/index.ts | exporio-edge-sdk-hono-23bcafc | [
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": " argument2: any\n}\ntype RewriterInstruction = {\n useRewriter: boolean\n transformations: Transformation[]\n}\ntype CustomUrlInstruction = {\n loadCustomUrl: boolean\n customUrl: string | null\n}",
"score": 0.7598388195037842
},
{
"filename": "src/types/instructions.ts",
"retrieved_chunk": "type Instructions = {\n customUrlInstruction: CustomUrlInstruction\n rewriterInstruction: RewriterInstruction\n cookieInstruction: CookieInstruction\n}\nexport { Instructions, CustomUrlInstruction, RewriterInstruction, Transformation, CookieInstruction, Cookie }",
"score": 0.7414118051528931
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export { ExporioMiddlewareOptions, RequestJson } from './general'\nexport {\n Instructions,\n CustomUrlInstruction,\n RewriterInstruction,\n Transformation,\n CookieInstruction,\n Cookie,\n} from './instructions'",
"score": 0.7224920392036438
},
{
"filename": "src/types/general.ts",
"retrieved_chunk": "type ExporioMiddlewareOptions = {\n url: string\n apiKey: string\n}\ntype RequestJson = {\n originalRequest: {\n url: string\n method: string\n headersInit: HeadersInit\n }",
"score": 0.6999710202217102
},
{
"filename": "src/htmlRewriterClasses/SetStyleProperty.ts",
"retrieved_chunk": "class SetStyleProperty {\n propertyName: string\n propertyValue: string\n constructor(propertyName: string, propertyValue: string) {\n this.propertyName = propertyName\n this.propertyValue = propertyValue\n }\n element(element: Element) {\n let currentStyleAttribute = element.getAttribute('style') || ''\n if (currentStyleAttribute.includes(`${this.propertyName}:`)) {",
"score": 0.6869356632232666
}
] | typescript | const customUrlInstruction = instructions?.customUrlInstruction
return customUrlInstruction?.loadCustomUrl && customUrlInstruction?.customUrl
? customUrlInstruction.customUrl
: defaultUrl
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.