Menu
Coddy logo textTech

הצגת היציאות

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

challenge icon

אתגר

קל

שפרו את חוויית המשתמש במשחק על ידי הצגת כל היציאות הזמינות לשחקן לאחר הצגת תיאור החדר.

המשתנים startingRoom, gardenRoom ו-player מהאתגר הקודם זמינים לכם.

שנו את לולאת המשחק כך שתציג את היציאות הזמינות:

  • הדפיסו את תיאור החדר שבו השחקן נמצא כעת
  • הדפיסו "Exits:" בשורה חדשה
  • השתמשו ב-pairs() כדי לעבור על טבלת ה-exits של החדר הנוכחי
  • עבור כל יציאה, הדפיסו " - " (שני רווחים, מקף ורווח) ואחריו את שם הכיוון
  • הדפיסו את ההנחיה "> " (סימן גדול מ- ואחריו רווח) בלי לרדת שורה
  • קראו את פקודת המשתמש באמצעות 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.
Exits:
  - east
> 
A hidden garden with overgrown plants and a small fountain.
Exits:
  - west
> 
You can't go that way.
A hidden garden with overgrown plants and a small fountain.
Exits:
  - west
> 
You find yourself in a dusty library filled with ancient books and scrolls.
Exits:
  - east
> 

נסו בעצמכם

-- 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 = {}
}

-- Connect rooms
startingRoom.exits["north"] = gardenRoom
gardenRoom.exits["south"] = 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]
    else
        print("You can't go that way.")
    end
end

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

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