Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

معالجة الحركات غير الصالحة

جزء من قسم المنطق والتحكم في التدفق في رحلة Lua على Coddy. الدرس 30 من 54.

challenge icon

التحدي

سهل

أضف معالجة الأخطاء إلى نظام الحركة لتقديم ملاحظات عندما يدخل اللاعب اتجاهاً غير صالح.

لقد تم تزويدك بمتغيرات startingRoom و gardenRoom و player من التحدي السابق.

قم بتعديل حلقة اللعبة (game loop) للتعامل مع أوامر الحركة غير الصالحة:

  • قم بتوصيل الغرف باستخدام مخارج 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 عبر الإنترنت