Menu
Coddy logo textTech

Manejo de movimientos no válidos

Parte de la sección Logic & Flow del Journey de Lua de Coddy — lección 30 de 54.

challenge icon

Desafío

Fácil

Agrega manejo de errores al sistema de movimiento para proporcionar retroalimentación cuando el jugador ingrese una dirección inválida.

Se te proporcionan las variables startingRoom, gardenRoom y player del desafío anterior.

Modifica el bucle del juego para manejar comandos de movimiento inválidos:

  • Conecta las habitaciones usando salidas north/south: establece startingRoom.exits["north"] como gardenRoom, y gardenRoom.exits["south"] como startingRoom
  • Imprime la descripción de la habitación actual del jugador
  • Imprime el prompt "> " (signo de mayor que seguido de un espacio) sin un salto de línea
  • Lee el comando del usuario usando io.read()
  • Verifica si el comando coincide con una clave en la tabla exits de la habitación actual
  • Si coincide, actualiza player.currentRoom a la habitación almacenada en esa salida
  • Si el comando no coincide con ninguna salida y no es "quit", imprime "You can't go that way."
  • Si el comando es "quit", establece gameRunning en false para salir del bucle

El bucle debe continuar hasta que el usuario escriba "quit".

Formato de salida esperado:

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.
> 

Pruébalo tú mismo

-- 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

Todas las lecciones de Logic & Flow