Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 84 additions & 25 deletions game-server/src/game/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,18 @@ function updateWormRotation(worm: Worm, targetDirection: { x: number; y: number
}
}

/**
* 지렁이의 경로 기록을 초기화합니다.
*/
export function initializePositionHistory(worm: Worm): { x: number; y: number }[] {
// 세그먼트 위치를 역순으로 저장 (과거 → 최신 순서)
return worm.segments.map((s) => ({ x: s.x, y: s.y })).reverse();
}

/**
* 지렁이 머리의 위치를 업데이트합니다.
*/
function updateWormHead(worm: Worm, deltaTime: number): void {
function updateWormHead(worm: Worm, deltaTime: number, positionHistory: { x: number; y: number }[]): void {
const dirX = worm.direction.x;
const dirY = worm.direction.y;
const magnitude = Math.sqrt(dirX * dirX + dirY * dirY);
Expand All @@ -144,27 +152,67 @@ function updateWormHead(worm: Worm, deltaTime: number): void {
head.x += normalizedDirX * speed * deltaTime;
head.y += normalizedDirY * speed * deltaTime;
}

// 머리의 새 위치를 경로 기록에 추가 (배열 끝 = 최신)
const head = worm.segments[0];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

head 상수가 여기서 다시 선언되고 있습니다. if (magnitude > 0) 블록 내에도 동일한 목적의 상수가 선언되어 있어 혼란을 줄 수 있습니다. 함수 상단에서 const head = worm.segments[0];와 같이 한 번만 선언하고 전체 함수에서 재사용하도록 리팩터링하는 것을 권장합니다. 이렇게 하면 코드 가독성이 향상되고 worm.segments[0]에 대한 반복적인 접근을 피할 수 있습니다.

positionHistory.push({ x: head.x, y: head.y });
}

/**
* 지렁이의 몸통 세그먼트들이 머리를 따라오도록 업데이트합니다.
* 지렁이의 몸통 세그먼트들이 머리의 경로를 따라가도록 업데이트합니다.
* 경로 기록을 역순(최신→과거)으로 걸어가며 각 세그먼트를 i × SEGMENT_SPACING 거리 지점에 배치합니다.
*/
function updateWormSegments(worm: Worm): void {
// 세그먼트들 따라오게 하기
for (let i = 1; i < worm.segments.length; i++) {
const prev = worm.segments[i - 1];
const curr = worm.segments[i];

const dx = prev.x - curr.x;
const dy = prev.y - curr.y;
const distance = Math.hypot(dx, dy);

if (distance > GAME_CONSTANTS.SEGMENT_SPACING) {
const moveX = (dx / distance) * (distance - GAME_CONSTANTS.SEGMENT_SPACING);
const moveY = (dy / distance) * (distance - GAME_CONSTANTS.SEGMENT_SPACING);

curr.x += moveX;
curr.y += moveY;
function updateWormSegments(worm: Worm, positionHistory: { x: number; y: number }[]): void {
if (positionHistory.length < 2) return;

let segmentIndex = 1;
let targetDistance = GAME_CONSTANTS.SEGMENT_SPACING;
let accumulatedDistance = 0;

// 경로 기록을 역순(최신→과거)으로 순회
for (let j = positionHistory.length - 1; j > 0 && segmentIndex < worm.segments.length; j--) {
const p1 = positionHistory[j]; // 최신 쪽
const p2 = positionHistory[j - 1]; // 과거 쪽
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const pathSegmentLength = Math.hypot(dx, dy);

// 이 경로 구간 내에 배치할 수 있는 세그먼트가 있는지 확인
while (segmentIndex < worm.segments.length && accumulatedDistance + pathSegmentLength >= targetDistance) {
const remaining = targetDistance - accumulatedDistance;
const t = pathSegmentLength > 0 ? remaining / pathSegmentLength : 0;

worm.segments[segmentIndex].x = p1.x + dx * t;
worm.segments[segmentIndex].y = p1.y + dy * t;

segmentIndex++;
targetDistance = segmentIndex * GAME_CONSTANTS.SEGMENT_SPACING;
}

accumulatedDistance += pathSegmentLength;
}

// 경로가 부족한 경우 남은 세그먼트는 경로의 가장 오래된 위치에 배치
if (segmentIndex < worm.segments.length) {
const lastPoint = positionHistory[0];
for (let i = segmentIndex; i < worm.segments.length; i++) {
worm.segments[i].x = lastPoint.x;
worm.segments[i].y = lastPoint.y;
}
}

// 경로 기록 트리밍 - 필요한 길이 + 여유분만 유지
const maxNeededDistance = worm.segments.length * GAME_CONSTANTS.SEGMENT_SPACING;
let totalDist = 0;
for (let j = positionHistory.length - 1; j > 0; j--) {
totalDist += Math.hypot(
positionHistory[j].x - positionHistory[j - 1].x,
positionHistory[j].y - positionHistory[j - 1].y,
);
if (totalDist > maxNeededDistance + GAME_CONSTANTS.SEGMENT_SPACING * 2) {
// j-1 이전의 기록은 불필요하므로 제거
positionHistory.splice(0, j - 1);
break;
}
}
}
Expand All @@ -176,18 +224,22 @@ function updateSingleWorm(
worm: Worm,
deltaTime: number,
targetDirections: Map<string, { x: number; y: number }>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
// 부드러운 회전 로직 적용
const targetDirection = targetDirections.get(worm.id);
if (targetDirection) {
updateWormRotation(worm, targetDirection, deltaTime);
}

// 머리 위치 업데이트
updateWormHead(worm, deltaTime);
const positionHistory = positionHistories.get(worm.id);
if (!positionHistory) return;

// 머리 위치 업데이트 + 경로 기록 추가
updateWormHead(worm, deltaTime, positionHistory);

// 몸통 세그먼트들 업데이트
updateWormSegments(worm);
// 몸통 세그먼트들 업데이트 (경로 기반)
updateWormSegments(worm, positionHistory);
}

/**
Expand All @@ -204,6 +256,7 @@ export function updateWorld(
foods: Map<string, Food>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
const allWorms = Array.from(worms.values());

Expand All @@ -214,7 +267,7 @@ export function updateWorld(
}

// 개별 지렁이 상태 업데이트
updateSingleWorm(worm, deltaTime, targetDirections);
updateSingleWorm(worm, deltaTime, targetDirections, positionHistories);
}
}

Expand Down Expand Up @@ -294,6 +347,7 @@ function removeDeadPlayer(
playerId: string,
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
const worm = worms.get(playerId);
if (worm && worm.isDead && worm.type === WormType.Player) {
Expand All @@ -302,6 +356,7 @@ function removeDeadPlayer(
// 플레이어 상태 제거
worms.delete(playerId);
targetDirections.delete(playerId);
positionHistories.delete(playerId);
}
}

Expand All @@ -313,15 +368,16 @@ export function handleKilledWorms(
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): string[] {
const removedPlayerIds: string[] = [];

for (const [wormId, worm] of worms) {
if (worm.isDead) {
if (worm.type === WormType.Bot) {
respawnBot(wormId, worms, targetDirections, botMovementStrategies);
respawnBot(wormId, worms, targetDirections, botMovementStrategies, positionHistories);
} else if (worm.type === WormType.Player) {
removeDeadPlayer(wormId, worms, targetDirections);
removeDeadPlayer(wormId, worms, targetDirections, positionHistories);
removedPlayerIds.push(wormId);
}
}
Expand All @@ -335,6 +391,7 @@ function respawnBot(
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
// 기존 봇 데이터 제거
const bot = worms.get(botId);
Expand All @@ -344,6 +401,7 @@ function respawnBot(
worms.delete(botId);
targetDirections.delete(botId);
botMovementStrategies.delete(botId);
positionHistories.delete(botId);

// 새로운 랜덤 타입의 봇 생성
const numericBotTypes = Object.values(BotType).filter((v) => typeof v === "number") as BotType[];
Expand All @@ -356,6 +414,7 @@ function respawnBot(
worms.set(botId, newBot);
targetDirections.set(botId, { x: newBot.direction.x, y: newBot.direction.y });
botMovementStrategies.set(botId, createMovementStrategy(botType));
positionHistories.set(botId, initializePositionHistory(newBot));

console.log(`🤖 Bot ${botId} respawned as type ${botType}`);
}
Expand Down
44 changes: 36 additions & 8 deletions game-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
handleSprintFoodDrop,
handleKilledWorms,
handleMapBoundaryExceedingWorms,
initializePositionHistory,
} from "./game/engine";
import { setupSocketHandlers } from "./socket/handlers";
import { registerWithLobby } from "./lobby/lobbyApi";
Expand Down Expand Up @@ -61,6 +62,7 @@ function initializeBots(
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): Worm[] {
const createdBots: Worm[] = [];

Expand All @@ -72,6 +74,7 @@ function initializeBots(
worms.set(bot.id, bot);
targetDirections.set(bot.id, { x: bot.direction.x, y: bot.direction.y });
botMovementStrategies.set(bot.id, createMovementStrategy(botType));
positionHistories.set(bot.id, initializePositionHistory(bot));

createdBots.push(bot);
}
Expand All @@ -86,6 +89,7 @@ function removeAllBots(
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
const botIds: string[] = [];

Expand All @@ -101,6 +105,7 @@ function removeAllBots(
worms.delete(botId);
targetDirections.delete(botId);
botMovementStrategies.delete(botId);
positionHistories.delete(botId);
}

console.log(`🤖 Removed ${botIds.length} bots - no players online`);
Expand All @@ -114,6 +119,7 @@ function manageBots(
worms: Map<string, Worm>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
playerCount: number,
): Worm[] {
let botCount = 0;
Expand All @@ -126,13 +132,13 @@ function manageBots(
if (playerCount === 0) {
// 서버에 연결된 플레이어가 없으면 모든 봇 제거
if (botCount > 0) {
removeAllBots(worms, targetDirections, botMovementStrategies);
removeAllBots(worms, targetDirections, botMovementStrategies, positionHistories);
}
return [];
} else if (botCount === 0) {
// 플레이어가 있는데 봇이 없으면 봇 생성
console.log(`🤖 Creating bots - ${playerCount} players online`);
return initializeBots(worms, targetDirections, botMovementStrategies);
return initializeBots(worms, targetDirections, botMovementStrategies, positionHistories);
}

return [];
Expand Down Expand Up @@ -168,21 +174,28 @@ function updateAndBroadcastGameState(
foods: Map<string, Food>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): void {
// 봇 관리 (주기적으로 체크) - 새로 생성된 봇들 수집
const newlyCreatedBots = manageBots(worms, targetDirections, botMovementStrategies, io.engine.clientsCount);
const newlyCreatedBots = manageBots(
worms,
targetDirections,
botMovementStrategies,
positionHistories,
io.engine.clientsCount,
);

// 먹이 업데이트 (부족한 먹이 추가)
updateFoods(foods);

// 부활 처리 및 제거된 플레이어 수집
const removedPlayerIds = handleKilledWorms(worms, targetDirections, botMovementStrategies);
const removedPlayerIds = handleKilledWorms(worms, targetDirections, botMovementStrategies, positionHistories);

// 스프린트 중 먹이 떨어뜨리기 처리
handleSprintFoodDrop(worms, foods, deltaTime);

// 지렁이 상태 업데이트
updateWorld(deltaTime, worms, foods, targetDirections, botMovementStrategies);
updateWorld(deltaTime, worms, foods, targetDirections, botMovementStrategies, positionHistories);

// 맵 경계 초과 지렁이 처리
const mapBoundaryExceedingWorms = handleMapBoundaryExceedingWorms(worms, foods);
Expand Down Expand Up @@ -238,6 +251,7 @@ function createGameLoop(
foods: Map<string, Food>,
targetDirections: Map<string, { x: number; y: number }>,
botMovementStrategies: Map<string, MovementStrategy>,
positionHistories: Map<string, { x: number; y: number }[]>,
): () => void {
let lastTickTime = Date.now();

Expand All @@ -246,7 +260,15 @@ function createGameLoop(
const deltaTime = (now - lastTickTime) / 1000;
lastTickTime = now;

updateAndBroadcastGameState(io, deltaTime, worms, foods, targetDirections, botMovementStrategies);
updateAndBroadcastGameState(
io,
deltaTime,
worms,
foods,
targetDirections,
botMovementStrategies,
positionHistories,
);

let nextSleepTime = GAME_CONSTANTS.TICK_MS - (Date.now() - lastTickTime); // 다음 틱까지 대기 시간 계산
if (nextSleepTime < 0) {
Expand Down Expand Up @@ -301,11 +323,17 @@ async function main() {
*/
const botMovementStrategies = new Map<string, MovementStrategy>();

/**
* 각 지렁이의 경로 기록을 저장하는 맵 (path-following용)
* Key: wormId, Value: 경로 기록 배열 (과거 → 최신 순서)
*/
const positionHistories = new Map<string, { x: number; y: number }[]>();

// Socket.IO 이벤트 핸들러 설정
setupSocketHandlers(io, worms, foods, targetDirections);
setupSocketHandlers(io, worms, foods, targetDirections, positionHistories);

// 게임 루프 시작
const gameLoop = createGameLoop(io, worms, foods, targetDirections, botMovementStrategies);
const gameLoop = createGameLoop(io, worms, foods, targetDirections, botMovementStrategies, positionHistories);
gameLoop();

// 서버 종료 시그널 처리
Expand Down
Loading