טיפול בתנועות לא חוקיות
חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-Lua של Coddy. שיעור 30 מתוך 54.
אתגר
קלהוסף טיפול בשגיאות למערכת התנועה כדי להציג משוב כאשר השחקן מזין כיוון לא חוקי.
המשתנים 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
כל השיעורים ביחידה לוגיקה וזרימת התוכנית
1איטרציה מתקדמת בטבלאות
איטרציה באמצעות pairs()איטרציה באמצעות ipairs()pairs() לעומת ipairs()סיכום – גיליון דמות2פונקציות נוספות של ספריית הטבלאות
table.concat()בניית טבלה ו־unpack()table.sort()מיון מותאם אישית באמצעות פונקציותסיכום – לוח שיאים5פרויקט: מנוע להרפתקת טקסט
הגדרת הפרויקט: החדרקישור בין חדריםתרגלו בעצמכם: קומפיילר Lua אונליין