let mapLayout = [];
let players = {};
let localPlayer = {
position: { x: 0, y: 0 },
color: { r: 255, g: 255, b: 255 },
name: "Player" + Math.floor(Math.random() * 1000) // Dynamic name
};
let socket;
let tileSprites = [];
let playerSprites = {};
// Utility to deserialize data from server
function deserialize(data) {
try {
return JSON.parse(data);
} catch (error) {
console.error("Deserialization error:", error);
return null;
}
}
mapLayout.forEach((row, y) => {
row.forEach((tile, x) => {
if (tile === 1) {
const tileSprite = add([
sprite("tile"),
pos(x * tileSize, y * tileSize),
area(),
layer("tiles")
]);
tileSprites.push(tileSprite); // Store the tile sprite
}
});
});
}
function drawPlayers() {
// Update existing player sprites or add new ones
Object.values(players).forEach(player => {
if (playerSprites[player.id]) {
// Update position and color
playerSprites[player.id].pos = vec2(player.position.x, player.position.y);
playerSprites[player.id].color = rgb(player.color.r, player.color.g, player.color.b);
} else {
// Add new player sprite
playerSprites[player.id] = add([
sprite("player"),
pos(player.position.x, player.position.y),
color(player.color.r, player.color.g, player.color.b),
scale(2), // Increased scale for larger player
area(),
layer("players")
]);
}
});
// Remove sprites of disconnected players
for (let id in playerSprites) {
if (!players[id]) {
destroy(playerSprites[id]);
delete playerSprites[id];
}
}
}
// Connect to the server
connectToServer();
// Player movement
onKeyDown("left", () => {
localPlayer.position.x -= tileSize;
sendPlayerUpdate();
});
onKeyDown("right", () => {
localPlayer.position.x += tileSize;
sendPlayerUpdate();
});
onKeyDown("up", () => {
localPlayer.position.y -= tileSize;
sendPlayerUpdate();
});
onKeyDown("down", () => {
localPlayer.position.y += tileSize;
sendPlayerUpdate();
});
// Send local player position to server
function sendPlayerUpdate() {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
position: localPlayer.position,
}));
}
}
// Update player positions and redraw the map on each frame
onUpdate(() => {
drawPlayers();
});
// Connect to the server function
function connectToServer() {
socket = new WebSocket(`ws://${serverHost}:${serverPort}`);
socket.addEventListener("open", () => {
console.log("Connected to server");
socket.send(JSON.stringify({ name: localPlayer.name })); // Send player name
});
socket.addEventListener("message", (event) => {
const data = deserialize(event.data); // Directly use event.data
if (!data) return;
if (data.map_layout) {
mapLayout = data.map_layout;
drawMap(); // Call drawMap() after updating the map layout
}
if (data.players) {
players = data.players || players;
drawPlayers(); // Call drawPlayers() after updating player data
}
});
socket.addEventListener("close", () => {
console.log("Disconnected from server");
});
}
let currentMapLayout = mapLayouts[0];
const connections = [];
// Function to serialize data for sending to clients
function serialize(data) {
return JSON.stringify(data);
}
// Function to get a random spawn position
function getRandomSpawnPosition() {
const x = randomInt(0, currentMapLayout[0].length);
const y = randomInt(0, currentMapLayout.length);
return { x: x * tileSize, y: y * tileSize };
}
// Function to generate a random color
function generateColor() {
return {
r: randomInt(0, 256),
g: randomInt(0, 256),
b: randomInt(0, 256)
};
}
// Function to change map layout periodically
async function changeMapLayoutPeriodically() {
let mapIndex = 1; // Start from the second map since currentMapLayout is mapLayouts[0]
while (true) {
await setTimeoutPromise(60000); // Change map layout every 60 seconds
currentMapLayout = mapLayouts[mapIndex];
mapIndex = (mapIndex + 1) % mapLayouts.length;
code
console.log("Map layout changed.");
// Send the new map layout to all connected clients
broadcast({ players, map_layout: currentMapLayout });
}
// Assign a unique ID to each WebSocket connection
ws.id = generateUniqueID();
// Handle incoming messages from this client
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
if (message.name) {
// Initial connection message with player name
const playerName = message.name;
// Generate a unique spawn position
const spawnPosition = getRandomSpawnPosition();
// Initialize new player with a unique color and position
players[ws.id] = { // Use the unique identifier as key
id: ws.id,
name: playerName,
position: spawnPosition,
color: generateColor()
};
// Send initial positions and map layout to the new client
ws.send(serialize({ players, map_layout: currentMapLayout }));
// Broadcast to others about the new player
broadcast({ players, map_layout: currentMapLayout });
} else if (message.position) {
// Position update message
if (players[ws.id]) {
players[ws.id].position = message.position;
// Broadcast updated positions to all clients
broadcast({ players, map_layout: currentMapLayout });
}
}
} catch (e) {
console.error(`Error processing data: ${e.message}`);
}
});
ws.on('close', () => {
console.log('Client disconnected');
// Remove player from players object
if (players[ws.id]) {
delete players[ws.id];
}
connections.splice(connections.indexOf(ws), 1);
// Inform remaining clients about the disconnected player
broadcast({ players });
});
});
// Function to generate a unique ID (simple incrementing counter or UUID)
let currentID = 1;
function generateUniqueID() {
return currentID++;
}
// Start server and change map layout periodically
console.log(WebSocket server running on ws://localhost:${PORT});
changeMapLayoutPeriodically();
migrate from kaboom to kaplayjs
Migrating from v2000 to v3000
obj._id is renamed to obj.id
const obj = add([pos(300, 200), sprite("bean"), area()]);
// before
console.log(obj._id);
// v3000
console.log(obj.id);
origin() is renamed to anchor()
// before
add([sprite("bean"), origin("center")]);
// v3000
add([sprite("bean"), anchor("center")]);
obj.onHover() in area() comp is renamed to obj.onHoverUpdate(), obj.onHover() now only runs once when obj is hovered
const obj = add([pos(300, 200), sprite("bean"), area()]);
// before
obj.onHover(
() => {
console.log("this will print every frame when obj is hovered");
},
() => {
console.log("this will print every frame when obj is not hovered");
},
);
// v3000
obj.onHover(() => {
console.log("this will run once when obj is hovered");
});
obj.onHoverUpdate(() => {
console.log("this will run every frame when obj is hovered");
});
obj.onHoverEnd(() => {
console.log("this will run once when obj stopped being hovered");
});
obj.pushOut() is renamed to obj.resolveCollision()
const player = add([sprite("bean"), pos(300, 200), area()]);
// before
player.pushOut(rock);
// v3000
player.resolveCollision(rocker);
solid() comp becomes an option in body({ isStatic: true })
// before
add([sprite("bean"), area(), body(), solid()]);
// v3000
add([sprite("bean"), area(), body({ isStatic: true })]);
gravity now needs to be manually enabled, gravity() is renamed to setGravity() and getGravity()
// before, gravity will be enabled by body() component
add([pos(100, 100), sprite("bean"), area(), body()]);
// v3000, use gravity() to manually enable gravity
setGravity(1600);
add([pos(100, 100), sprite("bean"), area(), body()]);
body.weight is renamed to body.gravityScale
// before
add([body({ weight: 2 })]);
// before
add([body({ gravityScale: 2 })]);
body.doubleJump() is removed in favor of new doubleJump() component
const obj = add([pos(100, 100), sprite("bean"), area(), body()]);
// before
obj.onFall(() => {
console.log("this will print when object falls off a platform");
});
// v3000
obj.onFallOff(() => {
console.log("this will print when object falls off a platform");
});
obj.onFall(() => {
console.log("this will print when object is in the air and starts falling");
});
removed outview() in favor of offscreen(), which is less accurate but much faster
// before
add([sprite("flower"), outview({ hide: true })]);
// v3000
add([
sprite("flower"),
// will hide itself when its position is 64 pixels offscreen
offscreen({ hide: true, distance: 64 }),
]);
removed cleanup() in favor of offscreen({ destroy: true })
// before
add([pos(player.pos), sprite("bullet"), cleanup()]);
// v3000
add([pos(player.pos), sprite("bullet"), offscreen({ destroy: true })]);
sprite.flipX and sprite.flipY becomes properties instead of functions
const bean = add([sprite("bean")]);
// before
bean.flipX(true);
// v3000
bean.flipX = true;
sprite.onAnimStart() and sprite.onAnimEnd() now triggers on any animation
const bean = add([sprite("bean")]);
// before
bean.onAnimStart("walk", () => {
// do something
});
// before
bean.onAnimStart((anim) => {
if (anim === "walk") {
// do something
}
});
obj.scale now is always a Vec2
scale(2); // scale is vec2(2, 2)
obj.scale; // vec2(2, 2)
loadFont() now only loads .ttf, .otf, .woff etc fonts that browser support, use loadBitmapFont() to load bitmap fonts
// before
loadFont("unscii", "/examples/fonts/unscii_8x8.png", 8, 8);
// v3000
loadBitmapFont("unscii", "/examples/fonts/unscii_8x8.png", 8, 8);
loadFont("apl386", "/examples/fonts/apl386.ttf");
removed builtin fonts apl386, apl386o, sink and sinko, using browser built-in monospace font as default font now
// v3000, manually load these fonts if you need them
loadFont("apl386", "/examples/fonts/apl386.ttf");
loadBitmapFont("sink", "/examples/fonts/sink_6x8.png");
// use outline option for "apl386o"
loadFont("apl386", "/examples/fonts/apl386.ttf", {
outline: 3,
});
changed vertex format from vec3 to vec2 (only applied in shaders)
// before
loadShader(
"test",
null,
vec4 frag(vec3 pos, vec2 uv, vec4 color, sampler2D tex) { return def_frag(); },
);
// v3000
loadShader(
"test",
null,
vec4 frag(vec2 pos, vec2 uv, vec4 color, sampler2D tex) { return def_frag(); },
);
anchor (previously origin) no longer controls text alignment (only controls the anchor of the whole text area), use text({ align: "left" }) option for text alignment
// before
add([pos(center()), origin("center"), text("oh hi")]);
// before
add([text("[oh hi].green here's some [styled].wavy text", textOpts)]);
// v3000
add([
text("[green]oh hi[/green] here's some [wavy]styled[/wavy] text", textOpts),
]);
changed all event handlers to return an EventController object, instead of a function to cancel
// before
const cancel = onUpdate(() => {
/* ... */
});
cancel();
To address the issues you've outlined—players not being visible to others, making the game fullscreen, and adding gravity and jump mechanics—we need to make several adjustments to both your client.js and server.js files. Additionally, we'll ensure that the code is compatible with the latest Kaplay.js v3000 API based on your migration notes.
Below are the comprehensive fixes and enhancements:
1. Client-Side (client.js) Enhancements
A. Make the Game Fullscreen
To make the game adapt to the entire screen, we'll adjust the game's width and height based on the browser window size. We'll also add an event listener to handle window resizing dynamically.
B. Fix Player Visibility
Ensure that each player, including the local player, is correctly added to the players object and that their sprites are properly managed. We'll synchronize the local player's ID with the server-assigned ID to prevent conflicts.
C. Add Gravity and Jump Mechanics
Implement gravity using the setGravity function and add jump mechanics by handling key presses. We'll use the body component to manage physics for each player.
D. Update to Kaplay.js v3000 API
Apply necessary changes based on the migration notes, such as renaming origin to anchor, updating event handlers, and adjusting sprite properties.
Complete Updated client.js
javascript
import kaplay from "kaplay";
import "kaplay/global";
// Initialize gravity
setGravity(1600);
const k = kaplay({
width: window.innerWidth,
height: window.innerHeight,
scale: 2,
});
// Update the canvas size on window resize
window.addEventListener('resize', () => {
k.updateSize(window.innerWidth, window.innerHeight);
});
const tileSize = 36; // Tile size for the map
const serverHost = 'localhost';
const serverPort = 25566;
let mapLayout = [];
let players = {};
let localPlayerId = null;
let socket;
let tileSprites = [];
let playerSprites = {};
// Utility to deserialize data from server
function deserialize(data) {
try {
return JSON.parse(data);
} catch (error) {
console.error("Deserialization error:", error);
return null;
}
}
// Load sprites
loadSprite("tile", "/sprites/grass.png");
loadSprite("player", "/sprites/player.png");
scene("game", () => {
// Function to draw the map based on the map layout
function drawMap() {
tileSprites.forEach(tile => tile.destroy());
tileSprites = [];
mapLayout.forEach((row, y) => {
row.forEach((tile, x) => {
if (tile === 1) {
const tileSprite = add([
sprite("tile"),
pos(x * tileSize, y * tileSize),
area(),
layer("tiles"),
solid(), // Make tiles solid for collision
]);
tileSprites.push(tileSprite);
}
});
});
}
// Function to draw and update player sprites
function drawPlayers() {
// Update existing player sprites or add new ones
Object.values(players).forEach(player => {
if (playerSprites[player.id]) {
// Update position and color
playerSprites[player.id].pos = vec2(player.position.x, player.position.y);
playerSprites[player.id].color = rgb(player.color.r, player.color.g, player.color.b);
} else {
// Add new player sprite
let components = [
sprite("player"),
pos(player.position.x, player.position.y),
color(player.color.r, player.color.g, player.color.b),
scale(2),
area(),
anchor("center"),
body({ gravityScale: 2 }), // Add body for physics
];
if (player.id === localPlayerId) {
components.push(
"localplayer" // Tag to identify the local player
);
} else {
components.push(
"player" // Tag for other players
);
}
playerSprites[player.id] = add(components);
}
});
// Remove sprites of disconnected players
for (let id in playerSprites) {
if (!players[id]) {
destroy(playerSprites[id]);
delete playerSprites[id];
}
}
}
// Function to set up controls for the local player
function setupPlayerControls(playerObj) {
onKeyDown("left", () => {
playerObj.move(-200, 0); // Move left
sendPlayerUpdate();
});
onKeyDown("right", () => {
playerObj.move(200, 0); // Move right
sendPlayerUpdate();
});
onKeyPress("space", () => {
if (playerObj.isGrounded()) {
playerObj.jump(); // Jump
sendPlayerUpdate();
}
});
}
// Function to send the local player's position to the server
function sendPlayerUpdate() {
if (socket.readyState === WebSocket.OPEN && localPlayerId) {
const player = players[localPlayerId];
if (player) {
socket.send(JSON.stringify({
id: player.id,
position: {
x: playerSprites[player.id].pos.x,
y: playerSprites[player.id].pos.y,
},
}));
}
}
}
// Connect to the WebSocket server
connectToServer();
// Update player positions and handle rendering each frame
onUpdate(() => {
drawPlayers();
// If the local player sprite exists, set up controls
if (localPlayerId && playerSprites[localPlayerId] && !playerSprites[localPlayerId].controlsSet) {
setupPlayerControls(playerSprites[localPlayerId]);
playerSprites[localPlayerId].controlsSet = true; // Prevent re-initializing controls
}
});
// Function to connect to the WebSocket server
function connectToServer() {
socket = new WebSocket(`ws://${serverHost}:${serverPort}`);
socket.addEventListener("open", () => {
console.log("Connected to server");
const playerName = "Player" + Math.floor(Math.random() * 1000);
socket.send(JSON.stringify({
name: playerName,
})); // Send player name to the server
});
socket.addEventListener("message", (event) => {
const data = deserialize(event.data);
if (!data) return;
if (data.map_layout) {
mapLayout = data.map_layout;
drawMap(); // Redraw the map when layout updates
}
if (data.players) {
players = data.players;
// Identify and set the local player's ID if not already set
if (!localPlayerId && data.local_id) {
localPlayerId = data.local_id;
}
drawPlayers(); // Redraw players when data updates
}
});
socket.addEventListener("close", () => {
console.log("Disconnected from server");
});
}
});
// Start the game
go("game");
Key Changes Explained:
Fullscreen Setup:
The game canvas now initializes with window.innerWidth and window.innerHeight to occupy the full screen.
An event listener ensures the canvas resizes dynamically when the browser window is resized.
Player Management:
Upon connection, the server assigns a unique local_id to the client, which is used to identify the local player.
The drawPlayers function manages adding, updating, and removing player sprites based on the players object received from the server.
Gravity and Physics:
Gravity is set globally using setGravity(1600).
Each player sprite includes the body component with a gravityScale to handle physics.
The local player has controls set up to handle left/right movement and jumping.
Event Handling and Controls:
Controls are bound to the local player only. The controlsSet flag ensures that controls are not re-initialized every frame.
The sendPlayerUpdate function sends the local player's position to the server whenever movement occurs.
Compatibility with Kaplay.js v3000:
Replaced origin with anchor.
Updated sprite properties and event handlers as per the migration notes.
2. Server-Side (server.js) Enhancements
A. Assign Unique IDs to Clients and Notify Them
Ensure that each client receives a unique ID upon connection, which is then used to synchronize player data across all clients.
B. Broadcast Player Data Correctly
When a new player connects or updates their position, broadcast the updated players object and map_layout to all connected clients.
C. Handle Disconnections Properly
Remove players from the players object when they disconnect and notify remaining clients.
Complete Updated server.js
javascript
Key Changes Explained:
Unique ID Assignment:
Each client connection is assigned a unique ws.id using the generateUniqueID function.
Upon receiving a player's name, the server assigns a spawn position and a random color.
Initial Data Transmission:
When a player connects, the server sends back the current players object, map_layout, and the local_id (unique ID assigned to the client).
This ensures that the client knows its own ID and can synchronize properly.
Handling Position Updates:
When the server receives a position update from a client, it updates the corresponding player's position and broadcasts the updated players object to all clients.
Broadcast Mechanism:
The broadcast function sends serialized data to all connected clients.
This function is used to notify all clients about new players, position updates, map changes, and player disconnections.
Map Layout Management:
The server periodically changes the map layout every 60 seconds and broadcasts the new layout to all clients.
Disconnection Handling:
When a client disconnects, the server removes the player from the players object and notifies remaining clients to remove the player's sprite.
3. Summary of Fixes and Enhancements
Player Visibility:
Ensured that each player, including the local player, is correctly managed and synchronized between the server and all clients.
The client now correctly identifies the local player using the local_id provided by the server.
Fullscreen Game:
The game canvas dynamically adjusts to the browser window size, providing a fullscreen experience.
The canvas resizes in real-time when the browser window is resized.
Gravity and Jump Mechanics:
Gravity is globally set, and each player has a body component that handles physics.
Jumping is implemented by checking if the player is grounded before allowing a jump.
Movement controls (left, right, jump) are bound to the local player only.
API Compatibility:
Updated the code to be compatible with Kaplay.js v3000 based on the provided migration notes.
Replaced deprecated functions and updated component properties accordingly.
4. Additional Recommendations
Optimizing Network Traffic:
Consider implementing rate limiting or interpolation to reduce the amount of position data sent over the network and to smooth out player movements.
Error Handling:
Enhance error handling on both client and server sides to manage unexpected scenarios gracefully.
Security Considerations:
Implement validation on the server to ensure that incoming data from clients is legitimate and to prevent potential exploits.
Advanced Physics:
Depending on your game's requirements, you might want to implement more advanced physics, such as collision responses, friction, and more sophisticated jump mechanics.
User Interface Enhancements:
Add UI elements such as player names, scores, and health indicators to enhance the gameplay experience.
By implementing these changes, your multiplayer game should now display all players correctly, adapt to fullscreen, and feature gravity and jump mechanics for a more engaging gameplay experience.
const WebSocket = require('ws');
const { randomInt } = require('crypto'); // For generating random integers
const { promisify } = require('util');
const setTimeoutPromise = promisify(setTimeout);
const PORT = 25566;
const players = {};
const tileSize = 36; // Updated to match client
const mapLayouts = [
// Example map layouts
[
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
// ... more rows
],
[
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
// ... more rows
]
];
let currentMapLayout = mapLayouts[0];
const connections = [];
// Function to serialize data for sending to clients
function serialize(data) {
return JSON.stringify(data);
}
// Function to get a random spawn position
function getRandomSpawnPosition() {
const x = randomInt(0, currentMapLayout[0].length) * tileSize;
const y = randomInt(0, currentMapLayout.length) * tileSize;
return { x, y };
}
// Function to generate a random color
function generateColor() {
return {
r: randomInt(0, 256),
g: randomInt(0, 256),
b: randomInt(0, 256)
};
}
// Function to change map layout periodically
async function changeMapLayoutPeriodically() {
let mapIndex = 1; // Start from the second map
while (true) {
await setTimeoutPromise(60000); // Change map layout every 60 seconds
currentMapLayout = mapLayouts[mapIndex];
mapIndex = (mapIndex + 1) % mapLayouts.length;
console.log("Map layout changed.");
// Send the new map layout to all connected clients
broadcast({ players, map_layout: currentMapLayout });
}
}
// Broadcast utility to send data to all clients
function broadcast(data) {
const message = serialize(data);
connections.forEach(ws => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(message);
}
});
}
// Create WebSocket server
const wss = new WebSocket.Server({ port: PORT });
wss.on('connection', (ws) => {
console.log('Client connected');
connections.push(ws);
// Assign a unique ID to each WebSocket connection
ws.id = generateUniqueID();
// Handle incoming messages from this client
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
if (message.name) {
// Initial connection message with player name
const playerName = message.name;
// Generate a unique spawn position
const spawnPosition = getRandomSpawnPosition();
// Initialize new player with a unique color and position
players[ws.id] = { // Use the unique identifier as key
id: ws.id,
name: playerName,
position: spawnPosition,
color: generateColor()
};
// Send initial data to the new client, including their assigned id
ws.send(serialize({
players,
map_layout: currentMapLayout,
local_id: ws.id,
}));
// Broadcast to others about the new player
broadcast({ players, map_layout: currentMapLayout });
} else if (message.position && message.id) {
// Position update message
if (players[message.id]) {
players[message.id].position = message.position;
// Broadcast updated positions to all clients
broadcast({ players, map_layout: currentMapLayout });
}
}
} catch (e) {
console.error(`Error processing data: ${e.message}`);
}
});
ws.on('close', () => {
console.log('Client disconnected');
// Remove player from players object
if (players[ws.id]) {
delete players[ws.id];
}
connections.splice(connections.indexOf(ws), 1);
// Inform remaining clients about the disconnected player
broadcast({ players });
});
});
// Function to generate a unique ID (simple incrementing counter)
let currentID = 1;
function generateUniqueID() {
return currentID++;
}
// Start server and change map layout periodically
console.log(`WebSocket server running on ws://localhost:${PORT}`);
changeMapLayoutPeriodically();