require "test/unit" class LCD attr_reader :display def initialize(digit, width=4) @display = Array2D.new(width, width, '.') @width = width end def to_s "LCD:\n#{@display.to_s}" end def show_digit(digit) @display.clear('0') if digit.eql? 1 draw_vertical_line(0, 0, @width-1) else puts "digit is not 1" end end def draw_vertical_line(x, from_y, to_y) for i in from_y..to_y @display[x, i] = "|" end end def draw_horizontal_line(from_x, to_x, y) for i in from_x..to_x @display[i, y] = "-" end end end class Array2D attr_reader :w, :h def initialize(w, h, default=nil) @w, @h = w, h @array = Array.new(w*h, default) end def [](x, y) check_bounds(x, y) @array[ y*w + x ] end def []=(x, y, v) check_bounds(x, y) @array[ y*w + x] = v end def check_bounds( x, y ) if ((0 > x or x >= @w ) or ( 0 > y or y >= @h )) raise "Index out of bounds for #{x}, #{y}" end end def to_s s = '' for r in 0..(h-1) for c in 0..(w-1) s += self[c,r].to_s end s += "\n" end s end def clear( reset_to_value = nil ) @array.fill( reset_to_value ) end end class TC_testArray2D < Test::Unit::TestCase def testStuff a = Array2D.new(27, 33) assert 27.eql?(a.w),"expected width of 27" assert 33.eql?(a.h), "expected height of 0" end def testDefaults a = Array2D.new(27, 33, 213) assert a[0, 0].eql?( 213 ) , "Expected value of 0, 0, to be the defalt value I passed in." assert a[0, 13].eql?( 213 ) , "Expected value to be the defalt value I passed in." assert a[21, 13].eql?( 213 ) , "Expected value to be the defalt value I passed in." assert_raise RuntimeError do assert a[44, 44].eql?( nil ), "Expected out of bounds access to give nil" end assert_raise RuntimeError do assert a[-1, 0].eql?(nil), "Expected out of bounds access to give nil" end assert_raise RuntimeError do assert a[0, 177].eql?(nil), "Expected out of bounds access to give nil" end end def testNilDefaults a = Array2D.new(27, 33) assert a[0, 13].eql?( nil ) , "Expected value to be nil, the default default value." end def testPutting a = Array2D.new( 71, 21, 0 ) a[1, 1]= 13; assert a[1, 1].eql?(13) a[12, 19]=888 assert a[12,19].eql?(888) a[19, 12]=55 assert a[19,12].eql?(55) assert a[12,19].eql?(888) # make sure we didn't overwrite the value at 12, 19 assert_raise RuntimeError do a[77, 109]=27 end assert_raise RuntimeError do a[-77, 109]=27 end end def testClearing a = Array2D.new( 71, 21, 0 ) a[1, 1]= 13; assert a[1, 1].eql?(13) a[12, 19]=888 assert a[12,19].eql?(888) a[19, 12]=55 assert a[19,12].eql?(55) a.clear() for x in 0..70 for y in 0..20 assert a[x,y].eql?(nil) end end end def testClearingToValue a = Array2D.new( 10, 4, 'A' ) assert a[1,1].eql?('A') assert a[0,3].eql?('A') a.clear('B') assert a[1,1].eql?('B') end def testOne d = LCD.new(3, 4) d.show_digit(1) puts "yo yo this should be 1" puts d d.show_digit(27) puts d end end # main