情境排程器

lua-users home
wiki

很久以前,我在名單中發布了一個使用協同程式的簡單合作式多工排程器。這是該排程器的一個變體,應能順利用於簡單模擬和遊戲腳本。

此排程器採用「條件」的概念。協同程式在條件為真時才會排程。當協同程式首次排程時,通常會給予「真」條件,然後在接下來可用的時段執行。然後它可能會在任何時間讓出控制,並在讓出時回傳新的條件。如果沒有回傳此類條件,則不會重新排程協同程式。

預期會包括合適條件的讓出操作,例如 wait()WalkTo() 等輔助程式功能,而腳本寫作者永遠不必擔心明確的讓出。如此會形成一個系統,在特定界限內,會如您預期般運作。

程式碼可在 檔案:wiki_insecure/users/twrensch/play.lua 中找到。

以下是一個範例(也包含在上面的原始檔中)

-- Wait is a function that tells the scheduler to
-- wait for some number of seconds before restarting
-- the script.
function wait(seconds, start)
	local t = (start or os.clock()) + seconds
	coroutine.yield(
		function() return os.clock() >= t end)
end

-- Two pretty much identical functions that differ
-- only in the label they print and the amount of
-- time they wait between prints.
simsch.start(
	function ()
		for i=1,10 do
			wait(1)
			print("One ", i)
		end
	end)

simsch.start(
	function ()
		for i=1,10 do
			wait(1.6)
			print("Two ", i)
		end
	end)
	
-- Start it up
simsch.run()

我想像這在編寫遊戲中的代理腳本時很有用。例如,假設我正在為我的狗 Rover 編寫腳本。我希望他去我家取我的戰斧,然後回來。腳本可能會像這樣

    function Rover:fetchAxe()
        local location = whereAmI(self)
        Rover:walkTo(self.home)
        self:pickup(MyAxe)
        Rover:walkTo(location)
        self:drop()
    end

在此,walkTo() 函式會包含帶有合適條件參數的讓出,以處理路徑和延遲時間。因此,效果會是腳本會花費等同於動作應有的時間(例如,走到家裡,然後走回開始處)的遊戲和/或真實時間來執行。walkTo() 函式的簡單版本可能會簡單地等待一段適合距離和代理速度的時間

    function Agent:walkTo(there)
        local here = whereAmI(self)
        local distance = here:distanceTo(there)
        local arivalTime = now() + distance / self.speed
        coroutine.yield(
	    function() return now() >= arivalTime end)
    end


最近變更 · 偏好設定
編輯 · 記錄
上次編輯於 2004 年 1 月 19 日,下午 8:12,格林威治標準時間 (diff)