Skip to content

Commit

Permalink
Support multi-game .ptn files
Browse files Browse the repository at this point in the history
  • Loading branch information
gruppler committed Sep 3, 2024
1 parent 06ec5f6 commit af05aaa
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 26 deletions.
7 changes: 7 additions & 0 deletions src/Game/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ export default class GameBase {
return params;
}

// Split multi-game PTN into separate games
static split(ptn) {
return ptn.match(
/^\s*(\[\w+\s"[^"]*"\]\s*)+((\{[^}]*\})*[/.\s\da-hCFRS!?"'><+-]+)+/gm
);
}

// #region Init
init({
ptn,
Expand Down
60 changes: 34 additions & 26 deletions src/store/game/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -444,11 +444,41 @@ export const OPEN_FILES = async function ({ dispatch, state }, files) {
resolve;
}
};

const onInit = (game) => {
games.push(game);
finish();
};

const parseGame = (ptn, name) => {
const onError = (error, plyID) => {
console.warn(
`Encountered an error in "${name}" at plyID:`,
plyID,
error
);
notifyError(`${name}: ${error.message}`);
finish();
};

const index = state.list.findIndex((g) => g.name === name);
if (index < 0 || this.state.ui.openDuplicate !== "replace") {
try {
new Game({
ptn,
name,
onError,
onInit,
});
} catch (error) {
console.error("Invalid game:", name, error);
}
} else {
dispatch("REPLACE_GAME", { index, ptn });
finish();
}
};

files = Array.from(files);
files = files.filter((file) => file && /(\.ptn|\.txt)+$/i.test(file.name));
if (!files.length) {
Expand All @@ -462,32 +492,10 @@ export const OPEN_FILES = async function ({ dispatch, state }, files) {
let reader = new FileReader();
reader.onload = (event) => {
const name = file.name.replace(/(\.ptn|\.txt)+$/, "");
const index = state.list.findIndex((g) => g.name === name);
const ptn = event.target.result;
const onError = (error, plyID) => {
console.warn(
`Encountered an error in "${name}" at plyID:`,
plyID,
error
);
notifyError(`${name}: ${error.message}`);
finish();
};
if (index < 0 || this.state.ui.openDuplicate !== "replace") {
try {
new Game({
ptn,
name,
onError,
onInit,
});
} catch (error) {
console.error("Invalid game:", name, error);
}
} else {
dispatch("REPLACE_GAME", { index, ptn });
finish();
}
const games = Game.split(event.target.result);
games.forEach((ptn, i) => {
parseGame(ptn, `${name} - Game ${i + 1}`);
});
};
reader.onerror = notifyError;
reader.readAsText(file);
Expand Down

0 comments on commit af05aaa

Please sign in to comment.