#!/usr/bin/lua local app = {} local fmt = string.format local write = io.write local exam = {} local color = { NoColor = 0, Black = 30, Red = 31, Green = 32, Brown = 33, Blue = 34, Purple = 35, Cyan = 36, LightGray = 37 }; function setColor(color, light) if color == 0 then write('\x1B[0m'); elseif light then write(fmt('\x1B[1;%dm', color)); else write(fmt('\x1B[0;%dm', color)); end end --exam.__index = exam function exam:new() local n = {} setmetatable(n, exam) exam:init() return n end function exam:init() self.start = os.time() self.finished = 0 self.correct = 0 self.wrong = 0 end local minVal = 0; local maxVal = 20; function getVal(notZero) local v = math.random(minVal, maxVal) while notZero and v == 0 do v = math.random(minVal, maxVal) end return v; end function exam:getQuestion() qt = math.random(1,3) x = getVal() y = getVal() if (qt == 1) then q = fmt("# %d + %d = ?", x, y) a = x + y elseif (qt == 2) then q = fmt("# %d - %d = ?", x, y) a = x - y elseif (qt == 3) then q = fmt("# %d * %d = ?", x, y) a = x * y elseif (qt == 4) then y = getVal(true) q = fmt("# %d / %d = ?", x, y) a = x / y end return q, a end function exam:finish() self.finished = os.time() end function exam:printResults() local diff = os.difftime(self.finished, self.start) write( fmt("Exam time: %d sec.\n", diff) ) write( fmt("%f sec. per correct answer\n", diff / self.correct)) write( fmt("%d total, %d correct, %d wrong\n", self.correct+self.wrong, self.correct, self.wrong) ) end function app.main() math.randomseed(os.time()) local myExam = exam:new() repeat local q, a = exam:getQuestion() write(q, "\n") answerStr = io.read() answer = tonumber(answerStr) if (answer) then if (answer >= a - 0.01 and answer <= a + 0.01) then setColor(color.Green); write("Correct!\n") exam.correct = exam.correct + 1 else setColor(color.Red); write("Wrong, correct answer: ", a,"\n") exam.wrong = exam.wrong + 1 end setColor(color.NoColor); write(string.rep("-", 30), "\n") end until answerStr == "" exam:finish() exam:printResults() end app.main()
25200cookie-checkLua math questions