Menu
Coddy logo textTech

잘못된 이동 처리하기

Coddy Lua 여정의 Logic & Flow 섹션에 포함된 레슨 — 54개 중 30번째.

challenge icon

챌린지

쉬움

플레이어가 잘못된 방향을 입력했을 때 피드백을 제공할 수 있도록 이동 시스템에 에러 핸들링을 추가하세요.

이전 챌린지에서 사용했던 startingRoom, gardenRoom, 그리고 player 변수가 제공됩니다.

잘못된 이동 명령을 처리하도록 게임 루프를 수정하세요:

  • north/south 출구를 사용하여 방들을 연결하세요: startingRoom.exits["north"]gardenRoom으로 설정하고, gardenRoom.exits["south"]startingRoom으로 설정합니다.
  • 플레이어의 현재 방에 대한 설명을 출력합니다.
  • 줄 바꿈 없이 프롬프트 "> " (부등호와 공백 하나)를 출력합니다.
  • io.read()를 사용하여 사용자의 명령을 읽습니다.
  • 명령이 현재 방의 exits 테이블에 있는 키와 일치하는지 확인합니다.
  • 일치하면, player.currentRoom을 해당 출구에 저장된 방으로 업데이트합니다.
  • 명령이 어떤 출구와도 일치하지 않고 "quit"도 아니라면, "You can't go that way."를 출력합니다.
  • 명령이 "quit"이면, gameRunningfalse로 설정하여 루프를 종료합니다.

루프는 사용자가 "quit"을 입력할 때까지 계속되어야 합니다.

예상 출력 형식:

You find yourself in a dusty library filled with ancient books and scrolls.
> 
A hidden garden with overgrown plants and a small fountain.
> 
You can't go that way.
A hidden garden with overgrown plants and a small fountain.
> 
You find yourself in a dusty library filled with ancient books and scrolls.
> 

직접 해보기

-- Room definitions
local startingRoom = {
  description = "You find yourself in a dusty library filled with ancient books and scrolls.",
  exits = {}
}

local gardenRoom = {
  description = "A hidden garden with overgrown plants and a small fountain.",
  exits = {}
}

-- Set exits using east / west
startingRoom.exits = {
  east = gardenRoom
}

gardenRoom.exits = {
  west = startingRoom
}

-- Player
local player = {
  currentRoom = startingRoom
}

-- Game loop
local gameRunning = true

while gameRunning do
  print(player.currentRoom.description)
  io.write("> ")
  local command = io.read()

  if command == "quit" then
    gameRunning = false
  elseif player.currentRoom.exits[command] then
    player.currentRoom = player.currentRoom.exits[command]
  end
end

Logic & Flow의 모든 레슨