Sha256: b048586738cb7961a5cc4e4003f0a9766358f319215ee2e3da4d6fb1359ec48c

Contents?: true

Size: 1.97 KB

Versions: 6

Compression:

Stored size: 1.97 KB

Contents

require 'ruby-processing'

# Modified from code by Martin. 
# Original 'Color Typewriter' concept by John Maeda. 
# 
# Click on the window to give it focus and press the letter keys to type colors. 
# The keyboard function keyPressed() is called whenever
# a key is pressed. keyReleased() is another keyboard
# function that is called when a key is released.

class KeyboardFunctions < Processing::App

  def setup
  	@num_chars = 26
  	@letter_width, @letter_height = 10, 10  	
  	@x = -@letter_width
  	@y = 0
  	
  	no_stroke
    color_mode RGB, @num_chars
    background @num_chars/2
    
    # Set a gray value for each key
    @colors = []
    @num_chars.times { |i| @colors[i] = color i }
  end
  
  def draw
  	if new_letter?
  		if upcase?
  			fill (key - "A".ord).abs % 255
  			rect @x, @y, @letter_width, @letter_height*2
  		else
  			# clear with letter space with background color
  			fill @num_chars/2
  			rect @x, @y, 			    @letter_width, @letter_height
  			
  			fill (key - "a".ord).abs % 255
  			rect @x, @y+@letter_height, @letter_width, @letter_height
  		end
  		@new_letter = false
  	end
  end
  
  def new_letter?
  	@new_letter
  end
  
  def upcase?
  	@upcase
  end
  
  def key_pressed
  	# Try to get a String for int value in "key"
  	key_char = nil
  	key_char = key.chr rescue nil
  	
  	# if the key is between 'A'(65) and 'z'(122)
  	if key_char && key_char >= "A" && key_char <= "z"
  		if key_char <= "Z"
  			@upcase = true
  		else
  			@upcase = false
  		end
  	end
  	@new_letter = true
  	
  	# Update the "letter" position and 
  	# wrap horizontally and vertically
  	@y += (@letter_height*2) if @x + @letter_width >= width
  	@y = @y % height
  	@x += @letter_width
  	@x = @x % width
  end
  
end

# A fix for Ruby 1.8 that adds String.ord of Ruby 1.9
class String
	unless method_defined? "ord"
		def ord
			self[0] # return character code point of first character
		end
	end
end

KeyboardFunctions.new :title => "Keyboard Functions", :width => 200, :height => 200

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ruby-processing-1.0.4 samples/processing_app/basics/input/keyboard_functions.rb
ruby-processing-1.0.3 samples/processing_app/basics/input/keyboard_functions.rb
ruby-processing-1.0.5 samples/processing_app/basics/input/keyboard_functions.rb
ruby-processing-1.0.6 samples/processing_app/basics/input/keyboard_functions.rb
ruby-processing-1.0.7 samples/processing_app/basics/input/keyboard_functions.rb
ruby-processing-1.0.8 samples/processing_app/basics/input/keyboard_functions.rb