Skip to content

Instantly share code, notes, and snippets.

@dru
Created May 9, 2012 07:54
Show Gist options
  • Save dru/2642796 to your computer and use it in GitHub Desktop.
Save dru/2642796 to your computer and use it in GitHub Desktop.
Rotate board puzzle
require 'rubygems' # sudo gem install gosu --no-ri --no-rdoc
require 'gosu'
class Board < Array
def rotate cw = false
rotated = if cw
transpose.map(&:reverse)
else
transpose.reverse
end
replace rotated.map(&:compact).map{|l| l.fill(nil, l.length..self.length-1)}
flatten.compact.each{|s| s.to_angle = cw ? 90 : -90 }
end
def render
each_with_index{|i, x| i.reverse.each_with_index{|s, y| s.render x, y if s }}
end
end
class Stone < Gosu::Image
attr_accessor :to_angle
def initialize w, stone
super w, stone, true
@my_angle, @to_angle, @x, @y, @x_r, @y_r = 0, 0, 0, 0, 0, 0, 0
@animation_speed, @center, @size = 0.3, 140, 64
end
def render x, y
if (@to_angle - @my_angle).abs < @animation_speed
@x_r += @animation_speed * (x-@x_r)
@y_r += @animation_speed * (y-@y_r)
@x, @y = @x_r, @y_r
@my_angle = @to_angle = 0
else
@my_angle += @animation_speed * (@to_angle - @my_angle)
f = @my_angle * (Math::PI/180.0)
cos = Math.cos(f); sin = Math.sin(f)
@x_r = ((@x - 2.0) * cos - (@y - 2.0) * sin) + 2.0
@y_r = ((@y - 2.0) * cos + (@x - 2.0) * sin) + 2.0
end
draw_rot @x_r * @size + @center, @y_r * @size + @center, 0, 0
end
end
class Game < Gosu::Window
def initialize
super 640, 480, false
@board = Board.new.replace [[ Stone.new(self, "gem.png"), nil, Stone.new(self, "gem.png"), Stone.new(self, "gem.png"),Stone.new(self, "gem.png")],
[ nil, Stone.new(self, "gem.png"), nil, nil, Stone.new(self, "gem_blue.png")],
[ nil, nil, Stone.new(self, "gem_blue.png"), nil, nil],
[ Stone.new(self, "gem_blue.png"), nil, Stone.new(self, "gem_blue.png"), nil, nil],
[ nil, nil, nil, Stone.new(self, "gem_blue.png"), nil]
].transpose
end
def draw
@board.render
end
def button_down key
case key
when Gosu::KbLeft then @board.rotate(true)
when Gosu::KbRight then @board.rotate(false)
end
end
end
Game.new.show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment