본문 바로가기

이노베이션캠프/TIL

이노베이션 캠프 5일차_무한 루프 로비 화면


배틀 종료 후 바로 로비로 넘어가는 문제 해결

✅ 문제 상황

  • 과제 게임 개발 중.
  • startGame() 함수에서 배틀(SceneManager.battle())이 끝난 후,
    플레이어와 몬스터의 체력 상태에 따라 게임 진행 여부를 판단하려 했음.
  • 하지만 배틀이 끝난 뒤, 스테이지 클리어 조건(if문)이 실행되지 않고 바로 로비로 넘어가는 현상이 발생.

 

✅ 원인 분석 과정

● 배틀 함수 내부 구조 점검

while (player.hp > 0) {
  // 배틀 루프
  ...
  if (monster.hp <= 0) break;
}

 

→ 배틀 함수는 몬스터 체력이 0 이하면 정상적으로 빠져나옴.

 

● startGame 함수 흐름 점검

await SceneManager.battle(stage, player, monster);

// 스테이지 클리어 및 종료 조건
if (player.hp <= 0 && monster.hp > 0) {
  ...
} else if (player.hp > 0 && monster.hp <= 0) {
  ...
}

 

→ SceneManager.batlle() 하는 부분에 디버깅을 찍었는데, if문에 들어가지 않는 현상을 확인함.

 

✅ 원인 분석

  • 핵심 문제는 비동기 흐름을 기다리지 않고 무한 루프를 계속 돌아서 발생하는 문제였음.
export function start() {
  while (true) {
    SceneManager.displayLobby();
    SceneManager.handleUserInput();  // 여기에 startGame이 있음
  }
}

 

export async function startGame() {

    ...
  
  while (stage <= 10) {

    await SceneManager.battle(stage, player, monster);
    
    ...
    
  }
}

 

→ handleUserInput 안에서 비동기 함수(startGame) 실행 → 하지만 여기서 await 안 함. 그래서 start() 안의 while (true) 루프가 handleUserInput() 끝날 때까지 기다리지 않고 계속해서 다음 루프로 넘어가서 다시 로비를 출력해버림.

 

흐름 단계 설명
1 start()에서 while(true)로 무한 루프
2 SceneManager.displayLobby() → 로비 화면 출력
3 SceneManager.handleUserInput() → 여기서 startGame() 실행
4 startGame()은 비동기(async) 함수인데, handleUserInput()이 이걸 기다리지 않음
5 handleUserInput()이 동기적으로 즉시 끝난 후 → start()는 다음 while 루프로 넘어감
6 start()가 while 루프를 계속 돌아서 로비 화면이 계속 출력됨
7 startGame() 내부 흐름은 정상 작동 중인데, 화면은 이미 다시 로비로 넘어가버림

 

✅ 해결

export async function start() {
  while (true) {
    SceneManager.displayLobby();
    await SceneManager.handleUserInput();  // 비동기 기다리기!
  }
}
export async function handleUserInput() {
  // ... 유저 입력 받고
  if (choice === '1') {
    await startGame();  // 반드시 await
  }
}

 

  • start()를 async로 변경 후 await 추가.
  • handleUserInput도 async로 바꾸고 startGame() 호출 시 await 사용.