NumberGuess

Oct 24th, 2017
196
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. os.pullEvent = os.pullEventRaw
2. print ("Please enter a lower number for number of digits")
3. local default_length = 4
4. local cheat = false
5.
6. local function numberToTable(num)
7. if not num or not tostring(num) then
8. error("Input should be a number")
9. end
10. local str = tostring(num)
11. local tbl = {}
12. for i=1,#str do
13. table.insert(tbl,string.sub(str,i,i))
14. end
15. return tbl
16. end
17.
19. --local w,h = term.getSize()
20. --print(string.rep("=",w))
21. print(str)
23. --write(string.rep("=",w))
24. return num
25. end
26.
27. local function getNumberToGuess(length)
28. length = tonumber(length) or default_length
29. if not type(length) == "number" then
30. error("Length of number to guess should be a number.")
31. end
32. local num = math.random(math.pow(10,length-1), math.pow(10,length)-1)
33. if cheat then
34. print("Number to guess is: " .. tonumber(num))
35. end
36. return numberToTable(num)
37. end
38.
39. local function getCorrectCount(correct, num)
40. local toCompare = numberToTable(num)
41. if(#toCompare ~= #correct) then
42. return nil
43. end
44. local count = 0
45. for i=1,#toCompare do
46. if(toCompare[i] == correct[i]) then
47. count = count + 1
48. end
49. end
50. return count
51. end
52.
53. local function printIntro()
54.
55. end
56.
58. local count = nil
59. local guess
60. while not count do
62. count = getCorrectCount(correct, guess)
63. if not count then
64. write("The number should be of length " .. tostring(#correct) .. ". ")
65. end
66. end
67. print(tostring(count) .. " of the ciphers were correct.")
68. return count == #correct
69. end
70.
71. local function main()
72. math.randomseed(os.time()*os.clock())
73. write("How long should the number be? ")
75. local numberToGuess = getNumberToGuess(length)
76. printIntro()
77. local tries = 0