-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJuliet.jl
350 lines (305 loc) · 7.96 KB
/
Juliet.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
__precompile__()
module Juliet
using FiniteStateMachine
using Match
using Compat
include("types.jl")
include("convert.jl")
include("util.jl")
export juliet
function __init__()
println("""
Welcome to Juliet, the Julia Interative Educational Tutor.
Type `juliet()` to get started
""")
# Seed the rng to make testing deterministic
srand(1)
end
"""
Try to use a progess bar - relies on `Atom.jl`
"""
macro tryprogress(ex)
if isdefined(Main, :Atom)
return :(Main.Atom.@progress $ex)
else
return ex
end
end
"""
Get user input in a environment agnostic manner
"""
function getInput()
if isdefined(Main, :Atom)
return Main.Atom.input()
else
return readline()
end
end
courses = Types.Course[]
help = Dict(
"select" => """
HELP:
[Number] -> select course
`!back` -> exit course
`!quit` -> exit Juliet
""",
"lesson" => """
HELP:
`...` -> press [Enter] to continue
[Enter] -> submit answer
`!skip` -> go to next question
`!quit` -> exit lesson
"""
)
"""
Main function to run Juliet
"""
function juliet()
println("""
Welcome to Juliet, the Julia Interative Educational Tutor.
Selct a lesson or course to get started, or type `!help` for information.
""")
choose_lesson(courses)
end
"""
Choose a course, and then choose a lesson
"""
function choose_lesson(courses::Vector{Types.Course})
@match courses begin
[] => begin println("No courses installed - import some packages"); return end
[_] => begin choose_lesson(courses[1]); return end
end
print_options(courses, "Courses:")
input = ""
while (print("> "); input = getInput();
!isa(parse(input), Number) ||
!(0 < parse(Int, input) <= length(courses)))
@match strip(input) begin
"!quit" => return
"!help" => println(help["select"])
_ => println("Invalid selection")
end
end
choose_lesson(courses[parse(Int, input)])
end
"""
Choose a lesson, then complete it
"""
function choose_lesson(course::Types.Course)
@match courses begin
[] => begin println("No lessons in $(course.name) - exiting course"); return end
[_] => begin complete_lesson(course.lessons[1]); return end
end
print_options(course.lessons,
"Lessons in $(course.name) (type `!back` to return to the total list):")
input = ""
while (print("> "); input = getInput();
!isa(parse(input), Number) ||
!(0 < parse(Int, input) <= length(course.lessons)))
@match strip(input) begin
"!quit" => return
"!back" => begin choose_lesson(courses); return end
"!help" => println(help["select"])
_ => println("Invalid selection")
end
end
selection = course.lessons[parse(Int, input)]
complete_lesson(selection)
if selection != last(course.lessons)
println("Continue to next lesson in course? y/n")
while (input = strip(lowercase(getInput()));
!(input in ["yes", "y", "no", "n"]))
println("Invalid selection")
end
if input in ["yes", "y"]
complete_lesson(course.lessons[getindex(course.lessons, selection) + 1])
else return end
end
end
"""
Print a list of options
"""
function print_options(list, message)
if length(list) > 0
println(message)
for (i, el) in enumerate(list)
println(rpad(i, length(string(length(list)))), " - ", el.name)
end
end
end
"""
Go through a lesson's questions
"""
function complete_lesson(lesson::Types.Lesson)
fsm = state_machine(Dict(
"initial" => "continuing",
"final" => "done",
"events" => [
Dict("name" => "ask", "from" => "continuing", "to" => "asking"),
Dict("name" => "next", "from" => ["asking", "hinting"], "to" => "continuing"),
Dict("name" => "reject", "from" => ["asking", "hinting"], "to" => "hinting"),
Dict("name" => "quit", "from" => ["continuing", "asking", "hinting"], "to" => "done")
]
))
println("Starting ", lesson.name)
@tryprogress for (i, question) in enumerate(lesson.questions)
fire(fsm, "ask")
print("$(rpad(i, length(string(length(lesson.questions))))) / $(length(lesson.questions)): ")
ask(question)
while fsm.current == "asking" || fsm.current == "hinting"
input = get_input(question)
@match strip(input) begin
"!skip" => begin fire(fsm, "next"); break end
"!quit" => begin fire(fsm, "quit"); break end
"!help" => begin println(help["lesson"]); continue end
end
if validate(question, input)
fire(fsm, "next")
show_congrats(question)
else
fire(fsm, "reject")
show_hint(question)
end
end
if fsm.current == "done" break end
end
println("Finished ", lesson.name)
end
"""
Get input for a question
"""
function get_input(question)
print("> ")
input = getInput()
# Remove ansii codes
return replace(input, r"\e\[([A-Z]|[0-9])", "")
end
function get_input(question::Types.InfoQuestion)
print("[Press Enter to continue]")
input = getInput()
# Remove ansii codes
return replace(input, r"\e\[([A-Z]|[0-9])", "")
end
"""
Ask a question
"""
function ask(question)
println(question.text)
end
function ask(question::Types.MultiQuestion)
println(question.text)
println("Options:")
for (i, option) in enumerate(question.options)
println(rpad(i, length(string(length(question.options)))), " - ", option)
end
end
function ask(question::Types.FunctionQuestion)
println(question.text)
println("`!submit` to submit file and run tests")
setup_function_file(question)
end
"""
Validate an answer to a question
"""
function validate(question::Types.InfoQuestion, response)
return true
end
function validate(question::Types.SyntaxQuestion, response)
return parse(response) == question.answer
end
function validate(question::Types.FunctionQuestion, response)
if strip(response) != "!submit" return false end
dir = joinpath(homedir(), "Juliet", "FunctionQuestion")
file = joinpath(dir, filename(question))
try
inputs = [pair[1] for pair in question.tests]
expected = [pair[2] for pair in question.tests]
# Use readall instead of readlines because it gives an error on failure
outputs = map(x -> readall(pipeline(`echo $x`, `julia $file`)), inputs)
same = pair -> strip(pair[1]) == strip(pair[2])
println("$(count(x -> x, map(same, zip(outputs, expected))))/$(length(inputs)) tests passed")
return all(same, zip(outputs, expected))
catch ex
@show ex
println("There were errors running your code")
return false
end
end
function validate(question::Types.MultiQuestion, response)
return isa(parse(response), Number) && parse(Int, response) == question.answer
end
"""
Show an encouraging message and a hint
"""
function show_hint(question)
println(rand([
"Oops - that's not quite right",
"Almost there - Keep trying!",
"One more try",
"Hang in there",
"Missed it by that much",
"Close, but no cigar"]))
if length(question.hints) > 0
println("hint: ", rand(question.hints))
end
end
function show_hint(question::Types.FunctionQuestion)
if length(question.hints) > 0
println("hint: ", rand(question.hints))
end
end
"""
Show a congratulatory message
"""
function show_congrats(question)
println(rand([
"You got it right!",
"Great job!",
"Keep up the great work!",
"You're doing great!"]))
end
function show_congrats(question::Types.InfoQuestion) end
"""
Set up the file for a function question
"""
function setup_function_file(question::Types.FunctionQuestion)
dir = joinpath(homedir(), "Juliet", "FunctionQuestion")
mkpath(dir)
file = joinpath(dir, filename(question))
if !isfile(file)
open(file, "w") do f
write(f, question.template)
end
end
try
@compat @static if is_windows()
Util.run(`explorer.exe $file`; whitelist=[1])
elseif is_linux()
run(`xdg-open $file`)
elseif is_apple()
try
run(`open $file`)
catch
run(`open -a TextEdit $file`)
end
end
catch
println(STDERR, "Could not open file: please open `$file` manually")
end
end
"""
Generate a filename for a function question
"""
function filename(question::Types.FunctionQuestion)
description = x -> x[1:min(25, length(x))]
return "$(description(question.text))-$(hash(question)).jl"
end
"""
Register a course with the current session of Juliet
"""
function register(course::Types.Course)
if !in(course, courses)
push!(courses, course)
end
end
end # module