richardoneill.com.au » Articles » Ruby Task

Ruby Task

30 May 2007 Ruby, Programming

Ruby Star Field

Since I'm fairly new to Ruby, I thought it would be a good idea to give myself a trivial programming task.

I decided to create a simple script to generate a star field typical of the DOS gaming era.

To make things a little more challenging, I used a grid to make sure stars were evenly spaced and covered the whole image.

Here's the code:

require 'rubygems'
require 'RMagick'

include Magick

#create the sky
$sky = Image.new(200,200){ self.background_color = "black" }


#define possible star colours
$colours = [white, grey, blue, pink, yellow]


#define the create star function
def draw_star(x, y)
$sky.pixel_color(x, y, $colours[rand($colours.length)])
end


#define starting coordinates
x = 0
y = 0


#define starting block
block = 0



while block < 100

#define random coordinates for the star in the block
rand_x = x + rand(20)
rand_y = y + rand(20)


#draw the star
draw_star(rand_x, rand_y)


#move the x coodinate position to the next block
x += 20


#check if its the last block on the row
if block % 10 == 0
y += 20
x = 0
end


#next block
block += 1

end

#create the image
$sky.write("sky.jpg")

And here is the output:

Ruby Sky

Comment on this article
Name
Website
Canberra Web Design