This is an old version, there's a new one at the bottom of this post
// -- Typewriter class --
import "chars"
import "stringUtil"
typewriter = {"ended": true, "skip": false}
typewriter.snd = new Sound
typewriter.txtDisp = display(3)
typewriter.canSkip = true
// This should be called only once.
// Once called it will start typing the text in x, y coords
typewriter.setText = function(text, x, y, delay, color, note=90, clear=true)
self.ended = false
self.skip = false
if clear then
self.txtDisp.clear
end if
// Make the text fit the screen adding new lines
text = text.wrap(68-x-2).join(chars.returnKey)
initialX = x
for i in text.indexes
// x coord should go back to the initial value when a new line is found
if text[i] == chars.returnKey then
x = initialX - i - 1
y = y - 1
continue
end if
self.txtDisp.setCellColor x+i, y, color
self.txtDisp.setCell x+i, y, text[i]
// User wants to skip text typing
if key.pressed("space") and self.canSkip then
// Wait for key to be released
// TOFIX: This makes the text typing to stop
// until the user releases the key...
while key.pressed("space")
end while
self.skip = true
end if
if not self.skip then
// Periods and commas must have a little more delay
if text[i] == "." then
wait delay+0.5
else if text[i] == "," then
wait delay+0.2
else
// Don't play the sound on spaces
if text[i] != " " then
self.snd.init(0.05, noteFreq(note))
self.snd.play(0.01)
end if
wait delay
end if
end if
end for
self.ended = true
end function
// -- End of typewriter class --
globals.Typewriter = typewriter
As the code says, there's a bug when the user press and holds the space key, the typing freezes until the user releases the key. There must be a better way of checking when the user pressed and released a key without stopping the for loop...
https://gist.github.com/Intasx/0f7f8d0fbdd4f49f4bd42ec782eaeb0c
Fixed the key bug, renamed most of the variables and added an optional parameter playSound
which is a function that can either play a sound generated by miniscript or an external sound, among other things.