Skip to content

Commit

Permalink
1.21 The Sounds Update
Browse files Browse the repository at this point in the history
Added startpos and loop to sounds
make sound setup better
added newgrounds sounds via CUSTOM with sound ids (this took a month)
removed herobrine
  • Loading branch information
niceEli committed May 16, 2024
1 parent f8c8383 commit 82199fe
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 8 deletions.
Binary file modified bun.lockb
Binary file not shown.
76 changes: 75 additions & 1 deletion src/kLdtkWorlds/campaign/Empty.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"iid": "a26276c0-7820-11ed-b6fd-ed05d55c9a75",
"jsonVersion": "1.5.3",
"appBuildId": 473703,
"nextUid": 226,
"nextUid": 228,
"identifierStyle": "Free",
"toc": [],
"worldLayout": "Free",
Expand Down Expand Up @@ -2149,6 +2149,80 @@
"allowedRefTags": [],
"tilesetUid": null
},
{
"identifier": "StartPos",
"doc": "This is where the song starts (in seconds)",
"__type": "Float",
"uid": 226,
"type": "F_Float",
"isArray": false,
"canBeNull": false,
"arrayMinLength": null,
"arrayMaxLength": null,
"editorDisplayMode": "ValueOnly",
"editorDisplayScale": 1,
"editorDisplayPos": "Above",
"editorLinkStyle": "StraightArrow",
"editorDisplayColor": null,
"editorAlwaysShow": false,
"editorShowInWorld": true,
"editorCutLongValues": true,
"editorTextSuffix": null,
"editorTextPrefix": "StartPos: ",
"useForSmartColor": false,
"exportToToc": false,
"searchable": false,
"min": 0,
"max": null,
"regex": null,
"acceptFileTypes": null,
"defaultOverride": null,
"textLanguageMode": null,
"symmetricalRef": false,
"autoChainRef": true,
"allowOutOfLevelRef": true,
"allowedRefs": "OnlySame",
"allowedRefsEntityUid": null,
"allowedRefTags": [],
"tilesetUid": null
},
{
"identifier": "Loop",
"doc": "Enable If You Want The Song To Loop",
"__type": "Bool",
"uid": 227,
"type": "F_Bool",
"isArray": false,
"canBeNull": false,
"arrayMinLength": null,
"arrayMaxLength": null,
"editorDisplayMode": "NameAndValue",
"editorDisplayScale": 1,
"editorDisplayPos": "Above",
"editorLinkStyle": "StraightArrow",
"editorDisplayColor": null,
"editorAlwaysShow": false,
"editorShowInWorld": true,
"editorCutLongValues": true,
"editorTextSuffix": null,
"editorTextPrefix": null,
"useForSmartColor": false,
"exportToToc": false,
"searchable": false,
"min": null,
"max": null,
"regex": null,
"acceptFileTypes": null,
"defaultOverride": null,
"textLanguageMode": null,
"symmetricalRef": false,
"autoChainRef": true,
"allowOutOfLevelRef": true,
"allowedRefs": "OnlySame",
"allowedRefsEntityUid": null,
"allowedRefTags": [],
"tilesetUid": null
},
{
"identifier": "GroupID",
"doc": "When This Group Is Active This Object Will Run Its Script Or Do Whatever The QWIK_Script Says It Will Do",
Expand Down
59 changes: 53 additions & 6 deletions src/kUtils/kLdtkSceneImporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import matterRect, {
import PlayerPawnCircle from "./kMatterPlayerCircle";
import kCamera from "./kCamera";
import kReset from "./kReset";
import { GameObj, SceneDef, Vec2 } from "kaboom-beta";
import { AudioPlay, GameObj, SceneDef, Vec2 } from "kaboom-beta";
import Matter from "matter-js";
import matterCircle from "./kMatterCircle";
import kDownloadToVar from "./kDownloadToVar";
Expand All @@ -19,6 +19,8 @@ import soundComp from "./soundComp";
import gameInfo from "../gameInfo";
import enemyMovement from "./enemyMovement";
import PlayerPawnCircleTopDown from "./kMatterCircleTopDown";
import getNGSong from "./kNGLoader";
import axios from "axios";

/**
* Imports LDtk scene data and initializes the level, including loading sprites, setting up triggers, handling collisions, and managing game objects.
Expand All @@ -29,7 +31,7 @@ import PlayerPawnCircleTopDown from "./kMatterCircleTopDown";
* @param {any} engine - The physics engine
* @param {Vec2} zoomZ - The zoom vector (default: k.vec2(1, 1))
*/
export default function kLdtkSceneImporter(
export default async function kLdtkSceneImporter(
sceneData,
currentScene: SceneDef,
nextScene: SceneDef,
Expand Down Expand Up @@ -62,6 +64,12 @@ export default function kLdtkSceneImporter(
let i;
let r;

let sfxQ: AudioPlay[] = [];

globalThis.sfxQ = sfxQ;

let xhr = new XMLHttpRequest();

function print(text: any) {
k.debug.log(text);
console.log(text);
Expand All @@ -75,6 +83,20 @@ export default function kLdtkSceneImporter(
printError("kReset Is Deprecated. Please Remove");
}

function kEndSongs() {
for (let i = 0; i < sfxQ.length; i++) {
const sfx = sfxQ[i];
sfx.stop();
}
}

function kSetSongsPause(paused: boolean) {
for (let i = 0; i < sfxQ.length; i++) {
const sfx = sfxQ[i];
sfx.paused = paused;
}
}

let enemys: {
ent?: GameObj;
unkillable?: boolean;
Expand Down Expand Up @@ -501,15 +523,35 @@ export default function kLdtkSceneImporter(
case "Play_Sound":
let qsSound: string;
if (entValues["Name"] === "CUSTOM") {
qsSound = entValues["Custom_Sound"];
if (
Number(entValues["Custom_Sound"]) ==
entValues["Custom_Sound"]
) {
qsSound = "newgroundsAudio_" + entValues["Custom_Sound"];
} else {
qsSound = entValues["Custom_Sound"];
}
} else {
qsSound = kEnumToPath.run(entValues["Name"]);
}

if (!sounds.includes(qsSound)) {
if (qsSound.startsWith("newgroundsAudio_")) {
//16 letter remove
let ngSound = qsSound.substring(16);
k.loadSound(qsSound, await getNGSong(ngSound));
}
sounds.push(qsSound);
}
let Play_Sound_Code = 'k.play("' + String(qsSound) + '");';
let doLoop = false;
if (entValues["Loop"] === true) {
doLoop = true;
}
let seekPos = 0;
if (typeof entValues["StartPos"] == "number") {
seekPos = entValues["StartPos"];
}
let Play_Sound_Code = `sfxQ.push(k.play('${String(qsSound)}', {loop: ${doLoop}, seek: ${seekPos} }));`;
if (
maxGroups < entValues["GroupID"] ||
maxGroups < entValues["NextGID"]
Expand Down Expand Up @@ -806,6 +848,7 @@ export default function kLdtkSceneImporter(
if (sessionStorage.getItem(gameInfo.internalName + "_isUGC") !== "true") {
localStorage.setItem(gameInfo.internalName + "_score", String(score));
}
kEndSongs();
k.scene("nextLevel", nextScene);
k.go("nextLevel");
});
Expand All @@ -815,6 +858,7 @@ export default function kLdtkSceneImporter(

k.onUpdate(() => {
if (isDead) {
kEndSongs();
k.go("scene");
}
});
Expand Down Expand Up @@ -877,6 +921,7 @@ export default function kLdtkSceneImporter(
"levelsize",
"soundComp",
"enemyMovement",
"sfxQ",
`
return (async function() {
${Func}
Expand Down Expand Up @@ -922,7 +967,8 @@ export default function kLdtkSceneImporter(
levelsize,
levelsize,
soundComp,
enemyMovement
enemyMovement,
sfxQ
)
);

Expand Down Expand Up @@ -969,6 +1015,7 @@ export default function kLdtkSceneImporter(
if (IMC.pausing()) {
const objs = k.get("*", { recursive: true });
isPaused = !isPaused;
kSetSongsPause(isPaused);
print("Paused: " + isPaused);
for (let i = 0; i < objs.length; i++) {
const obj = objs[i];
Expand All @@ -982,5 +1029,5 @@ export default function kLdtkSceneImporter(
},
"noPause",
]);
k.add([kReset(currentScene, deathScore)]);
k.add([kReset(currentScene, deathScore, kEndSongs), "noPause"]);
}
63 changes: 63 additions & 0 deletions src/kUtils/kNGLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export default async function getNGSong(id: string): Promise<ArrayBuffer> {
async function getPage(url: string): Promise<string> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "text";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
};
xhr.send();
});
}

if (!id) {
return Promise.reject("Song ID is empty!");
}

try {
const response = await getPage(
`https://api.allorigins.win/get?url=https%3A%2F%2Fwww.newgrounds.com%2Faudio%2Flisten%2F${id}`
);
const data = JSON.parse(response).contents;
const code = JSON.parse(response).status.http_code;

if (code !== 200) {
if (code === 404) {
return Promise.reject(
"The song could not be found! Please check the song id and try again! (error 404)"
);
}
return Promise.reject(
`Something went wrong! Please check your internet connection and try again! Error Code: ${code}`
);
}

let url = data.substring(data.indexOf("<![CDATA[") + 9);
url = url.substring(url.indexOf("embedController([") + 17);
url = url.substring(0, url.indexOf('","'));
url = url.substring(0, url.indexOf("?"));
url = url.substring(url.indexOf("url") + 3);
url = url.substring(url.indexOf(':"') + 2);
url = url.replace(/\\\//g, "/");

let songUrl = `https://cors.niceeli.workers.dev/?${encodeURI(url)}`;

let songArray: ArrayBuffer;
songArray = await (await (await fetch(songUrl)).blob()).arrayBuffer();
return songArray;
} catch (error) {
if (error === 404) {
return Promise.reject(
"The song could not be found! Please check the song id and try again! (error 404)"
);
}
return Promise.reject(
`Something went wrong! Please check your internet connection and try again! Error Code: ${error}`
);
}
}
7 changes: 6 additions & 1 deletion src/kUtils/kReset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import k from "../kaboom";
import * as IMC from "../Controls/INPUT_movement";
import gameInfo from "../gameInfo";

export default function kReset(currentScene: SceneDef, deathScore: number) {
export default function kReset(
currentScene: SceneDef,
deathScore: number,
kEndSongs: any
) {
return {
add() {
k.scene("scene", currentScene);
Expand All @@ -14,6 +18,7 @@ export default function kReset(currentScene: SceneDef, deathScore: number) {
gameInfo.internalName + "_score",
String(deathScore)
);
kEndSongs();
k.go("scene");
}
},
Expand Down
3 changes: 3 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import loadSounds from "./kUtils/kLoadSounds";
import loadScenes from "./kUtils/kLoadScenes";
import gameInfo from "./gameInfo";
import kPlayIntroVid from "./kUtils/kPlayIntroVid";
import getNGSong from "./kUtils/kNGLoader";

console.log(gameInfo);

Expand All @@ -27,6 +28,8 @@ loadSounds();
// Load Scenes
loadScenes();

globalThis.getNGSong = getNGSong;

k.onLoad(async () => {
console.clear();
if (
Expand Down

0 comments on commit 82199fe

Please sign in to comment.