began multiplayer

This commit is contained in:
2026-02-21 13:53:08 +01:00
parent 6412ba2a62
commit 16519532c1
5 changed files with 146 additions and 56 deletions

View File

@@ -1,8 +1,9 @@
import { crew } from "@kaplayjs/crew";
import kaplay, { Comp, EmptyComp } from "kaplay";
import kaplay from "kaplay";
import { createCards } from "./card";
import { WOBBLE_ANGLE, SPEED } from "./constants";
import "kaplay/global"; // uncomment if you want to use without the prefix
import { initWebRTC } from "./multiplayer";
export const k = kaplay({
plugins: [crew],
@@ -124,6 +125,9 @@ scene("menu", () => {
duration: 1,
});
});
const peerIDToConnect = location.pathname.replace("/", "");
initWebRTC(peerIDToConnect);
});
scene("game", (scravatar: string) => {
@@ -134,42 +138,6 @@ scene("game", (scravatar: string) => {
setCamPos(lerp(getCamPos(), player.pos, 0.1));
});
const button = add([
pos(10, height() - 50),
rect(120, 40),
outline(3, BLACK),
color("mediumspringgreen"),
area(),
layer("ui"),
fixed(),
"button",
]);
button.add([
pos(60, 20),
anchor("center"),
color(BLACK),
text("Countdown", { font: "happy", size: 14 }),
]);
button.onHover(() => {
button.color = button.color.darken(40);
setCursor("pointer");
});
button.onHoverEnd(() => {
button.color = button.color.lighten(40);
setCursor("default");
});
onClick("button", () => {
addKaboom(mousePos());
});
button.onClick(() => {
addKaboom(mousePos());
});
onKeyDown(["w", "up"], () => {
player.moveBy(0, -SPEED);
});

63
src/multiplayer.ts Normal file
View File

@@ -0,0 +1,63 @@
import { Peer } from "peerjs";
const configuration: RTCConfiguration = {
iceServers: [
{
urls: "stun:stun.relay.metered.ca:80",
},
{
urls: "turn:global.relay.metered.ca:80",
username: "4a945a7d37d35ee816074bb2",
credential: "N3Bhe64kpGzogdjY",
},
{
urls: "turn:global.relay.metered.ca:80?transport=tcp",
username: "4a945a7d37d35ee816074bb2",
credential: "N3Bhe64kpGzogdjY",
},
{
urls: "turn:global.relay.metered.ca:443",
username: "4a945a7d37d35ee816074bb2",
credential: "N3Bhe64kpGzogdjY",
},
{
urls: "turns:global.relay.metered.ca:443?transport=tcp",
username: "4a945a7d37d35ee816074bb2",
credential: "N3Bhe64kpGzogdjY",
},
],
};
export async function initWebRTC(peerId?: string) {
const peer = new Peer({
config: configuration,
});
peer.on("connection", (conn) => {
console.log(`Connection received from: ${conn.peer}`);
conn.on("open", () => {
conn.on("data", (data) => {
console.log(`Data: ${data}`);
});
conn.send("Hello from HOST?!");
});
});
peer.on("open", (id) => {
console.log(`My peer ID is: ${id}`);
if (peerId) {
console.log(`Connecting to: ${peerId}`);
const conn = peer.connect(peerId);
conn.on("open", () => {
conn.on("data", (data) => {
console.log(`Data: ${data}`);
});
conn.send("Hello from CLIENT!");
});
}
});
}