Menu
Coddy logo textTech

טיפול בתנועות לא חוקיות

חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-Lua של Coddy. שיעור 30 מתוך 54.

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", הגדר את gameRunning ל-false כדי לצאת מהלולאה

הלולאה צריכה להימשך עד שהמשתמש מקליד "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

כל השיעורים ביחידה לוגיקה וזרימת התוכנית

תרגלו בעצמכם: קומפיילר Lua אונליין