-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.scala
272 lines (223 loc) · 7.08 KB
/
start.scala
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
:power
Console.setIn(new jline.ConsoleReaderInputStream(new jline.ConsoleReader))
object state_ {
var i = 0
var level = 1
var prompts: List[Prompt] = Nil
var local = false
val rand = new scala.util.Random
val (id, secret) = findOrGetId()
val baseUrl = "http://www.scalacademy.com/%%s?id=%d&secret=%d".format(id, secret)
def cleanTypeName(t: String) = t.replaceAll("scala.collection.immutable.", "").replaceAll("java.lang.", "")
def hasType[T: Manifest](ident: String) = repl.typeForIdent(ident).exists(t => cleanTypeName(t) == cleanTypeName(implicitly[Manifest[T]].toString))
def hasTypeStr(ident: String, typ: String)(unused: String) = repl.typeForIdent(ident).exists(t => cleanTypeName(t) == cleanTypeName(typ))
def hasTypeFn(ident: String, args: String, ret: String)(unused: String) = {
val ok = hasTypeStr(ident, args+ret)(unused)
if (!ok) {
println("Oh no, I expected %s to be a function with arguments %s and return type %s!".format(ident, args, ret))
}
ok
}
def cond[T: Manifest](pred: T => Boolean)(ident: String) = {
val vOpt = repl.interpretExpr(ident)
vOpt.isDefined && vOpt.get.isInstanceOf[T] && pred(vOpt.get.asInstanceOf[T])
}
def hasValue[T: Manifest](v: T)(ident: String) = cond((x: T) => x == v)(ident)
def declared[T: Manifest](ident: String, v: T)(unused: String) = hasValue[T](v)(ident)
def declared[T: Manifest](ident: String)(unused: String) = hasType[T](ident)
def eval[T: Manifest](exp: String, expected: T)(unused: String) = {
val vOpt = repl.interpretExpr(exp)
vOpt.isDefined && {
val actualStr = vOpt.get.asInstanceOf[T].toString
val expectedStr = expected.toString
if (actualStr == expectedStr) {
println("%s = %s. Good!".format(exp, actualStr))
} else {
println("%s = %s. Oops! Should be '%s'!".format(exp, actualStr, expectedStr))
}
actualStr == expectedStr
}
}
def evalIO[T: Manifest](exp: String, expectedOut: String, in: String = "")(unused: String) = {
val os = new java.io.ByteArrayOutputStream
val is = new java.io.ByteArrayInputStream(in.getBytes("UTF-8"))
Console.withOut(os) {
Console.withIn(is) {
repl.interpretExpr(exp)
}
}
val actualOut = os.toString.trim
if (actualOut == expectedOut) {
println("%s outputs '%s'. Good!".format(exp, actualOut))
} else {
println("%s outputs '%s'. Oops! Should be '%s'!".format(exp, actualOut, expectedOut))
}
actualOut == expectedOut
}
var lastVar = "res0"
case class Prompt(prompt: List[String], checks: List[String]) {
def check() = {
lastVar = repl.mostRecentVar
checks.forall(c => {
val cmd = "state_."+c+"(\""+lastVar+"\")"
repl.interpretExpr(cmd).get.asInstanceOf[Boolean]
})
}
def show() = {
prompt.foreach(p =>
println(p.format(lastVar)
.replaceAll("<<", Console.BOLD)
.replaceAll(">>", Console.RESET)))
}
}
def eol() {
println("""You are now a Level %d Scala Coder! To move up to the next level, type 'next' and hit enter.
If you want to stop now and come back later, type ':quit' to exit. When you come back,
type 'level(%d)' instead of 'start'.
At any time you can type 'help' for help remembering what each command does.""".format(level, level+1))
}
def show() {
if (i > 0 && i < prompts.length) println("%s %d/%d [Lvl %d] ---\n".format("-"*81, i+1, prompts.length, level))
if (i < prompts.length) curr.show() else eol()
}
def parse(lines: List[String]): List[Prompt] = {
if (lines.isEmpty) Nil
else {
val first = lines.takeWhile(_ != "===")
val rest = lines.drop(first.length+1)
val text = first.takeWhile(_ != "---")
val checks = first.drop(text.length+1)
Prompt(text, checks) :: parse(rest)
}
}
def loadUrl(url: String) = {
val stream = new java.net.URL(url).openConnection.getInputStream
val scan = new java.util.Scanner(stream)
def allLines(s: java.util.Scanner): List[String] = if (s.hasNext) s.nextLine :: allLines(s) else Nil
allLines(scan)
}
def loadFile(file: String) = {
scala.io.Source.fromFile(file).getLines.toList
}
def loadLevel(l: Int) {
level = l
prompts = parse(if (local) loadFile("levels/"+l) else loadUrl("https://raw.github.com/jliszka/scalacademy/master/levels/"+l))
i = 0
}
def findOrGetId() = {
import java.io.{File, PrintWriter}
val idFile = new File("id")
if (idFile.exists) {
val parts = loadFile("id").mkString("").trim.split(":")
(parts(0).toInt, parts(1).toInt)
} else {
val secret = math.abs(rand.nextInt() % 10000000)
val id = loadUrl("http://www.scalacademy.com/id?secret="+secret).mkString("").trim.toInt
val p = new PrintWriter(idFile)
p.println(id+":"+secret)
p.close()
(id, secret)
}
}
def nextLevel() {
level = level + 1
loadLevel(level)
}
def restartLevel() {
i = 0
}
def curr = prompts(i)
def next() {
i = i + 1
}
def sendProgress(correct: Boolean) {
if (!local) {
try {
val c = if (correct) 1 else 0
val url = "%s&level=%d&step=%s&correct=%d".format(baseUrl.format("inc"), level, i, c)
new java.net.URL(url).openConnection.getInputStream
} catch {
case e =>
}
}
}
def resume() {
val url = baseUrl.format("last")
val parts = loadUrl(url).mkString("").trim.split(":")
level = parts(0).toInt
loadLevel(level)
i = parts(1).toInt + 1
}
def check() {
if (i >= prompts.length) {
nextLevel()
show()
} else if (curr.check()) {
sendProgress(true)
next()
show()
} else {
sendProgress(false)
println()
println("Oops, try again!")
}
}
def progress() {
println("You are on prompt %d of %d.".format(i+1, prompts.length))
}
}
def ok {
state_.check()
}
def start {
state_.loadLevel(1)
state_.show()
}
def level(l: Int) {
state_.loadLevel(l)
state_.show()
}
def next {
state_.nextLevel()
state_.show()
}
def restart {
state_.restartLevel()
state_.show()
}
def repeat {
state_.show()
}
def progress {
state_.progress()
}
def resume {
state_.resume()
state_.show()
}
def help {
println("""
Using Scalacademy
-------------------------
ok Check your work and move on to the next prompt.
repeat Repeat the current prompt.
level(n) Jump to level n, e.g., level(3).
next Jump to the next level.
restart Restart the current level.
progress Show how far along you are in this level.
resume Resume from where you last left off (progress is
saved automatically -- although definitions you made
in the console are not).
help This help message.
:quit Leave the program. When you return to Scalacademy
you can pick up where you left off by typing 'resume'.
:load file Read in the contents of a file as if you had
typed it.
For more help, tweet at @scalacademy on twitter!
""")
}
println("""
Welcome to Scalacademy!
To get started, type 'start' at the 'scala>' prompt below and hit enter.
Type 'help' at any time for help using Scalacademy.
""")