Sure! Let's address each of your requirements step-by-step:
-
Fixing the Player Visibility Issue:
- Issue: The local player is managed separately from other players, which can cause synchronization issues.
- Solution: Integrate the local player into the
players object received from the server, ensuring that all players (including the local one) are managed uniformly.
-
Making the Game Fullscreen:
- Issue: The game dimensions are fixed at 800x600.
- Solution: Modify the game initialization to use the full window size and adjust scaling accordingly.
-
Adding Gravity and Jump Mechanics:
- Issue: Players currently move in tile-sized steps without physics.
- Solution: Implement physics-based movement using gravity and allow players to jump. This involves updating the player sprite with physics components and handling jump inputs.
-
Migration Adjustments:
- Based on your provided migration notes from
kaboom to kaplayjs v3000, ensure that all renamed methods and components are correctly updated.
Below are the updated client.js and server.js files addressing all the above points:
Updated client.js:
import kaplay from "kaplay";
import "kaplay/global";
// Initialize the game to occupy the full window
const k = kaplay({
width: window.innerWidth,
height: window.innerHeight,
scale: 2,
fullscreen: true, // Ensure fullscreen mode
});
const tileSize = 36;
const serverHost = 'localhost';
const serverPort = 25566;
let mapLayout = [];
let players = {};
let localPlayer = {
// position will be set by the server
color: { r: 255, g: 255, b: 255 },
name: "Player" + Math.floor(Math.random() * 1000)
};
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
k.loadSprite("tile", "/sprites/grass.png");
k.loadSprite("player", "/sprites/player.png");
// Enable gravity
k.setGravity(1600); // Adjust gravity as needed
k.scene("game", () => {
function drawMap() {
// Clear previous tiles
tileSprites.forEach(tile => tile.destroy());
tileSprites = [];
// Draw the map
mapLayout.forEach((row, y) => {
row.forEach((tile, x) => {
if (tile === 1) {
const tileSprite = k.add([
k.sprite("tile"),
k.pos(x * tileSize, y * tileSize),
k.area(),
k.layer("tiles"),
k.body({ isStatic: true }) // Make tiles solid
]);
tileSprites.push(tileSprite);
}
});
});
}
function drawPlayers() {
Object.values(players).forEach(player => {
if (playerSprites[player.id]) {
// Update existing player sprite
playerSprites[player.id].pos = k.vec2(player.position.x, player.position.y);
playerSprites[player.id].color = k.rgb(player.color.r, player.color.g, player.color.b);
} else {
// Add new player sprite
playerSprites[player.id] = k.add([
k.sprite("player"),
k.pos(player.position.x, player.position.y),
k.anchor("center"),
k.color(player.color.r, player.color.g, player.color.b),
k.scale(2), // Adjust scale as needed
k.area(),
k.layer("players"),
k.body(), // Enable physics for the player
"player" // Tag for easy reference
]);
}
});
// Remove sprites of disconnected players
for (let id in playerSprites) {
if (!players[id]) {
playerSprites[id].destroy();
delete playerSprites[id];
}
}
}
// Connect to the server
connectToServer();
// Player movement variables
let isJumping = false;
// Handle player controls with physics
k.onKeyDown("left", () => {
if (players[localPlayer.id]) {
players[localPlayer.id].velocity.x = -300; // Adjust speed as needed
sendPlayerUpdate();
}
});
k.onKeyDown("right", () => {
if (players[localPlayer.id]) {
players[localPlayer.id].velocity.x = 300; // Adjust speed as needed
sendPlayerUpdate();
}
});
k.onKeyRelease("left", () => {
if (players[localPlayer.id] && players[localPlayer.id].velocity.x < 0) {
players[localPlayer.id].velocity.x = 0;
sendPlayerUpdate();
}
});
k.onKeyRelease("right", () => {
if (players[localPlayer.id] && players[localPlayer.id].velocity.x > 0) {
players[localPlayer.id].velocity.x = 0;
sendPlayerUpdate();
}
});
k.onKeyPress("space", () => {
if (players[localPlayer.id] && players[localPlayer.id].isGrounded) {
players[localPlayer.id].velocity.y = -600; // Jump strength
sendPlayerUpdate();
}
});
// Send local player state to server
function sendPlayerUpdate() {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
id: localPlayer.id, // Ensure the server knows which player is sending
position: players[localPlayer.id].position,
velocity: players[localPlayer.id].velocity,
}));
}
}
// Update loop
k.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 }));
});
socket.addEventListener("message", (event) => {
const data = deserialize(event.data);
if (!data) return;
if (data.map_layout) {
mapLayout = data.map_layout;
drawMap();
}
if (data.players) {
players = data.players || {};
// Update localPlayer.id if it's not set
if (!localPlayer.id && data.local_id) {
localPlayer.id = data.local_id;
}
drawPlayers();
}
});
socket.addEventListener("close", () => {
console.log("Disconnected from server");
});
}
});
// Start the game
k.go("game");
// Adjust the canvas size when the window is resized
window.addEventListener('resize', () => {
k.resize(window.innerWidth, window.innerHeight);
});
Explanation of Changes in client.js:
-
Fullscreen Setup:
- Initialized the game with
window.innerWidth and window.innerHeight to make it fullscreen.
- Added an event listener to handle window resizing dynamically.
-
Player Integration:
- The
localPlayer is now integrated into the players object received from the server. The server assigns a unique id to each player, including the local one.
- Updated the
sendPlayerUpdate function to include the player's id, ensuring the server can identify which player sends the update.
-
Physics and Jumping:
- Added the
body() component to player sprites to enable physics.
- Set gravity globally using
k.setGravity(1600).
- Implemented horizontal movement with
velocity.x and jumping with velocity.y.
- Players can jump by pressing the spacebar, provided they are grounded (
isGrounded).
-
Migration Adjustments:
- Updated methods like
anchor("center") instead of origin("center").
- Ensured that
sprite.flipX and sprite.flipY are used as properties if needed in the future.
Updated server.js:
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 = [
// Define your map layouts here
[
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
],
[
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
]
];
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() {
let x, y;
do {
x = randomInt(0, currentMapLayout[0].length);
y = randomInt(0, currentMapLayout.length);
} while (currentMapLayout[y][x] === 1); // Ensure spawn is not on a solid tile
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;
console.log("Map layout changed.");
// Send the new map layout to all connected clients
broadcast({ players, map_layout: currentMapLayout });
}
}
// Broadcast utility
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,
velocity: { x: 0, y: 0 }, // Initialize velocity
isGrounded: false, // To manage jumping
color: generateColor()
};
// Send initial positions, map layout, and the assigned ID to the new client
ws.send(serialize({
players,
map_layout: currentMapLayout,
local_id: ws.id // Inform the client of its own ID
}));
// Broadcast to others about the new player
broadcast({ players, map_layout: currentMapLayout });
} else if (message.position && message.velocity) {
// Position and velocity update message
if (players[message.id]) {
players[message.id].position = message.position;
players[message.id].velocity = message.velocity;
// Simple ground check (you might want to implement a more robust collision detection)
// Assuming the bottom of the screen is the ground
if (players[message.id].position.y >= (currentMapLayout.length * tileSize) - tileSize) {
players[message.id].position.y = (currentMapLayout.length * tileSize) - tileSize;
players[message.id].velocity.y = 0;
players[message.id].isGrounded = true;
} else {
players[message.id].isGrounded = false;
}
// 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();
Explanation of Changes in server.js:
-
Player State Management:
- Velocity and Ground State: Each player now has a
velocity and isGrounded property to manage physics-based movement and jumping.
- Ground Check: Implemented a simple ground collision check to determine if the player is on the ground, allowing them to jump only when grounded.
-
Player Identification:
- Local ID Assignment: When a client connects, the server assigns a unique
id (ws.id) and sends it back to the client as local_id. The client uses this ID to manage its own state.
-
Position and Velocity Updates:
- The server now handles both
position and velocity data from clients, updating and broadcasting them to all connected clients.
-
Spawn Position Validation:
- Ensured that players do not spawn on solid tiles by checking the
mapLayout.
-
Map Layout Broadcasting:
- When the map layout changes, it's broadcasted to all clients to ensure synchronization.
Additional Recommendations:
-
Collision Detection:
- The current implementation assumes the ground is at the bottom of the map. For more complex maps, implement robust collision detection between players and tiles.
-
Smooth Movement:
- Instead of sending tile-sized position updates, consider implementing continuous movement with physics interpolation for smoother gameplay.
-
Optimizations:
- Implement throttling or debouncing for sending player updates to reduce network traffic.
- Consider using a game loop with fixed time steps for consistent physics updates.
-
Security:
- Validate all incoming data on the server to prevent malicious clients from sending invalid or harmful data.
-
Error Handling:
- Enhance error handling on both client and server to gracefully handle unexpected scenarios.
-
Scalability:
- For larger games, consider implementing rooms or zones to manage players efficiently.
Feel free to customize the values (like gravity, speed, jump strength) to better suit your game's mechanics. Let me know if you need further assistance!