import os import sys import json def write_file(base_dir: str, rel_path: str, content: str) -> None: full_path = os.path.join(base_dir, rel_path) os.makedirs(os.path.dirname(full_path), exist_ok=True) with open(full_path, "w", encoding="utf-8", newline="\n") as f: f.write(content.lstrip("\n")) def ensure_sample_maps(base_dir: str) -> None: maps_dir = os.path.join(base_dir, "maps") os.makedirs(maps_dir, exist_ok=True) defaults = { "koszalin.json": { "v": 2, "city": "koszalin", "offset": {"x": 0, "z": 0}, "roads": [ {"pts": [[-140, -140], [-60, -70], [20, 0], [110, 80], [210, 150]], "w": 9, "name": "", "type": "tertiary"}, {"pts": [[-180, 120], [-80, 60], [20, 0], [120, -55], [220, -110]], "w": 8, "name": "", "type": "residential"}, {"pts": [[20, 0], [25, 110], [30, 220]], "w": 7, "name": "", "type": "unclassified"}, {"pts": [[-90, -210], [-75, -70], [-60, 70], [-45, 200]], "w": 8, "name": "", "type": "tertiary"} ], "blds": [ {"pts": [[45, 20], [75, 20], [75, 45], [45, 45]], "h": 9.6}, {"pts": [[-40, -50], [-15, -50], [-15, -28], [-40, -28]], "h": 6.4}, {"pts": [[85, -80], [118, -80], [118, -50], [85, -50]], "h": 12.8}, {"pts": [[-120, 30], [-95, 30], [-95, 55], [-120, 55]], "h": 3.2} ], "areas": [ {"pts": [[-220, -220], [240, -220], [240, 240], [-220, 240]], "c": 4885050}, {"pts": [[5, -15], [35, -15], [35, 15], [5, 15]], "c": 2776463} ], "rivers": [ {"pts": [[-240, -190], [-120, -130], [0, -165], [140, -195], [240, -150]], "w": 10} ] }, "bialogard.json": { "v": 2, "city": "bialogard", "offset": {"x": 650, "z": -420}, "roads": [ {"pts": [[520, -520], [600, -460], [650, -420], [730, -370], [810, -320]], "w": 8, "name": "", "type": "tertiary"}, {"pts": [[650, -550], [650, -420], [650, -280]], "w": 7.5, "name": "", "type": "residential"}, {"pts": [[550, -340], [650, -420], [760, -490]], "w": 6.5, "name": "", "type": "service"} ], "blds": [ {"pts": [[670, -455], [705, -455], [705, -430], [670, -430]], "h": 6.4}, {"pts": [[585, -400], [615, -400], [615, -375], [585, -375]], "h": 9.6}, {"pts": [[710, -365], [740, -365], [740, -340], [710, -340]], "h": 3.2} ], "areas": [ {"pts": [[480, -600], [860, -600], [860, -240], [480, -240]], "c": 2377503} ], "rivers": [ {"pts": [[490, -260], [610, -330], [740, -290], [850, -360]], "w": 12} ] }, "nosowek.json": { "v": 2, "city": "nosowek", "offset": {"x": -520, "z": 480}, "roads": [ {"pts": [[-660, 420], [-580, 455], [-520, 480], [-430, 515], [-340, 550]], "w": 8, "name": "", "type": "tertiary"}, {"pts": [[-520, 360], [-520, 480], [-520, 610]], "w": 4.5, "name": "", "type": "service"}, {"pts": [[-610, 560], [-520, 480], [-420, 410]], "w": 4, "name": "", "type": "track"} ], "blds": [ {"pts": [[-500, 445], [-475, 445], [-475, 465], [-500, 465]], "h": 3.2}, {"pts": [[-565, 495], [-540, 495], [-540, 518], [-565, 518]], "h": 6.4} ], "areas": [ {"pts": [[-700, 320], [-300, 320], [-300, 660], [-700, 660]], "c": 2377503} ], "rivers": [ {"pts": [[-680, 620], [-540, 570], [-420, 615], [-310, 580]], "w": 9} ] } } for filename, data in defaults.items(): target = os.path.join(maps_dir, filename) if not os.path.exists(target): with open(target, "w", encoding="utf-8") as f: json.dump(data, f, indent=2) def generate_project(base_dir: str) -> None: ensure_sample_maps(base_dir) # 1. server/package.json write_file(base_dir, "server/package.json", """ { "name": "gta-grand-theft-koszalin-server", "version": "1.0.0", "private": true, "dependencies": { "ws": "^8.18.0" } } """) # 2. server/db.js write_file(base_dir, "server/db.js", """ const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const DB_FILE = path.join(__dirname, "database.json"); function defaultDb() { return { users: {} }; } function loadDb() { try { if (!fs.existsSync(DB_FILE)) { const init = defaultDb(); fs.writeFileSync(DB_FILE, JSON.stringify(init, null, 2), "utf8"); return init; } const raw = fs.readFileSync(DB_FILE, "utf8"); const parsed = JSON.parse(raw); if (!parsed.users || typeof parsed.users !== "object") { parsed.users = {}; } return parsed; } catch (err) { console.error("DB load error:", err); return defaultDb(); } } function saveDb(db) { try { fs.writeFileSync(DB_FILE, JSON.stringify(db, null, 2), "utf8"); } catch (err) { console.error("DB save error:", err); } } function hashPassword(password, salt = null) { const realSalt = salt || crypto.randomBytes(16).toString("hex"); const derived = crypto.scryptSync(password, realSalt, 64).toString("hex"); return `${realSalt}:${derived}`; } function verifyPassword(password, storedHash) { if (!storedHash || !storedHash.includes(":")) return false; const [salt, keyHex] = storedHash.split(":"); const keyBuf = Buffer.from(keyHex, "hex"); const derivedBuf = crypto.scryptSync(password, salt, 64); if (keyBuf.length !== derivedBuf.length) return false; return crypto.timingSafeEqual(keyBuf, derivedBuf); } function createDefaultPlayerState() { return { money: 1500, kills: 0, deaths: 0, hp: 100, pos: { x: 0, y: 0.5, z: 20, yaw: 0 }, skin: { shirt: "#2563eb", pants: "#1e293b", skinTone: "#e0ac8b" }, inventory: [ { id: "pistol", name: "Pistolet 9mm", type: "weapon", qty: 1, stackable: false }, { id: "assault_rifle", name: "Karabin Szturmowy", type: "weapon", qty: 1, stackable: false }, { id: "shotgun", name: "Strzelba Bojowa", type: "weapon", qty: 1, stackable: false }, { id: "grenade", name: "Granat Odlamkowy", type: "throwable", qty: 3, stackable: true }, { id: "rocket_launcher", name: "Rakietnica RPG", type: "weapon", qty: 1, stackable: false }, { id: "burger", name: "Burger Szefa (+5% HP)", type: "food", healPct: 5, qty: 3, stackable: true }, { id: "black_coolwave", name: "Black Coolwave (+15% SPD)", type: "drink", speedBoostPct: 15, durationMs: 150000, qty: 2, stackable: true } ], hotbar: ["pistol", "assault_rifle", "shotgun", "grenade", "rocket_launcher"], vehicleTuning: { model: "sedan", engineLevel: 1, turboLevel: 1, color: "#dc2626" }, settings: { graphicsQuality: "high", shadows: true, fov: 75, keybinds: { moveForward: "KeyW", moveBackward: "KeyS", moveLeft: "KeyA", moveRight: "KeyD", jump: "Space", roll: "KeyC", interact: "KeyE", inventory: "KeyI", map: "KeyM", debug: "F3", enterVehicle: "KeyF", reload: "KeyR" } }, // Przygotowane czyste miejsce pod przyszle rozszerzenia bez aktywnej logiki: futureHooks: { limitedClothes: [], weaponSkins: {} } }; } class GameDatabase { constructor() { this.data = loadDb(); } register(login, password) { const cleanLogin = String(login || "").trim(); if (cleanLogin.length < 3 || cleanLogin.length > 24) { return { ok: false, error: "Login musi miec 3-24 znaki." }; } if (typeof password !== "string" || password.length < 4) { return { ok: false, error: "Haslo musi miec minimum 4 znaki." }; } const key = cleanLogin.toLowerCase(); if (this.data.users[key]) { return { ok: false, error: "Taki login juz istnieje." }; } const state = createDefaultPlayerState(); this.data.users[key] = { login: cleanLogin, passwordHash: hashPassword(password), createdAt: Date.now(), state }; saveDb(this.data); return { ok: true, login: cleanLogin, state }; } login(login, password) { const cleanLogin = String(login || "").trim(); const key = cleanLogin.toLowerCase(); const user = this.data.users[key]; if (!user || !verifyPassword(String(password || ""), user.passwordHash)) { return { ok: false, error: "Niepoprawny login lub haslo." }; } if (!user.state.hotbar || user.state.hotbar.length !== 5) { user.state.hotbar = ["pistol", "assault_rifle", "shotgun", "grenade", "rocket_launcher"]; } return { ok: true, login: user.login, state: user.state }; } savePlayerState(login, partialOrFullState) { if (!login) return; const key = String(login).toLowerCase(); const user = this.data.users[key]; if (!user) return; user.state = { ...user.state, ...partialOrFullState, pos: partialOrFullState.pos ? { ...user.state.pos, ...partialOrFullState.pos } : user.state.pos, skin: partialOrFullState.skin ? { ...user.state.skin, ...partialOrFullState.skin } : user.state.skin, vehicleTuning: partialOrFullState.vehicleTuning ? { ...user.state.vehicleTuning, ...partialOrFullState.vehicleTuning } : user.state.vehicleTuning, settings: partialOrFullState.settings ? { ...user.state.settings, ...partialOrFullState.settings, keybinds: { ...user.state.settings.keybinds, ...(partialOrFullState.settings.keybinds || {}) } } : user.state.settings }; saveDb(this.data); } getLeaderboard() { const list = Object.values(this.data.users).map((u) => ({ login: u.login, kills: u.state.kills || 0, deaths: u.state.deaths || 0, money: u.state.money || 0 })); list.sort((a, b) => (b.kills - a.kills) || (b.money - a.money)); return list.slice(0, 20); } } module.exports = { GameDatabase, createDefaultPlayerState }; """) # 3. server/mapGraph.js write_file(base_dir, "server/mapGraph.js", """ const fs = require("fs"); const path = require("path"); function dist2D(a, b) { const dx = a[0] - b[0]; const dz = a[1] - b[1]; return Math.hypot(dx, dz); } class MapRoadGraph { constructor(mapsDir) { this.nodes = []; this.edges = []; this.zones = { weedKoszalin: { id: "weed_koszalin", name: "Rynek Koszalin - Marihuana", x: 15, z: 5, radius: 38, itemId: "marijuana", label: "Marihuana" }, cokeBialogard: { id: "coke_bialogard", name: "Dworzec Bialogard - Bialogardzki Koks", x: 650, z: -420, radius: 42, itemId: "bialogard_coke", label: "Bialogardzki Koks" } }; this.shops = [ { id: "shop_koszalin_1", name: "Sklep Spozywczy Koszalin", x: -45, z: 25, radius: 14 }, { id: "shop_bialogard_1", name: "Sklep Spozywczy Bialogard", x: 675, z: -395, radius: 14 }, { id: "shop_nosowek_1", name: "Sklepik Nosowek", x: -500, z: 495, radius: 14 } ]; this.tunings = [ { id: "tuning_koszalin", name: "Tuning Koszalin", x: 95, z: 55, radius: 16 }, { id: "tuning_bialogard", name: "Tuning Bialogard", x: 625, z: -445, radius: 16 } ]; this.dealers = [ { id: "dealer_koszalin", name: "Pasazer / Odbiorca Koszalin", x: 32, z: -18, radius: 12 }, { id: "dealer_bialogard", name: "Pasazer / Odbiorca Bialogard", x: 635, z: -395, radius: 12 } ]; this.loadMaps(mapsDir); } addNode(x, z) { for (let i = 0; i < this.nodes.length; i++) { if (dist2D([this.nodes[i].x, this.nodes[i].z], [x, z]) < 4.0) { return i; } } const id = this.nodes.length; this.nodes.push({ id, x, z, neighbors: [] }); return id; } addEdge(aId, bId, length) { if (aId === bId) return; const a = this.nodes[aId]; const b = this.nodes[bId]; if (!a.neighbors.some((n) => n.to === bId)) { a.neighbors.push({ to: bId, cost: length }); } if (!b.neighbors.some((n) => n.to === aId)) { b.neighbors.push({ to: aId, cost: length }); } this.edges.push({ from: aId, to: bId, length }); } loadMaps(mapsDir) { if (!fs.existsSync(maps_dir_safe(mapsDir))) return; const files = fs.readdirSync(mapsDir).filter((f) => f.endsWith(".json")); for (const file of files) { try { const raw = fs.readFileSync(path.join(mapsDir, file), "utf8"); const data = JSON.parse(raw); const roads = Array.isArray(data.roads) ? data.roads : []; for (const road of roads) { const pts = road.pts || []; let prevNode = null; for (let i = 0; i < pts.length; i++) { const p = pts[i]; if (!Array.isArray(p) || p.length < 2) continue; const nodeId = this.addNode(Number(p[0]), Number(p[1])); if (prevNode !== null) { const d = dist2D([this.nodes[prevNode].x, this.nodes[prevNode].z], [this.nodes[nodeId].x, this.nodes[nodeId].z]); if (d > 0.1) { this.addEdge(prevNode, nodeId, d); } } prevNode = nodeId; } } } catch (err) { console.error("Map graph parse error in", file, err.message); } } } getRandomNodeId() { if (this.nodes.length === 0) return -1; return Math.floor(Math.random() * this.nodes.length); } findPath(startId, goalId) { if (startId < 0 || goalId < 0 || startId >= this.nodes.length || goalId >= this.nodes.length) { return []; } if (startId === goalId) return [this.nodes[goalId]]; const dist = new Array(this.nodes.length).fill(Infinity); const prev = new Array(this.nodes.length).fill(-1); const visited = new Array(this.nodes.length).fill(false); dist[startId] = 0; for (let step = 0; step < this.nodes.length; step++) { let u = -1; let best = Infinity; for (let i = 0; i < this.nodes.length; i++) { if (!visited[i] && dist[i] < best) { best = dist[i]; u = i; } } if (u === -1 || u === goalId) break; visited[u] = true; for (const nb of this.nodes[u].neighbors) { if (visited[nb.to]) continue; const alt = dist[u] + nb.cost; if (alt < dist[nb.to]) { dist[nb.to] = alt; prev[nb.to] = u; } } } const pathNodes = []; let curr = goalId; while (curr !== -1) { pathNodes.push({ x: this.nodes[curr].x, z: this.nodes[curr].z }); if (curr === startId) break; curr = prev[curr]; } pathNodes.reverse(); return pathNodes; } } function maps_dir_safe(p) { return p || ""; } module.exports = { MapRoadGraph }; """) # 4. server/server.js write_file(base_dir, "server/server.js", """ const http = require("http"); const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const WebSocket = require("ws"); const { GameDatabase } = require("./db"); const { MapRoadGraph } = require("./mapGraph"); const PORT = process.env.PORT || 3000; const ROOT_DIR = path.resolve(__dirname, ".."); const CLIENT_DIR = path.join(ROOT_DIR, "client"); const MAPS_DIR = path.join(ROOT_DIR, "maps"); const MIME_TYPES = { ".html": "text/html; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png" }; const db = new GameDatabase(); const roadGraph = new MapRoadGraph(MAPS_DIR); const SHOP_CATALOG = { water_bottle: { id: "water_bottle", name: "Woda Mineralna (+5% HP)", type: "food", healPct: 5, price: 45, stackable: true }, burger: { id: "burger", name: "Burger Szefa (+5% HP)", type: "food", healPct: 5, price: 65, stackable: true }, kebab: { id: "kebab", name: "Kebab Koszalinski (+10% HP)", type: "food", healPct: 10, price: 120, stackable: true }, pizza_slice: { id: "pizza_slice", name: "Pizza 00 (+10% HP)", type: "food", healPct: 10, price: 135, stackable: true }, mega_zestaw: { id: "mega_zestaw", name: "Zestaw Mocarza (+15% HP)", type: "food", healPct: 15, price: 210, stackable: true }, black_coolwave: { id: "black_coolwave", name: "Black Coolwave (+15% SPD)", type: "drink", speedBoostPct: 15, durationMs: 150000, price: 160, stackable: true } }; const WEAPON_DAMAGE = { pistol: 22, assault_rifle: 18, shotgun: 14, rocket_launcher: 95, grenade: 85 }; const NPC_PRICES = { marijuana: 95, bialogard_coke: 180 }; const clients = new Map(); // socketId -> clientObj const droppedItems = []; // { id, item, x, y, z, expiresAt } const projectiles = []; // { id, ownerId, kind, x, y, z, vx, vy, vz, createdAt, explodeAt } const trades = new Map(); // tradeId -> { id, aId, bId, aOffer: [], bOffer: [], aReady: false, bReady: false } const npcStock = { marijuana: 45, bialogard_coke: 30 }; const npcVehicles = []; function initNpcVehicles() { if (roadGraph.nodes.length < 2) return; for (let i = 0; i < 6; i++) { const startId = roadGraph.getRandomNodeId(); const goalId = roadGraph.getRandomNodeId(); const waypoints = roadGraph.findPath(startId, goalId); const startPos = waypoints[0] || { x: 0, z: 0 }; npcVehicles.push({ id: "npc_car_" + i, model: i % 2 === 0 ? "sedan" : "suv_offroad", color: ["#94a3b8", "#eab308", "#06b6d4", "#a855f7"][i % 4], x: startPos.x, y: 0.4, z: startPos.z, yaw: 0, speed: 14, waypoints, wpIndex: 1 }); } } initNpcVehicles(); function broadcast(payload, excludeId = null) { const msg = JSON.stringify(payload); for (const [id, c] of clients.entries()) { if (id === excludeId) continue; if (c.ws.readyState === WebSocket.OPEN) { c.ws.send(msg); } } } function sendTo(clientObj, payload) { if (clientObj && clientObj.ws.readyState === WebSocket.OPEN) { clientObj.ws.send(JSON.stringify(payload)); } } function addItemToInventory(state, newItem) { if (newItem.stackable) { const existing = state.inventory.find((it) => it.id === newItem.id); if (existing) { existing.qty += newItem.qty || 1; return; } } state.inventory.push({ ...newItem, qty: newItem.qty || 1 }); } function removeItemQty(state, itemId, qty = 1) { const idx = state.inventory.findIndex((it) => it.id === itemId); if (idx === -1) return false; const item = state.inventory[idx]; if (item.qty < qty) return false; item.qty -= qty; if (item.qty <= 0) { state.inventory.splice(idx, 1); } return true; } function spawnDroppedItem(item, x, y, z) { const now = Date.now(); droppedItems.push({ id: "drop_" + crypto.randomUUID().slice(0, 8), item: { ...item, qty: item.qty || 1 }, x, y, z, createdAt: now, expiresAt: now + 180000 // 3 minuty }); } function scatterLootOnDeath(victimClient) { const st = victimClient.state; const baseX = st.pos.x; const baseY = Math.max(0.5, st.pos.y); const baseZ = st.pos.z; const toDrop = [...st.inventory]; st.inventory = [ { id: "pistol", name: "Pistolet 9mm", type: "weapon", qty: 1, stackable: false } ]; toDrop.forEach((it, idx) => { const angle = (idx / Math.max(1, toDrop.length)) * Math.PI * 2; const radius = 1.8 + (idx % 3) * 1.1; const dx = baseX + Math.cos(angle) * radius; const dz = baseZ + Math.sin(angle) * radius; spawnDroppedItem(it, dx, baseY + 0.4, dz); }); } function applyExplosion(x, y, z, radius, maxDamage, attackerClient) { broadcast({ type: "explosion", x, y, z, radius }); for (const [, target] of clients.entries()) { if (!target.authenticated || target.state.hp <= 0) continue; const dx = target.state.pos.x - x; const dy = target.state.pos.y - y; const dz = target.state.pos.z - z; const d = Math.hypot(dx, dy, dz); if (d <= radius) { const falloff = Math.max(0.15, 1 - d / radius); const dmg = Math.round(maxDamage * falloff); damagePlayer(target, dmg, attackerClient); } } } function damagePlayer(targetClient, amount, attackerClient = null) { if (targetClient.state.hp <= 0) return; targetClient.state.hp = Math.max(0, targetClient.state.hp - amount); if (targetClient.state.hp <= 0) { targetClient.state.deaths = (targetClient.state.deaths || 0) + 1; if (attackerClient && attackerClient.socketId !== targetClient.socketId) { attackerClient.state.kills = (attackerClient.state.kills || 0) + 1; attackerClient.state.money = (attackerClient.state.money || 0) + 250; db.savePlayerState(attackerClient.login, attackerClient.state); sendTo(attackerClient, { type: "notification", text: `Eliminacja gracza ${targetClient.login}! +250$` }); } scatterLootOnDeath(targetClient); db.savePlayerState(targetClient.login, targetClient.state); sendTo(targetClient, { type: "player_died", respawnInMs: 4000 }); setTimeout(() => { if (!clients.has(targetClient.socketId)) return; targetClient.state.hp = 100; targetClient.state.pos = { x: 0, y: 0.5, z: 20, yaw: 0 }; db.savePlayerState(targetClient.login, targetClient.state); sendTo(targetClient, { type: "player_respawned", state: targetClient.state }); }, 4000); } } const server = http.createServer((req, res) => { const urlPath = (req.url || "/").split("?")[0]; if (urlPath === "/api/leaderboard") { res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" }); res.end(JSON.stringify(db.getLeaderboard())); return; } if (urlPath.startsWith("/maps/")) { const safeName = path.basename(urlPath); const mapFile = path.join(MAPS_DIR, safeName); if (fs.existsSync(mapFile)) { res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" }); fs.createReadStream(mapFile).pipe(res); return; } } let fileRel = urlPath === "/" ? "index.html" : urlPath.replace(/^\\/+/, ""); let filePath = path.join(CLIENT_DIR, fileRel); if (!filePath.startsWith(CLIENT_DIR) || !fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { filePath = path.join(CLIENT_DIR, "index.html"); } const ext = path.extname(filePath).toLowerCase(); res.writeHead(200, { "Content-Type": MIME_TYPES[ext] || "application/octet-stream" }); fs.createReadStream(filePath).pipe(res); }); const wss = new WebSocket.Server({ server }); wss.on("connection", (ws) => { const socketId = "sock_" + crypto.randomUUID().slice(0, 8); const clientObj = { socketId, ws, authenticated: false, login: null, state: null, speedBoostUntil: 0, speedBoostPct: 0, inVehicle: false, pingMs: 12 }; clients.set(socketId, clientObj); sendTo(clientObj, { type: "welcome", socketId, zones: roadGraph.zones, shops: roadGraph.shops, tunings: roadGraph.tunings, dealers: roadGraph.dealers, shopCatalog: SHOP_CATALOG }); ws.on("message", (rawMsg) => { let data; try { data = JSON.parse(rawMsg.toString("utf8")); } catch { return; } if (data.type === "ping") { sendTo(clientObj, { type: "pong", clientTime: data.clientTime, serverTime: Date.now() }); return; } if (data.type === "register") { const res = db.register(data.login, data.password); if (!res.ok) { sendTo(clientObj, { type: "auth_error", error: res.error }); return; } clientObj.authenticated = true; clientObj.login = res.login; clientObj.state = res.state; sendTo(clientObj, { type: "auth_ok", socketId, login: res.login, state: res.state, leaderboard: db.getLeaderboard() }); return; } if (data.type === "login") { const res = db.login(data.login, data.password); if (!res.ok) { sendTo(clientObj, { type: "auth_error", error: res.error }); return; } clientObj.authenticated = true; clientObj.login = res.login; clientObj.state = res.state; sendTo(clientObj, { type: "auth_ok", socketId, login: res.login, state: res.state, leaderboard: db.getLeaderboard() }); return; } if (!clientObj.authenticated || !clientObj.state) return; if (data.type === "move") { if (clientObj.state.hp <= 0) return; clientObj.state.pos = { x: Number(data.x) || 0, y: Number(data.y) || 0.5, z: Number(data.z) || 0, yaw: Number(data.yaw) || 0 }; clientObj.inVehicle = Boolean(data.inVehicle); if (typeof data.pingMs === "number") { clientObj.pingMs = Math.max(1, Math.min(999, Math.round(data.pingMs))); } return; } if (data.type === "update_profile") { if (data.skin) clientObj.state.skin = { ...clientObj.state.skin, ...data.skin }; if (data.settings) { clientObj.state.settings = { ...clientObj.state.settings, ...data.settings, keybinds: { ...clientObj.state.settings.keybinds, ...(data.settings.keybinds || {}) } }; } if (Array.isArray(data.hotbar) && data.hotbar.length === 5) { clientObj.state.hotbar = data.hotbar; } db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); return; } if (data.type === "use_item") { const itemId = data.itemId; const invItem = clientObj.state.inventory.find((i) => i.id === itemId && i.qty > 0); if (!invItem) return; if (invItem.type === "food") { const heal = Math.round((invItem.healPct || 5)); clientObj.state.hp = Math.min(100, clientObj.state.hp + heal); removeItemQty(clientObj.state, itemId, 1); sendTo(clientObj, { type: "notification", text: `Zjedzono ${invItem.name} (+${heal}% HP)` }); } else if (invItem.type === "drink" && invItem.id === "black_coolwave") { const now = Date.now(); clientObj.speedBoostPct = invItem.speedBoostPct || 15; clientObj.speedBoostUntil = now + (invItem.durationMs || 150000); removeItemQty(clientObj.state, itemId, 1); sendTo(clientObj, { type: "speed_boost", boostPct: clientObj.speedBoostPct, durationMs: invItem.durationMs || 150000 }); sendTo(clientObj, { type: "notification", text: "Black Coolwave aktywny: +15% predkosci przez 2.5 min!" }); } db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); return; } if (data.type === "drop_item") { const itemId = data.itemId; const qty = Math.max(1, Math.min(Number(data.qty) || 1, 50)); const invItem = clientObj.state.inventory.find((i) => i.id === itemId); if (!invItem || invItem.qty < qty) return; const droppedCopy = { ...invItem, qty }; removeItemQty(clientObj.state, itemId, qty); spawnDroppedItem( droppedCopy, clientObj.state.pos.x + Math.sin(clientObj.state.pos.yaw) * 1.5, Math.max(0.5, clientObj.state.pos.y + 0.3), clientObj.state.pos.z + Math.cos(clientObj.state.pos.yaw) * 1.5 ); db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); return; } if (data.type === "pickup_item") { const idx = droppedItems.findIndex((d) => d.id === data.dropId); if (idx === -1) return; const drop = droppedItems[idx]; const dist = Math.hypot(clientObj.state.pos.x - drop.x, clientObj.state.pos.z - drop.z); if (dist > 6.5) return; droppedItems.splice(idx, 1); addItemToInventory(clientObj.state, drop.item); db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); return; } if (data.type === "harvest_drug") { const zone = Object.values(roadGraph.zones).find((z) => z.id === data.zoneId); if (!zone) return; const dist = Math.hypot(clientObj.state.pos.x - zone.x, clientObj.state.pos.z - zone.z); if (dist > zone.radius + 6) { sendTo(clientObj, { type: "notification", text: "Jestes za daleko od strefy zbioru!" }); return; } const amount = Math.floor(Math.random() * 3) + 1; addItemToInventory(clientObj.state, { id: zone.itemId, name: zone.label, type: "drug", qty: amount, stackable: true }); db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); sendTo(clientObj, { type: "notification", text: `Zebrano ${amount}x ${zone.label}!` }); return; } if (data.type === "sell_drug_npc") { const drugId = data.drugId === "bialogard_coke" ? "bialogard_coke" : "marijuana"; const unitPrice = NPC_PRICES[drugId]; const invItem = clientObj.state.inventory.find((i) => i.id === drugId && i.qty > 0); if (!invItem) { sendTo(clientObj, { type: "notification", text: "Nie masz tego towaru w EQ." }); return; } // 0.1% szansy na wykupienie calego zapasu NPC od gracza const buyoutChance = Math.random() < 0.001; let soldQty = 0; if (buyoutChance) { soldQty = invItem.qty; } else { const wanted = Math.floor(Math.random() * 5) + 1; // losowo 1-5 sztuk soldQty = Math.min(invItem.qty, wanted); } removeItemQty(clientObj.state, drugId, soldQty); const earned = soldQty * unitPrice; clientObj.state.money += earned; db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); sendTo(clientObj, { type: "notification", text: buyoutChance ? `RZADKI WYKUP CALOSCI (0.1%)! Sprzedano ${soldQty} szt. za ${earned}$!` : `NPC kupil ${soldQty} szt. za ${earned}$ (${unitPrice}$/szt.).` }); return; } if (data.type === "buy_shop_item") { const catalogItem = SHOP_CATALOG[data.itemId]; if (!catalogItem) return; if (clientObj.state.money < catalogItem.price) { sendTo(clientObj, { type: "notification", text: "Za malo gotowki!" }); return; } clientObj.state.money -= catalogItem.price; addItemToInventory(clientObj.state, { id: catalogItem.id, name: catalogItem.name, type: catalogItem.type, healPct: catalogItem.healPct, speedBoostPct: catalogItem.speedBoostPct, durationMs: catalogItem.durationMs, qty: 1, stackable: true }); db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); sendTo(clientObj, { type: "notification", text: `Kupiono: ${catalogItem.name} (-${catalogItem.price}$)` }); return; } if (data.type === "tuning_upgrade") { const tuning = clientObj.state.vehicleTuning || { model: "sedan", engineLevel: 1, turboLevel: 1, color: "#dc2626" }; let cost = 0; if (data.upgradeType === "engine") { const nextLvl = (tuning.engineLevel || 1) + 1; if (nextLvl > 5) return; cost = nextLvl * 400; if (clientObj.state.money < cost) return sendTo(clientObj, { type: "notification", text: "Brak srodkow na silnik!" }); clientObj.state.money -= cost; tuning.engineLevel = nextLvl; } else if (data.upgradeType === "turbo") { const nextLvl = (tuning.turboLevel || 1) + 1; if (nextLvl > 5) return; cost = nextLvl * 450; if (clientObj.state.money < cost) return sendTo(clientObj, { type: "notification", text: "Brak srodkow na turbo!" }); clientObj.state.money -= cost; tuning.turboLevel = nextLvl; } else if (data.upgradeType === "color" && typeof data.color === "string") { cost = 200; if (clientObj.state.money < cost) return sendTo(clientObj.state, { type: "notification", text: "Brak srodkow na lakier!" }); clientObj.state.money -= cost; tuning.color = data.color; } else if (data.upgradeType === "model" && typeof data.model === "string") { cost = 600; if (clientObj.state.money < cost) return sendTo(clientObj.state, { type: "notification", text: "Brak srodkow na zmiane auta!" }); clientObj.state.money -= cost; tuning.model = data.model; } clientObj.state.vehicleTuning = tuning; db.savePlayerState(clientObj.login, clientObj.state); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); sendTo(clientObj, { type: "notification", text: `Zastosowano ulepszenie tuningu (${cost}$).` }); return; } if (data.type === "shoot") { if (clientObj.state.hp <= 0) return; const weaponId = data.weaponId || "pistol"; const origin = { x: Number(data.ox) || clientObj.state.pos.x, y: Number(data.oy) || clientObj.state.pos.y + 1.4, z: Number(data.oz) || clientObj.state.pos.z }; const dir = { x: Number(data.dx) || 0, y: Number(data.dy) || 0, z: Number(data.dz) || 1 }; const len = Math.hypot(dir.x, dir.y, dir.z) || 1; dir.x /= len; dir.y /= len; dir.z /= len; if (weaponId === "grenade") { const hasGrenade = clientObj.state.inventory.some((i) => i.id === "grenade" && i.qty > 0); if (!hasGrenade) return; removeItemQty(clientObj.state, "grenade", 1); sendTo(clientObj, { type: "state_sync", state: clientObj.state }); const now = Date.now(); projectiles.push({ id: "proj_" + crypto.randomUUID().slice(0, 8), ownerId: socketId, kind: "grenade", x: origin.x + dir.x * 1.2, y: origin.y + 0.3, z: origin.z + dir.z * 1.2, vx: dir.x * 22, vy: dir.y * 22 + 6.5, vz: dir.z * 22, createdAt: now, explodeAt: now + 2200 }); return; } if (weaponId === "rocket_launcher") { const hasRocket = clientObj.state.inventory.some((i) => i.id === "rocket_launcher" && i.qty > 0); if (!hasRocket) return; const now = Date.now(); projectiles.push({ id: "proj_" + crypto.randomUUID().slice(0, 8), ownerId: socketId, kind: "rocket", x: origin.x + dir.x * 1.5, y: origin.y, z: origin.z + dir.z * 1.5, vx: dir.x * 38, vy: dir.y * 38, vz: dir.z * 38, createdAt: now, explodeAt: now + 3500 }); return; } // Bron palna (pistol / assault_rifle / shotgun) - synchronizacja smug + autorytatywne trafienie const pellets = weaponId === "shotgun" ? 6 : 1; const baseDmg = WEAPON_DAMAGE[weaponId] || 18; const tracers = []; for (let p = 0; p < pellets; p++) { const spread = weaponId === "shotgun" ? 0.08 : 0.012; const sx = dir.x + (Math.random() - 0.5) * spread; const sy = dir.y + (Math.random() - 0.5) * spread; const sz = dir.z + (Math.random() - 0.5) * spread; const sLen = Math.hypot(sx, sy, sz) || 1; const rdx = sx / sLen; const rdy = sy / sLen; const rdz = sz / sLen; const maxRange = 140; let hitDist = maxRange; let hitPlayer = null; for (const [tid, tClient] of clients.entries()) { if (tid === socketId || !tClient.authenticated || tClient.state.hp <= 0) continue; const toTargetX = tClient.state.pos.x - origin.x; const toTargetY = tClient.state.pos.y + 1.0 - origin.y; const toTargetZ = tClient.state.pos.z - origin.z; const proj = toTargetX * rdx + toTargetY * rdy + toTargetZ * rdz; if (proj < 0 || proj > hitDist) continue; const closestX = origin.x + rdx * proj; const closestY = origin.y + rdy * proj; const closestZ = origin.z + rdz * proj; const perpDist = Math.hypot( tClient.state.pos.x - closestX, tClient.state.pos.y + 1.0 - closestY, tClient.state.pos.z - closestZ ); if (perpDist <= 1.15) { hitDist = proj; hitPlayer = tClient; } } const end = { x: origin.x + rdx * hitDist, y: Math.max(0.1, origin.y + rdy * hitDist), z: origin.z + rdz * hitDist }; tracers.push({ start: origin, end }); if (hitPlayer) { damagePlayer(hitPlayer, baseDmg, clientObj); } } broadcast({ type: "tracers", shooterId: socketId, weaponId, tracers }); return; } // System Trade pomiedzy graczami if (data.type === "trade_request") { const target = clients.get(data.targetSocketId); if (!target || !target.authenticated || target.socketId === socketId) return; const tradeId = "trade_" + crypto.randomUUID().slice(0, 8); trades.set(tradeId, { id: tradeId, aId: socketId, bId: target.socketId, aOffer: [], bOffer: [], aReady: false, bReady: false }); sendTo(clientObj, { type: "trade_started", tradeId, partnerId: target.socketId, partnerLogin: target.login }); sendTo(target, { type: "trade_started", tradeId, partnerId: socketId, partnerLogin: clientObj.login }); return; } if (data.type === "trade_update") { const tr = trades.get(data.tradeId); if (!tr) return; const offer = Array.isArray(data.offer) ? data.offer : []; if (tr.aId === socketId) { tr.aOffer = offer; tr.aReady = false; } else if (tr.bId === socketId) { tr.bOffer = offer; tr.bReady = false; } const pA = clients.get(tr.aId); const pB = clients.get(tr.bId); sendTo(pA, { type: "trade_state", trade: tr }); sendTo(pB, { type: "trade_state", trade: tr }); return; } if (data.type === "trade_confirm") { const tr = trades.get(data.tradeId); if (!tr) return; if (tr.aId === socketId) tr.aReady = true; if (tr.bId === socketId) tr.bReady = true; const pA = clients.get(tr.aId); const pB = clients.get(tr.bId); sendTo(pA, { type: "trade_state", trade: tr }); sendTo(pB, { type: "trade_state", trade: tr }); if (tr.aReady && tr.bReady && pA && pB) { // Realizacja wymiany for (const item of tr.aOffer) { if (removeItemQty(pA.state, item.id, item.qty || 1)) { addItemToInventory(pB.state, item); } } for (const item of tr.bOffer) { if (removeItemQty(pB.state, item.id, item.qty || 1)) { addItemToInventory(pA.state, item); } } db.savePlayerState(pA.login, pA.state); db.savePlayerState(pB.login, pB.state); trades.delete(tr.id); sendTo(pA, { type: "trade_completed", state: pA.state }); sendTo(pB, { type: "trade_completed", state: pB.state }); } return; } if (data.type === "trade_cancel") { const tr = trades.get(data.tradeId); if (!tr) return; trades.delete(tr.id); const pA = clients.get(tr.aId); const pB = clients.get(tr.bId); if (pA) sendTo(pA, { type: "trade_cancelled" }); if (pB) sendTo(pB, { type: "trade_cancelled" }); } }); ws.on("close", () => { if (clientObj.authenticated && clientObj.login && clientObj.state) { db.savePlayerState(clientObj.login, clientObj.state); } clients.delete(socketId); }); }); // Petla symulacji serwera (TPS) const TICK_RATE = 20; const TICK_MS = 1000 / TICK_RATE; let lastTickTime = Date.now(); let currentTps = TICK_RATE; setInterval(() => { const now = Date.now(); const dt = Math.min(0.1, (now - lastTickTime) / 1000); if (now > lastTickTime) { currentTps = Math.min(60, Math.round(1000 / (now - lastTickTime))); } lastTickTime = now; // 1. Usuwanie wyrzuconych / posmiertnych przedmiotow po 3 minutach (180000 ms) for (let i = droppedItems.length - 1; i >= 0; i--) { if (droppedItems[i].expiresAt <= now) { droppedItems.splice(i, 1); } } // 2. Fizyka i lot granatow oraz rakiet for (let i = projectiles.length - 1; i >= 0; i--) { const pr = projectiles[i]; pr.x += pr.vx * dt; pr.y += pr.vy * dt; pr.z += pr.vz * dt; if (pr.kind === "grenade") { pr.vy -= 18 * dt; // grawitacja if (pr.y <= 0.15) { pr.y = 0.15; pr.vy = Math.abs(pr.vy) * 0.45; pr.vx *= 0.72; pr.vz *= 0.72; } if (now >= pr.explodeAt) { const owner = clients.get(pr.ownerId) || null; applyExplosion(pr.x, pr.y, pr.z, 11, WEAPON_DAMAGE.grenade, owner); projectiles.splice(i, 1); } } else if (pr.kind === "rocket") { const owner = clients.get(pr.ownerId) || null; let hitSomething = pr.y <= 0.15 || now >= pr.explodeAt; if (!hitSomething) { for (const [cid, c] of clients.entries()) { if (cid === pr.ownerId || !c.authenticated || c.state.hp <= 0) continue; const d = Math.hypot(c.state.pos.x - pr.x, c.state.pos.y + 1.0 - pr.y, c.state.pos.z - pr.z); if (d < 2.2) { hitSomething = true; break; } } } if (hitSomething) { applyExplosion(pr.x, Math.max(0.2, pr.y), pr.z, 14, WEAPON_DAMAGE.rocket_launcher, owner); projectiles.splice(i, 1); } } } // 3. Ruch pojazdow NPC po grafie drog z map for (const car of npcVehicles) { if (!car.waypoints || car.waypoints.length === 0) continue; const targetWp = car.waypoints[car.wpIndex]; if (!targetWp) { const startId = roadGraph.getRandomNodeId(); const goalId = roadGraph.getRandomNodeId(); car.waypoints = roadGraph.findPath(startId, goalId); car.wpIndex = 1; continue; } const dx = targetWp.x - car.x; const dz = targetWp.z - car.z; const dist = Math.hypot(dx, dz); if (dist < 3.5) { car.wpIndex++; } else { car.yaw = Math.atan2(dx, dz); const step = Math.min(dist, car.speed * dt); car.x += (dx / dist) * step; car.z += (dz / dist) * step; } } // 4. Rozsylanie stanu swiata do klientow const playersSnapshot = []; for (const [sid, c] of clients.entries()) { if (!c.authenticated || !c.state) continue; playersSnapshot.push({ socketId: sid, login: c.login, hp: c.state.hp, pos: c.state.pos, skin: c.state.skin, vehicleTuning: c.state.vehicleTuning, inVehicle: c.inVehicle, pingMs: c.pingMs }); } const activeProjectiles = projectiles.map((p) => ({ id: p.id, kind: p.kind, x: p.x, y: p.y, z: p.z })); const worldMsg = JSON.stringify({ type: "world_tick", tps: currentTps, players: playersSnapshot, npcVehicles, droppedItems, projectiles: activeProjectiles, npcStock }); for (const [, c] of clients.entries()) { if (c.ws.readyState === WebSocket.OPEN) { c.ws.send(worldMsg); } } }, TICK_MS); server.listen(PORT, () => { console.log(`GTA: Grand Theft Koszalin server running on http://localhost:${PORT}`); }); """) # 5. client/index.html write_file(base_dir, "client/index.html", """ GTA: Grand Theft Koszalin - 3D PvP Multiplayer """) # 6. client/css/style.css write_file(base_dir, "client/css/style.css", """ * { box-sizing: border-box; margin: 0; padding: 0; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } body, html { width: 100%; height: 100%; overflow: hidden; background: #0f172a; color: #f8fafc; } #gameCanvas { display: block; width: 100vw; height: 100vh; } .hidden { display: none !important; } .modal-backdrop, .overlay-panel { position: fixed; inset: 0; background: rgba(2, 6, 23, 0.78); display: flex; align-items: center; justify-content: center; z-index: 30; } .modal-box, .panel-card { width: 420px; max-width: 94vw; max-height: 90vh; overflow-y: auto; background: #1e293b; border: 1px solid #334155; border-radius: 10px; padding: 22px; box-shadow: 0 20px 50px rgba(0, 0, 0, 0.6); } .menu-wide { width: 740px; } h1, h2, h3 { margin-bottom: 10px; } .subtitle { color: #94a3b8; font-size: 13px; margin-bottom: 16px; } .tabs, .menu-nav { display: flex; gap: 8px; margin-bottom: 16px; } .tab-btn, .menu-tab, .small-btn, .slot-pick { background: #334155; color: #f8fafc; border: none; padding: 8px 14px; border-radius: 6px; cursor: pointer; font-weight: 600; } .tab-btn.active, .menu-tab.active, .slot-pick.active { background: #2563eb; } .form-group { margin-bottom: 12px; } .form-group label { display: block; font-size: 13px; margin-bottom: 4px; color: #cbd5e1; } .form-group input, select { width: 100%; padding: 9px 11px; border-radius: 6px; border: 1px solid #475569; background: #0f172a; color: #f8fafc; } .primary-btn { width: 100%; padding: 10px 14px; border: none; border-radius: 6px; background: #16a34a; color: #fff; font-weight: 700; cursor: pointer; margin-top: 8px; } .primary-btn:hover { background: #15803d; } .error-text { color: #f87171; margin-top: 10px; font-size: 13px; } #hud { position: fixed; inset: 0; pointer-events: none; z-index: 10; } #topBar { position: absolute; top: 14px; left: 14px; display: flex; gap: 10px; align-items: center; background: rgba(15, 23, 42, 0.8); padding: 8px 14px; border-radius: 8px; border: 1px solid #334155; } .money-badge { color: #4ade80; font-weight: 700; } .hp-badge { color: #f87171; font-weight: 700; } .boost-badge { color: #38bdf8; font-weight: 700; } #crosshair { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 22px; color: rgba(255, 255, 255, 0.85); } #interactPrompt { position: absolute; bottom: 115px; left: 50%; transform: translateX(-50%); background: rgba(15, 23, 42, 0.9); border: 1px solid #38bdf8; padding: 8px 16px; border-radius: 8px; font-weight: 600; } #notificationBox { position: absolute; top: 64px; left: 14px; background: rgba(22, 163, 74, 0.9); color: #fff; padding: 8px 14px; border-radius: 8px; font-size: 13px; font-weight: 600; opacity: 0; transition: opacity 0.25s; } #notificationBox.show { opacity: 1; } #debugOverlay { position: absolute; top: 14px; right: 220px; background: rgba(2, 6, 23, 0.85); border: 1px solid #f59e0b; color: #fde68a; padding: 10px 12px; border-radius: 8px; font-family: monospace; font-size: 12px; line-height: 1.5; } #minimapCanvas { position: absolute; top: 14px; right: 14px; width: 190px; height: 190px; border-radius: 10px; border: 2px solid #475569; background: #0f172a; } #hotbar { position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%); display: flex; gap: 8px; pointer-events: auto; } .hotbar-slot { width: 68px; height: 68px; background: rgba(15, 23, 42, 0.85); border: 2px solid #475569; border-radius: 8px; display: flex; flex-direction: column; align-items: center; justify-content: center; position: relative; font-size: 11px; text-align: center; padding: 3px; } .hotbar-slot.active { border-color: #38bdf8; box-shadow: 0 0 12px rgba(56, 189, 248, 0.5); } .slot-num { position: absolute; top: 3px; left: 6px; font-size: 11px; font-weight: 700; color: #94a3b8; } .eq-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(135px, 1fr)); gap: 10px; margin-top: 10px; } .eq-card { background: #0f172a; border: 1px solid #334155; border-radius: 8px; padding: 10px; display: flex; flex-direction: column; gap: 6px; font-size: 12px; } .eq-card img { width: 36px; height: 36px; margin: 0 auto; } .eq-actions { display: flex; gap: 4px; flex-wrap: wrap; } .eq-actions button { flex: 1; padding: 4px 6px; font-size: 11px; border: none; border-radius: 4px; cursor: pointer; background: #334155; color: #fff; } .panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; } table { width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 13px; } th, td { border-bottom: 1px solid #334155; padding: 6px 8px; text-align: left; } .skin-row, .settings-row, .hotbar-assign { display: flex; gap: 14px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; } .keybinds-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; margin-bottom: 12px; } .shop-item-row { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px 10px; border-radius: 6px; margin-bottom: 8px; font-size: 13px; } #fullMapOverlay { position: fixed; inset: 0; background: rgba(2, 6, 23, 0.92); z-index: 40; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; } .fullmap-header { width: 1100px; max-width: 95vw; display: flex; justify-content: space-between; align-items: center; font-weight: 700; } #fullMapCanvas { max-width: 95vw; max-height: 82vh; border: 2px solid #475569; border-radius: 10px; background: #0f172a; } """) # 7. client/js/config.js write_file(base_dir, "client/js/config.js", """ window.GameConfig = { maxRoadSegmentLength: 25, maxTerrainPatchSize: 60, defaultKeybinds: { moveForward: "KeyW", moveBackward: "KeyS", moveLeft: "KeyA", moveRight: "KeyD", jump: "Space", roll: "KeyC", interact: "KeyE", inventory: "KeyI", map: "KeyM", debug: "F3", enterVehicle: "KeyF", reload: "KeyR" }, keyLabels: { moveForward: "Ruch do przodu", moveBackward: "Ruch do tylu", moveLeft: "Ruch w lewo", moveRight: "Ruch w prawo", jump: "Skok", roll: "Przewrot (Roll)", interact: "Interakcja", inventory: "Ekwipunek", map: "Pelna mapa", debug: "Debug Mode", enterVehicle: "Wsiadz / Wysiadz (Auto)", reload: "Przeladowanie" }, // Miejsce pod przyszle rozszerzenia bez aktywnej logiki w tym etapie: futureExtensions: { limitedClothesEnabled: false, weaponSkinsEnabled: false } }; """) # 8. client/js/icons/itemIcons.js write_file(base_dir, "client/js/icons/itemIcons.js", """ (function () { function svgDataUri(bg, fg, label) { const svg = ` ${label} `; return "data:image/svg+xml;utf8," + encodeURIComponent(svg); } window.ItemIcons = { pistol: svgDataUri("#1e293b", "#f8fafc", "9MM"), assault_rifle: svgDataUri("#1e293b", "#38bdf8", "AR"), shotgun: svgDataUri("#1e293b", "#fb923c", "SG"), grenade: svgDataUri("#1e293b", "#ef4444", "GRN"), rocket_launcher: svgDataUri("#1e293b", "#facc15", "RPG"), marijuana: svgDataUri("#14532d", "#4ade80", "ZIOLO"), bialogard_coke: svgDataUri("#312e81", "#c4b5fd", "KOKS"), water_bottle: svgDataUri("#0c4a6e", "#7dd3fc", "+5%"), burger: svgDataUri("#7c2d12", "#fdba74", "+5%"), kebab: svgDataUri("#7c2d12", "#fb923c", "+10%"), pizza_slice: svgDataUri("#7c2d12", "#facc15", "+10%"), mega_zestaw: svgDataUri("#713f12", "#fde047", "+15%"), black_coolwave: svgDataUri("#18181b", "#a855f7", "+15% SPD") }; window.getItemIcon = function (itemId) { return window.ItemIcons[itemId] || svgDataUri("#334155", "#e2e8f0", "ITEM"); }; })(); """) # 9. client/js/mapParser.js write_file(base_dir, "client/js/mapParser.js", """ (function () { function subdividePolyline(pts, maxLen) { if (!Array.isArray(pts) || pts.length < 2) return pts || []; const out = []; for (let i = 0; i < pts.length - 1; i++) { const a = pts[i]; const b = pts[i + 1]; const ax = Number(a[0]); const az = Number(a[1]); const bx = Number(b[0]); const bz = Number(b[1]); const dist = Math.hypot(bx - ax, bz - az); const steps = Math.max(1, Math.ceil(dist / maxLen)); for (let s = 0; s < steps; s++) { const t = s / steps; out.push([ax + (bx - ax) * t, az + (bz - az) * t]); } } const last = pts[pts.length - 1]; out.push([Number(last[0]), Number(last[1])]); return out; } class MapParser { constructor(maxSegLen = 25) { this.maxSegLen = maxSegLen; this.roadSegments = []; // { a: [x,z], b: [x,z], w: number, type: string, city: string } this.buildings = []; // { pts: [[x,z],...], h: number, city: string } this.areas = []; // { pts: [[x,z],...], c: number, city: string } this.rivers = []; // { pts: [[x,z],...], w: number, city: string } this.collisionSurfaces = []; // { minX, maxX, minZ, maxZ, y } } async loadAllMaps() { const files = ["koszalin.json", "bialogard.json", "nosowek.json"]; for (const file of files) { try { const resp = await fetch(`/maps/${file}`); if (!resp.ok) continue; const json = await resp.json(); this.parseCityJson(json); } catch (e) { console.warn("Could not load map file", file, e); } } this.buildCollisionGrid(); return this; } parseCityJson(data) { if (!data) return; const city = data.city || "unknown"; // 1. Drogi z segmentacja dlugich odcinkow const roads = Array.isArray(data.roads) ? data.roads : []; for (const road of roads) { const segPts = subdividePolyline(road.pts || [], this.maxSegLen); const w = Number(road.w) || 6; const type = road.type || "unclassified"; for (let i = 0; i < segPts.length - 1; i++) { this.roadSegments.push({ a: segPts[i], b: segPts[i + 1], w, type, city }); } } // 2. Budynki const blds = Array.isArray(data.blds) ? data.blds : []; for (const b of blds) { if (Array.isArray(b.pts) && b.pts.length >= 3) { this.buildings.push({ pts: b.pts.map((p) => [Number(p[0]), Number(p[1])]), h: Number(b.h) || 6.4, city }); } } // 3. Obszary (podzielone na mniejsze kawalki kolizyjne) const areas = Array.isArray(data.areas) ? data.areas : []; for (const ar of areas) { if (Array.isArray(ar.pts) && ar.pts.length >= 3) { this.areas.push({ pts: ar.pts.map((p) => [Number(p[0]), Number(p[1])]), c: Number(ar.c) || 4885050, city }); } } // 4. Rzeki z segmentacja const rivers = Array.isArray(data.rivers) ? data.rivers : []; for (const rv of rivers) { const segPts = subdividePolyline(rv.pts || [], this.maxSegLen); this.rivers.push({ pts: segPts, w: Number(rv.w) || 10, city }); } } buildCollisionGrid() { // Ciagla siatka podloza z kontrolowanymi komorkami (max 40m) zapobiegajaca wpadaniu pod tekstury this.collisionSurfaces = []; const cellSize = 40; for (let gx = -900; gx <= 1000; gx += cellSize) { for (let gz = -800; gz <= 900; gz += cellSize) { this.collisionSurfaces.push({ minX: gx, maxX: gx + cellSize, minZ: gz, maxZ: gz + cellSize, y: 0 }); } } } // Bezpieczne rzutowanie wysokosci (snap to ground) pod postac i kola pojazdu getGroundHeight(x, z) { let groundY = 0; for (const seg of this.roadSegments) { const ax = seg.a[0], az = seg.a[1]; const bx = seg.b[0], bz = seg.b[1]; const abx = bx - ax, abz = bz - az; const lenSq = abx * abx + abz * abz; if (lenSq < 0.0001) continue; const t = Math.max(0, Math.min(1, ((x - ax) * abx + (z - az) * abz) / lenSq)); const px = ax + abx * t; const pz = az + abz * t; const d = Math.hypot(x - px, z - pz); if (d <= seg.w * 0.55) { return 0.04; // nawierzchnia drogi nieco ponad terenem bazowym } } return groundY; } snapToGround(obj, yOffset = 0) { if (!obj || !obj.position) return 0; const gy = this.getGroundHeight(obj.position.x, obj.position.z); obj.position.y = gy + yOffset; return obj.position.y; } } window.MapParser = MapParser; })(); """) # 10. Bronie (osobne pliki) write_file(base_dir, "client/js/weapons/pistol.js", """ window.Weapons = window.Weapons || {}; window.Weapons.pistol = { id: "pistol", name: "Pistolet 9mm", category: "gun", damage: 22, cooldownMs: 260, color: 0xfef08a }; """) write_file(base_dir, "client/js/weapons/assaultRifle.js", """ window.Weapons = window.Weapons || {}; window.Weapons.assault_rifle = { id: "assault_rifle", name: "Karabin Szturmowy", category: "gun", damage: 18, cooldownMs: 110, color: 0x38bdf8 }; """) write_file(base_dir, "client/js/weapons/shotgun.js", """ window.Weapons = window.Weapons || {}; window.Weapons.shotgun = { id: "shotgun", name: "Strzelba Bojowa", category: "gun", damage: 14, cooldownMs: 680, color: 0xfb923c }; """) write_file(base_dir, "client/js/weapons/grenade.js", """ window.Weapons = window.Weapons || {}; window.Weapons.grenade = { id: "grenade", name: "Granat Odlamkowy", category: "throwable", damage: 85, cooldownMs: 900, color: 0xef4444 }; """) write_file(base_dir, "client/js/weapons/rocketLauncher.js", """ window.Weapons = window.Weapons || {}; window.Weapons.rocket_launcher = { id: "rocket_launcher", name: "Rakietnica RPG", category: "heavy", damage: 95, cooldownMs: 1100, color: 0xfacc15 }; """) write_file(base_dir, "client/js/weapons/weaponRegistry.js", """ window.getWeaponSpec = function (weaponId) { return (window.Weapons && window.Weapons[weaponId]) || window.Weapons.pistol; }; """) # 11. Pojazdy (osobne pliki) write_file(base_dir, "client/js/vehicles/sedan.js", """ window.Vehicles = window.Vehicles || {}; window.Vehicles.sedan = { id: "sedan", name: "Koszalin Sedan", baseSpeed: 28, accel: 22, turnSpeed: 2.3, width: 2.0, length: 4.2, height: 1.4 }; """) write_file(base_dir, "client/js/vehicles/sportCoupe.js", """ window.Vehicles = window.Vehicles || {}; window.Vehicles.sport_coupe = { id: "sport_coupe", name: "Baltyk Coupe", baseSpeed: 36, accel: 28, turnSpeed: 2.5, width: 2.05, length: 4.1, height: 1.25 }; """) write_file(base_dir, "client/js/vehicles/suvOffroad.js", """ window.Vehicles = window.Vehicles || {}; window.Vehicles.suv_offroad = { id: "suv_offroad", name: "Nosowek 4x4", baseSpeed: 26, accel: 20, turnSpeed: 2.0, width: 2.2, length: 4.5, height: 1.75 }; """) write_file(base_dir, "client/js/vehicles/vehicleRegistry.js", """ window.getVehicleSpec = function (modelId) { return (window.Vehicles && window.Vehicles[modelId]) || window.Vehicles.sedan; }; """) # 12. client/js/ui.js write_file(base_dir, "client/js/ui.js", """ (function () { class UIManager { constructor(game) { this.game = game; this.selectedHotbarSlot = 0; this.listeningBind = null; this.bindEvents(); } bindEvents() { // Zakladki logowania/rejestracji document.getElementById("tabLogin").addEventListener("click", () => { document.getElementById("tabLogin").classList.add("active"); document.getElementById("tabRegister").classList.remove("active"); document.getElementById("btnAuthSubmit").textContent = "Zaloguj sie"; this.game.authMode = "login"; }); document.getElementById("tabRegister").addEventListener("click", () => { document.getElementById("tabRegister").classList.add("active"); document.getElementById("tabLogin").classList.remove("active"); document.getElementById("btnAuthSubmit").textContent = "Zarejestruj konto"; this.game.authMode = "register"; }); document.getElementById("btnAuthSubmit").addEventListener("click", () => { const login = document.getElementById("authLogin").value.trim(); const password = document.getElementById("authPassword").value; this.game.submitAuth(login, password); }); // Menu glowne document.querySelectorAll(".menu-tab").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".menu-tab").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); const sec = btn.dataset.menu; document.getElementById("menuSectionPlay").classList.toggle("hidden", sec !== "play"); document.getElementById("menuSectionEq").classList.toggle("hidden", sec !== "eq"); document.getElementById("menuSectionSkin").classList.toggle("hidden", sec !== "skin"); document.getElementById("menuSectionSettings").classList.toggle("hidden", sec !== "settings"); if (sec === "eq") this.renderMenuEq(); if (sec === "skin") this.syncSkinInputs(); if (sec === "settings") this.syncSettingsInputs(); }); }); document.getElementById("btnResumeGame").addEventListener("click", () => { this.toggleMainMenu(false); }); document.querySelectorAll(".slot-pick").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".slot-pick").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); this.selectedHotbarSlot = Number(btn.dataset.slot); }); }); document.getElementById("btnSaveSkin").addEventListener("click", () => { const skin = { shirt: document.getElementById("skinShirt").value, pants: document.getElementById("skinPants").value, skinTone: document.getElementById("skinTone").value }; this.game.updateProfile({ skin }); this.notify("Zapisano wyglad postaci (Skin)."); }); document.getElementById("btnSaveSettings").addEventListener("click", () => { const settings = { graphicsQuality: document.getElementById("setQuality").value, fov: Number(document.getElementById("setFov").value) || 75, shadows: document.getElementById("setShadows").checked, keybinds: { ...(this.game.playerState.settings.keybinds || {}) } }; const dbg = document.getElementById("setDebugToggle").checked; this.game.setDebugMode(dbg); this.game.updateProfile({ settings }); this.notify("Zapisano ustawienia."); }); document.getElementById("btnCloseEq").addEventListener("click", () => this.toggleEq(false)); document.getElementById("btnCloseAction").addEventListener("click", () => this.closeActionPanel()); document.getElementById("btnCloseFullMap").addEventListener("click", () => this.toggleFullMap(false)); window.addEventListener("keydown", (e) => { if (this.listeningBind) { e.preventDefault(); this.game.playerState.settings.keybinds[this.listeningBind] = e.code; this.listeningBind = null; this.renderKeybinds(); this.notify("Przypisano nowy klawisz."); } }); } notify(text) { const box = document.getElementById("notificationBox"); box.textContent = text; box.classList.add("show"); clearTimeout(this._notifyTimer); this._notifyTimer = setTimeout(() => box.classList.remove("show"), 2800); } showAuthError(msg) { document.getElementById("authError").textContent = msg; } hideAuthModal() { document.getElementById("authModal").classList.add("hidden"); document.getElementById("hud").classList.remove("hidden"); } toggleMainMenu(forceState = null) { const el = document.getElementById("mainMenu"); const next = forceState !== null ? forceState : el.classList.contains("hidden"); el.classList.toggle("hidden", !next); if (next) { this.game.requestLeaderboard(); this.syncSkinInputs(); this.syncSettingsInputs(); } } toggleEq(forceState = null) { const el = document.getElementById("eqOverlay"); const next = forceState !== null ? forceState : el.classList.contains("hidden"); el.classList.toggle("hidden", !next); if (next) this.renderTileEq(); } toggleFullMap(forceState = null) { const el = document.getElementById("fullMapOverlay"); const next = forceState !== null ? forceState : el.classList.contains("hidden"); el.classList.toggle("hidden", !next); if (next) this.game.renderFullMap(); } closeActionPanel() { document.getElementById("actionPanel").classList.add("hidden"); } openShopPanel() { const panel = document.getElementById("actionPanel"); const body = document.getElementById("actionPanelBody"); document.getElementById("actionPanelTitle").textContent = "Sklep Spozywczy & Energetyk"; const catalog = Object.values(this.game.shopCatalog || {}); body.innerHTML = catalog .map( (item) => `
${item.name}
Cena: ${item.price}$
` ) .join(""); panel.classList.remove("hidden"); } openDealerPanel() { const panel = document.getElementById("actionPanel"); const body = document.getElementById("actionPanelBody"); document.getElementById("actionPanelTitle").textContent = "Odbiorca Towaru (NPC)"; body.innerHTML = `

Kupuje losowo 1-5 szt. (0.1% szansy na wykup calosci).

Marihuana (Rynek Koszalin)
Cena: 95$ / szt.
Bialogardzki Koks (Dworzec Bialogard)
Cena: 180$ / szt.
`; panel.classList.remove("hidden"); } openTuningPanel() { const tuning = this.game.playerState.vehicleTuning || {}; const panel = document.getElementById("actionPanel"); const body = document.getElementById("actionPanelBody"); document.getElementById("actionPanelTitle").textContent = "Warsztat Tuningu"; body.innerHTML = `

Silnik Lv.${tuning.engineLevel || 1}/5 • Turbo Lv.${tuning.turboLevel || 1}/5

Ulepszenie Silnika
Koszt: ${((tuning.engineLevel || 1) + 1) * 400}$
Ulepszenie Turbo
Koszt: ${((tuning.turboLevel || 1) + 1) * 450}$
Kolor karoserii (200$)
Model pojazdu (600$)
`; panel.classList.remove("hidden"); } renderLeaderboard(rows) { const tbody = document.querySelector("#leaderboardTable tbody"); tbody.innerHTML = (rows || []) .map( (r, i) => ` ${i + 1} ${r.login} ${r.kills} ${r.deaths} ${r.money}$ ` ) .join(""); } renderTileEq() { const grid = document.getElementById("eqTileGrid"); const inv = (this.game.playerState && this.game.playerState.inventory) || []; grid.innerHTML = inv .map( (item) => `
${item.name}
${item.name} x${item.qty}
${item.type === "food" || item.type === "drink" ? `` : ""}
` ) .join(""); } renderMenuEq() { const grid = document.getElementById("menuEqGrid"); const inv = (this.game.playerState && this.game.playerState.inventory) || []; grid.innerHTML = inv .map( (item) => `
${item.name}
${item.name} x${item.qty}
` ) .join(""); } renderHotbar() { const bar = document.getElementById("hotbar"); const st = this.game.playerState; if (!st) return; const hotbar = st.hotbar || []; bar.innerHTML = [0, 1, 2, 3, 4] .map((idx) => { const itemId = hotbar[idx]; const found = st.inventory.find((i) => i.id === itemId); const activeClass = this.game.activeHotbarIndex === idx ? "active" : ""; return `
${idx + 1} ${found ? `${found.name.split(" ")[0]} (${found.qty})` : `Pusty`}
`; }) .join(""); } syncSkinInputs() { const skin = (this.game.playerState && this.game.playerState.skin) || {}; document.getElementById("skinShirt").value = skin.shirt || "#2563eb"; document.getElementById("skinPants").value = skin.pants || "#1e293b"; document.getElementById("skinTone").value = skin.skinTone || "#e0ac8b"; } syncSettingsInputs() { const s = (this.game.playerState && this.game.playerState.settings) || {}; document.getElementById("setQuality").value = s.graphicsQuality || "high"; document.getElementById("setFov").value = s.fov || 75; document.getElementById("setShadows").checked = s.shadows !== false; document.getElementById("setDebugToggle").checked = this.game.debugEnabled; this.renderKeybinds(); } renderKeybinds() { const container = document.getElementById("keybindsList"); const kb = (this.game.playerState && this.game.playerState.settings && this.game.playerState.settings.keybinds) || window.GameConfig.defaultKeybinds; container.innerHTML = Object.keys(window.GameConfig.keyLabels) .map((actionKey) => { const code = kb[actionKey] || window.GameConfig.defaultKeybinds[actionKey]; const isListening = this.listeningBind === actionKey; return ` `; }) .join(""); } startRebind(actionKey) { this.listeningBind = actionKey; this.renderKeybinds(); } updateHud() { const st = this.game.playerState; if (!st) return; document.getElementById("hudPlayerInfo").textContent = `Gracz: ${this.game.login}`; document.getElementById("hudMoney").textContent = `${st.money || 0}$`; document.getElementById("hudHp").textContent = `HP: ${st.hp}`; const boostEl = document.getElementById("hudBoost"); if (Date.now() < this.game.speedBoostUntil) { boostEl.classList.remove("hidden"); boostEl.textContent = `BOOST +${this.game.speedBoostPct}%`; } else { boostEl.classList.add("hidden"); } this.renderHotbar(); } } window.UIManager = UIManager; })(); """) # 13. client/js/game.js write_file(base_dir, "client/js/game.js", """ (function () { class GTACoszalinaGame { constructor() { this.authMode = "login"; this.socketId = null; this.login = null; this.playerState = null; this.activeHotbarIndex = 0; this.speedBoostUntil = 0; this.speedBoostPct = 0; this.debugEnabled = false; this.pingMs = 12; this.serverTps = 20; this.zones = {}; this.shops = []; this.tunings = []; this.dealers = []; this.shopCatalog = {}; this.remotePlayers = []; this.npcVehicles = []; this.droppedItems = []; this.projectiles = []; this.keysDown = new Set(); this.playerYaw = 0; this.playerVelY = 0; this.isGrounded = true; this.inVehicle = false; this.carSpeed = 0; this.rollUntil = 0; this.lastShotTime = 0; this.mapParser = new window.MapParser(window.GameConfig.maxRoadSegmentLength); this.ui = new window.UIManager(this); window.__game = this; window.__ui = this.ui; this.initThree(); this.connectSocket(); this.bindInputs(); this.startLoop(); } initThree() { const canvas = document.getElementById("gameCanvas"); this.scene = new THREE.Scene(); this.scene.background = new THREE.Color(0x60a5fa); this.scene.fog = new THREE.FogExp2(0x93c5fd, 0.0014); this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1800); this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); this.renderer.setSize(window.innerWidth, window.innerHeight); this.renderer.shadowMap.enabled = true; const hemi = new THREE.HemisphereLight(0xffffff, 0x334155, 0.9); this.scene.add(hemi); const dirLight = new THREE.DirectionalLight(0xffffff, 1.1); dirLight.position.set(120, 220, 100); dirLight.castShadow = true; this.scene.add(dirLight); // Podloze bazowe podzielone na segmenty const groundGeo = new THREE.PlaneGeometry(2400, 2400, 48, 48); groundGeo.rotateX(-Math.PI / 2); const groundMat = new THREE.MeshStandardMaterial({ color: 0x3f6212, roughness: 0.95 }); const groundMesh = new THREE.Mesh(groundGeo, groundMat); groundMesh.receiveShadow = true; this.scene.add(groundMesh); this.worldGroup = new THREE.Group(); this.scene.add(this.worldGroup); this.entitiesGroup = new THREE.Group(); this.scene.add(this.entitiesGroup); // Postac gracza this.playerMesh = new THREE.Group(); const bodyGeo = new THREE.BoxGeometry(0.8, 1.5, 0.5); const bodyMat = new THREE.MeshStandardMaterial({ color: 0x2563eb }); this.bodyMesh = new THREE.Mesh(bodyGeo, bodyMat); this.bodyMesh.position.y = 0.75; this.playerMesh.add(this.bodyMesh); const headGeo = new THREE.BoxGeometry(0.55, 0.55, 0.55); const headMat = new THREE.MeshStandardMaterial({ color: 0xe0ac8b }); this.headMesh = new THREE.Mesh(headGeo, headMat); this.headMesh.position.y = 1.8; this.playerMesh.add(this.headMesh); this.scene.add(this.playerMesh); // Pojazd gracza this.playerCarMesh = new THREE.Group(); const chassisGeo = new THREE.BoxGeometry(2.0, 1.0, 4.2); this.carChassisMat = new THREE.MeshStandardMaterial({ color: 0xdc2626 }); const chassis = new THREE.Mesh(chassisGeo, this.carChassisMat); chassis.position.y = 0.85; this.playerCarMesh.add(chassis); this.playerCarMesh.visible = false; this.scene.add(this.playerCarMesh); window.addEventListener("resize", () => { this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); this.renderer.setSize(window.innerWidth, window.innerHeight); }); this.mapParser.loadAllMaps().then(() => { this.buildMapGeometry(); }); } buildMapGeometry() { this.worldGroup.clear(); // Drogi z podzielonych segmentow + snap to ground const roadMat = new THREE.MeshStandardMaterial({ color: 0x1e293b, roughness: 0.85 }); for (const seg of this.mapParser.roadSegments) { const ax = seg.a[0], az = seg.a[1]; const bx = seg.b[0], bz = seg.b[1]; const len = Math.hypot(bx - ax, bz - az); if (len < 0.05) continue; const geo = new THREE.BoxGeometry(seg.w, 0.08, len); const mesh = new THREE.Mesh(geo, roadMat); mesh.position.set((ax + bx) * 0.5, 0.04, (az + bz) * 0.5); mesh.rotation.y = Math.atan2(bx - ax, bz - az); mesh.receiveShadow = true; this.worldGroup.add(mesh); } // Budynki for (const b of this.mapParser.buildings) { if (!b.pts || b.pts.length < 3) continue; let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity; for (const p of b.pts) { if (p[0] < minX) minX = p[0]; if (p[0] > maxX) maxX = p[0]; if (p[1] < minZ) minZ = p[1]; if (p[1] > maxZ) maxZ = p[1]; } const w = Math.max(2, maxX - minX); const d = Math.max(2, maxZ - minZ); const h = Math.max(2.5, b.h || 6.4); const bMat = new THREE.MeshStandardMaterial({ color: 0x64748b, roughness: 0.7 }); const bMesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), bMat); bMesh.position.set((minX + maxX) * 0.5, h * 0.5, (minZ + maxZ) * 0.5); bMesh.castShadow = true; bMesh.receiveShadow = true; this.worldGroup.add(bMesh); } // Rzeki const riverMat = new THREE.MeshStandardMaterial({ color: 0x0284c7, roughness: 0.25 }); for (const rv of this.mapParser.rivers) { for (let i = 0; i < rv.pts.length - 1; i++) { const a = rv.pts[i], b = rv.pts[i + 1]; const len = Math.hypot(b[0] - a[0], b[1] - a[1]); if (len < 0.05) continue; const m = new THREE.Mesh(new THREE.BoxGeometry(rv.w, 0.05, len), riverMat); m.position.set((a[0] + b[0]) * 0.5, 0.02, (a[1] + b[1]) * 0.5); m.rotation.y = Math.atan2(b[0] - a[0], b[1] - a[1]); this.worldGroup.add(m); } } } applyVisualAppearance() { if (!this.playerState) return; if (this.playerState.skin) { if (this.playerState.skin.shirt) this.bodyMesh.material.color.set(this.playerState.skin.shirt); if (this.playerState.skin.skinTone) this.headMesh.material.color.set(this.playerState.skin.skinTone); } if (this.playerState.vehicleTuning && this.playerState.vehicleTuning.color) { this.carChassisMat.color.set(this.playerState.vehicleTuning.color); } if (this.playerState.settings) { this.camera.fov = Number(this.playerState.settings.fov) || 75; this.camera.updateProjectionMatrix(); this.renderer.shadowMap.enabled = this.playerState.settings.shadows !== false; } } connectSocket() { const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; this.ws = new WebSocket(`${proto}//${window.location.host}`); this.ws.addEventListener("message", (ev) => { const msg = JSON.parse(ev.data); if (msg.type === "welcome") { this.socketId = msg.socketId; this.zones = msg.zones || {}; this.shops = msg.shops || []; this.tunings = msg.tunings || []; this.dealers = msg.dealers || []; this.shopCatalog = msg.shopCatalog || {}; return; } if (msg.type === "pong") { this.pingMs = Math.max(1, Date.now() - msg.clientTime); return; } if (msg.type === "auth_error") { this.ui.showAuthError(msg.error); return; } if (msg.type === "auth_ok") { this.login = msg.login; this.playerState = msg.state; this.playerYaw = this.playerState.pos.yaw || 0; this.playerMesh.position.set( this.playerState.pos.x, this.mapParser.getGroundHeight(this.playerState.pos.x, this.playerState.pos.z), this.playerState.pos.z ); this.applyVisualAppearance(); this.ui.hideAuthModal(); this.ui.updateHud(); if (msg.leaderboard) this.ui.renderLeaderboard(msg.leaderboard); this.ui.notify(`Witaj, ${this.login}!`); return; } if (msg.type === "state_sync") { this.playerState = msg.state; this.applyVisualAppearance(); this.ui.updateHud(); return; } if (msg.type === "speed_boost") { this.speedBoostPct = msg.boostPct || 15; this.speedBoostUntil = Date.now() + (msg.durationMs || 150000); this.ui.updateHud(); return; } if (msg.type === "notification") { this.ui.notify(msg.text); return; } if (msg.type === "player_died") { this.ui.notify("Zginales! Rozrzucono EQ na ziemi (znika po 3 min). Respawn za 4s..."); return; } if (msg.type === "player_respawned") { this.playerState = msg.state; this.inVehicle = false; this.playerCarMesh.visible = false; this.playerMesh.visible = true; this.playerMesh.position.set(0, this.mapParser.getGroundHeight(0, 20), 20); this.ui.updateHud(); this.ui.notify("Odrodzono!"); return; } if (msg.type === "tracers") { this.spawnTracers(msg.tracers || []); return; } if (msg.type === "explosion") { this.spawnExplosionEffect(msg.x, msg.y, msg.z, msg.radius); return; } if (msg.type === "world_tick") { this.serverTps = msg.tps || 20; this.remotePlayers = msg.players || []; this.npcVehicles = msg.npcVehicles || []; this.droppedItems = msg.droppedItems || []; this.projectiles = msg.projectiles || []; this.syncDynamicEntities(); } }); setInterval(() => { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "ping", clientTime: Date.now() })); } }, 2500); } submitAuth(login, password) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: this.authMode === "register" ? "register" : "login", login, password })); } requestLeaderboard() { fetch("/api/leaderboard") .then((r) => r.json()) .then((rows) => this.ui.renderLeaderboard(rows)) .catch(() => {}); } updateProfile(patch) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "update_profile", ...patch })); } selectHotbarSlot(idx) { this.activeHotbarIndex = idx; this.ui.renderHotbar(); } assignHotbar(slotIdx, itemId) { if (!this.playerState) return; const hb = [...(this.playerState.hotbar || ["pistol", "assault_rifle", "shotgun", "grenade", "rocket_launcher"])]; hb[slotIdx] = itemId; this.playerState.hotbar = hb; this.updateProfile({ hotbar: hb }); this.ui.renderHotbar(); this.ui.notify(`Przypisano do slotu ${slotIdx + 1}`); } useItem(itemId) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "use_item", itemId })); } dropItem(itemId, qty = 1) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "drop_item", itemId, qty })); } buyShopItem(itemId) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "buy_shop_item", itemId })); } sellDrugToNpc(drugId) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "sell_drug_npc", drugId })); } upgradeTuning(upgradeType, value = null) { if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; this.ws.send(JSON.stringify({ type: "tuning_upgrade", upgradeType, color: value, model: value })); } setDebugMode(enabled) { this.debugEnabled = Boolean(enabled); document.getElementById("debugOverlay").classList.toggle("hidden", !this.debugEnabled); } bindInputs() { window.addEventListener("keydown", (e) => { if (this.ui.listeningBind) return; if (document.activeElement && ["INPUT", "SELECT"].includes(document.activeElement.tagName)) return; if (e.code === "Escape") { if (!document.getElementById("fullMapOverlay").classList.contains("hidden")) { this.ui.toggleFullMap(false); return; } if (!document.getElementById("eqOverlay").classList.contains("hidden")) { this.ui.toggleEq(false); return; } if (!document.getElementById("actionPanel").classList.contains("hidden")) { this.ui.closeActionPanel(); return; } this.ui.toggleMainMenu(); return; } if (!this.playerState) return; const kb = (this.playerState.settings && this.playerState.settings.keybinds) || window.GameConfig.defaultKeybinds; if (e.code === kb.debug || e.code === "F3") { e.preventDefault(); this.setDebugMode(!this.debugEnabled); return; } if (e.code === kb.inventory || e.code === "KeyI") { e.preventDefault(); this.ui.toggleEq(); return; } if (e.code === kb.map || e.code === "KeyM") { e.preventDefault(); this.ui.toggleFullMap(); return; } if (["Digit1", "Digit2", "Digit3", "Digit4", "Digit5"].includes(e.code)) { const slot = Number(e.code.replace("Digit", "")) - 1; this.selectHotbarSlot(slot); const itemId = (this.playerState.hotbar || [])[slot]; if (itemId) { const invItem = this.playerState.inventory.find((i) => i.id === itemId); if (invItem && (invItem.type === "food" || invItem.type === "drink")) { this.useItem(itemId); } } return; } if (e.code === kb.roll || e.code === "KeyC") { if (!this.inVehicle && Date.now() > this.rollUntil) { this.rollUntil = Date.now() + 550; this.ui.notify("Przewrot bojowy (Roll)"); } } if (e.code === kb.enterVehicle || e.code === "KeyF") { this.inVehicle = !this.inVehicle; this.playerCarMesh.visible = this.inVehicle; this.playerMesh.visible = !this.inVehicle; if (this.inVehicle) { this.playerCarMesh.position.copy(this.playerMesh.position); this.mapParser.snapToGround(this.playerCarMesh, 0); this.carSpeed = 0; } else { this.playerMesh.position.set(this.playerCarMesh.position.x + 2.5, 0, this.playerCarMesh.position.z); this.mapParser.snapToGround(this.playerMesh, 0); } this.ui.notify(this.inVehicle ? "Wsiadles do pojazdu" : "Wysiadles z pojazdu"); } if (e.code === kb.interact || e.code === "KeyE") { this.triggerContextInteraction(); } this.keysDown.add(e.code); }); window.addEventListener("keyup", (e) => { this.keysDown.delete(e.code); }); window.addEventListener("mousedown", (e) => { if (e.button !== 0 || !this.playerState || this.playerState.hp <= 0) return; if (!document.getElementById("mainMenu").classList.contains("hidden")) return; if (!document.getElementById("eqOverlay").classList.contains("hidden")) return; if (!document.getElementById("actionPanel").classList.contains("hidden")) return; if (!document.getElementById("fullMapOverlay").classList.contains("hidden")) return; if (document.getElementById("hud").classList.contains("hidden")) return; this.fireSelectedWeapon(); }); window.addEventListener("mousemove", (e) => { if (!this.playerState) return; if (!document.getElementById("mainMenu").classList.contains("hidden")) return; if (document.getElementById("hud").classList.contains("hidden")) return; if (document.pointerLockElement === document.getElementById("gameCanvas")) { this.playerYaw -= e.movementX * 0.0025; } else if (e.buttons === 2) { this.playerYaw -= e.movementX * 0.004; } }); window.addEventListener("contextmenu", (e) => e.preventDefault()); } triggerContextInteraction() { const pos = this.getActivePosition(); // 1. Najblizszy wyrzucony przedmiot na ziemi const nearDrop = this.droppedItems.find((d) => Math.hypot(d.x - pos.x, d.z - pos.z) < 4.5); if (nearDrop && this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "pickup_item", dropId: nearDrop.id })); return; } // 2. Strefa zbioru narkotykow (Rynek Koszalin / Dworzec Bialogard) const zone = Object.values(this.zones || {}).find((z) => Math.hypot(z.x - pos.x, z.z - pos.z) <= z.radius + 3); if (zone && this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "harvest_drug", zoneId: zone.id })); return; } // 3. NPC odbiorca narkotykow const dealer = (this.dealers || []).find((d) => Math.hypot(d.x - pos.x, d.z - pos.z) <= d.radius + 3); if (dealer) { this.ui.openDealerPanel(); return; } // 4. Sklep spozywczy const shop = (this.shops || []).find((s) => Math.hypot(s.x - pos.x, s.z - pos.z) <= s.radius + 3); if (shop) { this.ui.openShopPanel(); return; } // 5. Warsztat tuningu const tuning = (this.tunings || []).find((t) => Math.hypot(t.x - pos.x, t.z - pos.z) <= t.radius + 3); if (tuning) { this.ui.openTuningPanel(); } } fireSelectedWeapon() { const hb = this.playerState.hotbar || []; const weaponId = hb[this.activeHotbarIndex] || "pistol"; const spec = window.getWeaponSpec(weaponId); const now = Date.now(); if (now - this.lastShotTime < (spec.cooldownMs || 250)) return; this.lastShotTime = now; const pos = this.getActivePosition(); const dx = Math.sin(this.playerYaw); const dz = Math.cos(this.playerYaw); if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "shoot", weaponId, ox: pos.x, oy: pos.y + 1.4, oz: pos.z, dx, dy: 0.02, dz })); } } spawnTracers(tracers) { for (const tr of tracers) { const pts = [ new THREE.Vector3(tr.start.x, tr.start.y, tr.start.z), new THREE.Vector3(tr.end.x, tr.end.y, tr.end.z) ]; const geo = new THREE.BufferGeometry().setFromPoints(pts); const mat = new THREE.LineBasicMaterial({ color: 0xfef08a }); const line = new THREE.Line(geo, mat); this.entitiesGroup.add(line); setTimeout(() => this.entitiesGroup.remove(line), 80); } } spawnExplosionEffect(x, y, z, radius) { const geo = new THREE.SphereGeometry(Math.min(5, radius * 0.4), 16, 16); const mat = new THREE.MeshBasicMaterial({ color: 0xf97316, transparent: true, opacity: 0.8 }); const sphere = new THREE.Mesh(geo, mat); sphere.position.set(x, Math.max(0.5, y), z); this.entitiesGroup.add(sphere); setTimeout(() => this.entitiesGroup.remove(sphere), 350); } syncDynamicEntities() { this.entitiesGroup.clear(); // Inni gracze for (const rp of this.remotePlayers) { if (rp.socketId === this.socketId) continue; const m = new THREE.Mesh( new THREE.BoxGeometry(0.8, 1.6, 0.5), new THREE.MeshStandardMaterial({ color: (rp.skin && rp.skin.shirt) || 0xef4444 }) ); const gy = this.mapParser.getGroundHeight(rp.pos.x, rp.pos.z); m.position.set(rp.pos.x, gy + 0.8, rp.pos.z); this.entitiesGroup.add(m); } // Pojazdy NPC for (const nv of this.npcVehicles) { const car = new THREE.Mesh( new THREE.BoxGeometry(2.0, 1.0, 4.2), new THREE.MeshStandardMaterial({ color: nv.color || 0x94a3b8 }) ); const gy = this.mapParser.getGroundHeight(nv.x, nv.z); car.position.set(nv.x, gy + 0.85, nv.z); car.rotation.y = nv.yaw || 0; this.entitiesGroup.add(car); } // Wyrzucone / posmiertne przedmioty for (const di of this.droppedItems) { const box = new THREE.Mesh( new THREE.BoxGeometry(0.6, 0.6, 0.6), new THREE.MeshStandardMaterial({ color: 0x22c55e }) ); const gy = this.mapParser.getGroundHeight(di.x, di.z); box.position.set(di.x, gy + 0.4, di.z); this.entitiesGroup.add(box); } // Granaty i rakiety w locie for (const pr of this.projectiles) { const pMesh = new THREE.Mesh( new THREE.SphereGeometry(pr.kind === "rocket" ? 0.35 : 0.25, 10, 10), new THREE.MeshBasicMaterial({ color: pr.kind === "rocket" ? 0xfacc15 : 0xef4444 }) ); pMesh.position.set(pr.x, Math.max(0.2, pr.y), pr.z); this.entitiesGroup.add(pMesh); } } getActivePosition() { if (this.inVehicle) { return { x: this.playerCarMesh.position.x, y: this.playerCarMesh.position.y, z: this.playerCarMesh.position.z, yaw: this.playerYaw }; } return { x: this.playerMesh.position.x, y: this.playerMesh.position.y, z: this.playerMesh.position.z, yaw: this.playerYaw }; } updatePhysicsAndMovement(dt) { if (!this.playerState || this.playerState.hp <= 0) return; const kb = (this.playerState.settings && this.playerState.settings.keybinds) || window.GameConfig.defaultKeybinds; const boostMult = Date.now() < this.speedBoostUntil ? 1 + (this.speedBoostPct || 15) / 100 : 1; const rollMult = Date.now() < this.rollUntil ? 1.55 : 1; if (!this.inVehicle) { let moveX = 0; let moveZ = 0; if (this.keysDown.has(kb.moveForward)) moveZ += 1; if (this.keysDown.has(kb.moveBackward)) moveZ -= 1; if (this.keysDown.has(kb.moveLeft)) moveX -= 1; if (this.keysDown.has(kb.moveRight)) moveX += 1; const speed = 11 * boostMult * rollMult; if (moveX !== 0 || moveZ !== 0) { const len = Math.hypot(moveX, moveZ); moveX /= len; moveZ /= len; const forwardX = Math.sin(this.playerYaw); const forwardZ = Math.cos(this.playerYaw); const rightX = Math.cos(this.playerYaw); const rightZ = -Math.sin(this.playerYaw); this.playerMesh.position.x += (forwardX * moveZ + rightX * moveX) * speed * dt; this.playerMesh.position.z += (forwardZ * moveZ + rightZ * moveX) * speed * dt; } const groundY = this.mapParser.getGroundHeight(this.playerMesh.position.x, this.playerMesh.position.z); if (this.keysDown.has(kb.jump) && this.isGrounded) { this.playerVelY = 8.5; this.isGrounded = false; } this.playerVelY -= 22 * dt; this.playerMesh.position.y += this.playerVelY * dt; if (this.playerMesh.position.y <= groundY) { this.playerMesh.position.y = groundY; this.playerVelY = 0; this.isGrounded = true; } if (Date.now() < this.rollUntil) { this.playerMesh.rotation.x += 12 * dt; } else { this.playerMesh.rotation.x = 0; } this.playerMesh.rotation.y = this.playerYaw; } else { const tuning = this.playerState.vehicleTuning || {}; const spec = window.getVehicleSpec(tuning.model || "sedan"); const maxSpd = spec.baseSpeed * (1 + ((tuning.engineLevel || 1) - 1) * 0.14 + ((tuning.turboLevel || 1) - 1) * 0.12) * boostMult; const accel = spec.accel * (1 + ((tuning.turboLevel || 1) - 1) * 0.15); if (this.keysDown.has(kb.moveForward)) this.carSpeed = Math.min(maxSpd, this.carSpeed + accel * dt); else if (this.keysDown.has(kb.moveBackward)) this.carSpeed = Math.max(-maxSpd * 0.5, this.carSpeed - accel * dt); else this.carSpeed *= Math.pow(0.25, dt); if (Math.abs(this.carSpeed) > 0.3) { const dirSign = this.carSpeed >= 0 ? 1 : -1; if (this.keysDown.has(kb.moveLeft)) this.playerYaw += spec.turnSpeed * dt * dirSign; if (this.keysDown.has(kb.moveRight)) this.playerYaw -= spec.turnSpeed * dt * dirSign; } this.playerCarMesh.position.x += Math.sin(this.playerYaw) * this.carSpeed * dt; this.playerCarMesh.position.z += Math.cos(this.playerYaw) * this.carSpeed * dt; this.mapParser.snapToGround(this.playerCarMesh, 0); this.playerCarMesh.rotation.y = this.playerYaw; } // Kamera za plecami + snap/ochrona nad ziemia const active = this.getActivePosition(); const camDist = this.inVehicle ? 9.5 : 6.5; const camX = active.x - Math.sin(this.playerYaw) * camDist; const camZ = active.z - Math.cos(this.playerYaw) * camDist; const camGround = this.mapParser.getGroundHeight(camX, camZ); this.camera.position.set(camX, Math.max(camGround + 2.2, active.y + (this.inVehicle ? 4.2 : 3.0)), camZ); this.camera.lookAt(active.x, active.y + 1.3, active.z); // Podpowiedz interakcji this.updateInteractPrompt(active); // Wysylanie pozycji na serwer this.playerState.pos = { x: active.x, y: active.y, z: active.z, yaw: this.playerYaw }; if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ type: "move", x: active.x, y: active.y, z: active.z, yaw: this.playerYaw, inVehicle: this.inVehicle, pingMs: this.pingMs })); } } updateInteractPrompt(pos) { const prompt = document.getElementById("interactPrompt"); let text = null; if (this.droppedItems.some((d) => Math.hypot(d.x - pos.x, d.z - pos.z) < 4.5)) { text = "[E] Podnies przedmiot"; } else { const z = Object.values(this.zones || {}).find((zn) => Math.hypot(zn.x - pos.x, zn.z - pos.z) <= zn.radius + 3); if (z) text = `[E] Zbieraj: ${z.name}`; else { const dl = (this.dealers || []).find((d) => Math.hypot(d.x - pos.x, d.z - pos.z) <= d.radius + 3); if (dl) text = `[E] Sprzedaj towar (${dl.name})`; else { const sh = (this.shops || []).find((s) => Math.hypot(s.x - pos.x, s.z - pos.z) <= s.radius + 3); if (sh) text = `[E] Sklep (${sh.name})`; else { const tn = (this.tunings || []).find((t) => Math.hypot(t.x - pos.x, t.z - pos.z) <= t.radius + 3); if (tn) text = `[E] Tuning (${tn.name})`; } } } } if (text) { prompt.textContent = text; prompt.classList.remove("hidden"); } else { prompt.classList.add("hidden"); } } drawRadarCanvas(canvasId, scale, centerX, centerZ) { const canvas = document.getElementById(canvasId); if (!canvas) return; const ctx = canvas.getContext("2d"); const w = canvas.width; const h = canvas.height; ctx.clearRect(0, 0, w, h); ctx.fillStyle = "#0f172a"; ctx.fillRect(0, 0, w, h); const toPx = (wx, wz) => [ w * 0.5 + (wx - centerX) * scale, h * 0.5 + (wz - centerZ) * scale ]; // Drogi ctx.strokeStyle = "#64748b"; ctx.lineWidth = Math.max(1, 2.2 * scale * 25); for (const seg of this.mapParser.roadSegments) { const [x1, y1] = toPx(seg.a[0], seg.a[1]); const [x2, y2] = toPx(seg.b[0], seg.b[1]); ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } // Blipy stref narkotykow for (const z of Object.values(this.zones || {})) { const [zx, zy] = toPx(z.x, z.z); ctx.fillStyle = "#22c55e"; ctx.beginPath(); ctx.arc(zx, zy, 5, 0, Math.PI * 2); ctx.fill(); } // Blipy sklepow for (const sh of this.shops || []) { const [sx, sy] = toPx(sh.x, sh.z); ctx.fillStyle = "#38bdf8"; ctx.beginPath(); ctx.arc(sx, sy, 5, 0, Math.PI * 2); ctx.fill(); } // Blipy tuningu for (const tn of this.tunings || []) { const [tx, ty] = toPx(tn.x, tn.z); ctx.fillStyle = "#f97316"; ctx.beginPath(); ctx.arc(tx, ty, 5, 0, Math.PI * 2); ctx.fill(); } // Inni gracze for (const rp of this.remotePlayers) { if (rp.socketId === this.socketId) continue; const [rx, ry] = toPx(rp.pos.x, rp.pos.z); ctx.fillStyle = "#ef4444"; ctx.beginPath(); ctx.arc(rx, ry, 4, 0, Math.PI * 2); ctx.fill(); } // Gracz const pos = this.getActivePosition(); const [px, py] = toPx(pos.x, pos.z); ctx.fillStyle = "#facc15"; ctx.beginPath(); ctx.arc(px, py, 5.5, 0, Math.PI * 2); ctx.fill(); } renderFullMap() { const pos = this.getActivePosition(); this.drawRadarCanvas("fullMapCanvas", 0.42, pos.x, pos.z); } startLoop() { let lastTime = performance.now(); let fpsFrames = 0; let fpsLastCheck = performance.now(); let currentFps = 60; const loop = (now) => { const dt = Math.min(0.05, (now - lastTime) / 1000); lastTime = now; fpsFrames++; if (now - fpsLastCheck >= 500) { currentFps = Math.round((fpsFrames * 1000) / (now - fpsLastCheck)); fpsFrames = 0; fpsLastCheck = now; } if (this.playerState && document.getElementById("mainMenu").classList.contains("hidden")) { this.updatePhysicsAndMovement(dt); } const pos = this.getActivePosition(); this.drawRadarCanvas("minimapCanvas", 0.85, pos.x, pos.z); if (this.debugEnabled) { const deg = Math.round(((this.playerYaw * 180) / Math.PI) % 360); document.getElementById("dbgFps").textContent = `FPS: ${currentFps}`; document.getElementById("dbgTps").textContent = `TPS: ${this.serverTps}`; document.getElementById("dbgPing").textContent = `Ping: ${this.pingMs} ms`; document.getElementById("dbgCoords").textContent = `XYZ: ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)} | Yaw: ${deg}°`; } this.renderer.render(this.scene, this.camera); requestAnimationFrame(loop); }; requestAnimationFrame(loop); } } window.addEventListener("DOMContentLoaded", () => { new GTACoszalinaGame(); }); })(); """) def main() -> int: base_dir = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(__file__)) generate_project(base_dir) print("Wygenerowano wszystkie pliki projektu pomyslnie.") return 0 if __name__ == "__main__": raise SystemExit(main())