Menu
Coddy logo textTech

Tratando Movimentos Inválidos

Parte da seção Logic & Flow do Journey de Lua da Coddy — lição 30 de 54.

challenge icon

Desafio

Fácil

Adicione tratamento de erros ao sistema de movimento para fornecer feedback quando o jogador inserir uma direção inválida.

Você recebeu as variáveis startingRoom, gardenRoom e player do desafio anterior.

Modifique o loop do jogo para lidar com comandos de movimento inválidos:

  • Conecte as salas usando as saídas north/south: defina startingRoom.exits["north"] como gardenRoom, e gardenRoom.exits["south"] como startingRoom
  • Imprima a descrição da sala atual do jogador
  • Imprima o prompt "> " (sinal de maior que seguido por um espaço) sem uma nova linha
  • Leia o comando do usuário usando io.read()
  • Verifique se o comando corresponde a uma chave na tabela exits da sala atual
  • Se corresponder, atualize player.currentRoom para a sala armazenada nessa saída
  • Se o comando não corresponder a nenhuma saída e não for "quit", imprima "You can't go that way."
  • Se o comando for "quit", defina gameRunning como false para sair do loop

O loop deve continuar até que o usuário digite "quit".

Formato de Saída 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.
> 

Experimente você mesmo

-- 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 as lições de Logic & Flow