Menu
Coddy logo textTech

Gestire le mosse non valide

Fa parte della sezione Logica e flusso del percorso Lua di Coddy. Lezione 30 di 54.

challenge icon

Sfida

Facile

Aggiungi la gestione degli errori al sistema di movimento per fornire un feedback quando il giocatore inserisce una direzione non valida.

Ti vengono fornite le variabili startingRoom, gardenRoom e player della sfida precedente.

Modifica il ciclo di gioco per gestire i comandi di movimento non validi:

  • Collega le stanze usando le uscite north/south: imposta startingRoom.exits["north"] su gardenRoom e gardenRoom.exits["south"] su startingRoom
  • Stampa la descrizione della stanza in cui si trova il giocatore
  • Stampa il prompt "> " (segno di maggiore seguito da uno spazio) senza andare a capo
  • Leggi il comando dell'utente usando io.read()
  • Controlla se il comando corrisponde a una chiave nella tabella exits della stanza corrente
  • Se corrisponde, aggiorna player.currentRoom con la stanza memorizzata in quell'uscita
  • Se il comando non corrisponde a nessuna uscita e non è "quit", stampa "You can't go that way."
  • Se il comando è "quit", imposta gameRunning su false per uscire dal ciclo

Il ciclo dovrebbe continuare finché l'utente non digita "quit".

Formato dell'output previsto:

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

Provalo tu

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

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Lua online