Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- 20q.lua with extended question count
- local treeFile = "tree.db"
- local monitor = peripheral.find("monitor") or error("No monitor attached!")
- monitor.setTextScale(0.5)
- local function clear(text)
- monitor.clear()
- monitor.setCursorPos(1, 1)
- for line in text:gmatch("[^\n]+") do
- monitor.write(line)
- local _, y = monitor.getCursorPos()
- monitor.setCursorPos(1, y + 1)
- end
- end
- local function loadTree()
- if fs.exists(treeFile) then
- local f = fs.open(treeFile, "r")
- local data = textutils.unserialize(f.readAll())
- f.close()
- return data
- else
- return { question = "Is it a living thing?", yes = { guess = "cat" }, no = { guess = "rock" } }
- end
- end
- local function saveTree(tree)
- local f = fs.open(treeFile, "w")
- f.write(textutils.serialize(tree))
- f.close()
- end
- local function ask(node, count)
- count = count + 1
- if count == 21 then
- clear("You've hit 20 questions!\nContinue? [y/n]")
- if read():lower():sub(1,1) ~= "y" then
- clear("Giving up early? Maybe next time.\nPress Enter.")
- read()
- return node
- end
- end
- if node.guess then
- clear("Is it a " .. node.guess .. "?\n[y]es / [n]o")
- local reply = read()
- if reply:lower():sub(1,1) == "y" then
- clear("Haha! I got it!\nPress Enter.")
- read()
- else
- clear("Darn! What was it?")
- local correct = read()
- clear("Give a question to split " .. correct .. " vs. " .. node.guess)
- local question = read()
- clear("What's the answer for " .. correct .. "? [y/n]")
- local answer = read():lower():sub(1,1)
- local newNode = { question = question }
- if answer == "y" then
- newNode.yes = { guess = correct }
- newNode.no = node
- else
- newNode.no = { guess = correct }
- newNode.yes = node
- end
- return newNode
- end
- else
- clear(node.question .. "\n[y]es / [n]o")
- local reply = read()
- if reply:lower():sub(1,1) == "y" then
- node.yes = ask(node.yes, count)
- else
- node.no = ask(node.no, count)
- end
- end
- return node
- end
- while true do
- local tree = loadTree()
- clear("Think of something...\nPress Enter.")
- read()
- tree = ask(tree, 0)
- saveTree(tree)
- clear("Play again? [y/n]")
- if read():lower():sub(1,1) ~= "y" then break end
- end
Advertisement
Add Comment
Please, Sign In to add comment