Skip to content

Instantly share code, notes, and snippets.

@KeithHanson
Created May 6, 2009 08:02
Show Gist options
  • Save KeithHanson/107429 to your computer and use it in GitHub Desktop.
Save KeithHanson/107429 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'gosu'
include Gosu
class GameWindow < Window
# Word Wrap method shamelessly stolen from: http://www.libgosu.org/cgi-bin/mwf/topic_show.pl?tid=94
def wordwrap(message,width,font)
#split the message into multiple words
word_array = message.split(' ')
#begin the lines array with the first word; this will be an array of strings
lines = [word_array.shift]
#Loop over each word...
word_array.each do |word|
#as long as the line + this word doesn't exceed the width...
if font.text_width("#{lines[-1]} #{word}") < width
#push the word onto the last string in the array with a space
lines[-1] << ' ' << word
else
#otherwise, push the current word onto the next line
lines.push(word)
end
end
return lines
end
def initialize
super(640, 480, false)
self.caption = "Gosu Text Scrolling Example"
#Setup the font to be used
@font = Font.new(self,default_font_name,20)
#Create a long string for wrapping
@message = "Hello and welcome to my very long text string which is also pretty boring and stupid, but oh well I guess there is a time and a place for lorum ipsum, and this was probably it, but I didn't have any handy so we get this crap instead, which is too bad really, because Lorem Ipsum is kinda nice, but oh well, what can you do, other than end this damn string already?"
#Set the margin to be used for the window
@margin = 20
#Set the width of the body of the message
body_width = self.width - 2*@margin
#Generate the wrapped lines
@lines = wordwrap(@message,body_width,@font)
#This will be used to auto-scroll the message
@start = Time.now.to_i
end
def update
end
def draw
#determine the offset of the text and speed at which we scroll
speed = 5
#The offset will be a negative number to pull the text upward per second passed
offset = ( @start - Time.now.to_i ) * speed
#Set the clipping region. We're going to clip 1/7th of the screen height
self.clip_to(0, 0, self.width, self.height / 7) do
#Draw each line
@lines.each_with_index do |line,index|
#determine where this line will be drawn and factor in the offset
height = @margin + (index * @font.height + offset)
#draw the line
@font.draw(line,@margin,height,0)
end
end
end
end
window = GameWindow.new
window.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment