Skip to content

Instantly share code, notes, and snippets.

@Sephi-Chan
Created August 5, 2011 10:34
Show Gist options
  • Save Sephi-Chan/1127281 to your computer and use it in GitHub Desktop.
Save Sephi-Chan/1127281 to your computer and use it in GitHub Desktop.
ig
.module('game.main')
.requires(
'impact.game'
'impact.font'
)
.defines ->
mockGame = ig.Game.extend
computeTexts: (texts, parameters)->
compiledText = {}
@font = new ig.Font("media/#{parameters.font}")
@width = parameters.width
@height = parameters.height
for own index, text of texts
compiledText[text.key] = @computeText(text.value)
compiledText
computeText: (text)->
new Texter(text, @font, @width, @height)
ig.main("#canvas", mockGame, 1, 0, 0, 1)
window.Texter = ig.Class.extend
init: (@text, @font, @width, @height, @lineHeight = 10)->
@linesPerScreen = Math.floor(@height / @lineHeight)
@lines = @textToLines(text)
@screens = @linesToScreens(@lines)
@screenIndex = 0
# Return an array of lines.
# Lines are strings that fit the @width limit.
textToLines: (text = "")->
linesCount = 0
lines = []
paragraphs = text.split("\n")
for paragraph in paragraphs
words = paragraph.split(' ')
line = ""
lineWidth = 0
newLine = true
for word, index in words
# A new paragraph.
if word == ''
lines.push('')
continue
if newLine
lines.push(line) if line != ''
line = ""
lineWidth = 0
wordToAppend = word
else
wordToAppend = " #{word}"
wordWidth = @font.widthForString(wordToAppend)
line += wordToAppend
lineWidth += wordWidth
# Prepare a new line if the next word and its space
# are not going to fit.
nextWord = words[index + 1]
if nextWord
nextWordWidth = @font.widthForString(" #{nextWord}")
enoughPlaceForNextWord = (lineWidth + nextWordWidth) <= @width
newLine = !enoughPlaceForNextWord
else
lines.push(line)
lines
# Return an array of screens.
# Screens are arrays of strings and contain @linesPerScreen lines,
# except the last one which contains 1 to @linesPerScreen lines.
linesToScreens: (lines)->
in_groups_of(lines, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment