蒙娜丽莎的微笑 Ruby实现

这个挺有意思:Ruby 的 UI 库向来不怎么样,所以这里用的 Gosu 这个2d游戏引擎(其实是包装了Gosu 的 Chingu),顺便加了点料。

[代码] mona_lisa.rb

01 #!/usr/bin/env ruby
02 require "chingu"
03  
04 include Gosu
05 include Chingu
06  
07 class MonaLisa < Chingu::Window
08   def initialize
09     super(600550false)
10     self.input = {:esc => :exit}
11     push_game_state(Paint)
12   end
13 end
14  
15 class Pix < Chingu::GameObject
16   traits :velocity
17   def initialize(options)
18     super(options)
19   end
20  
21   def drop
22     if rand(2) == 0
23       @velocity_x = rand(0..2)
24     else
25       @velocity_x = -rand(0..2)
26     end
27     @velocity_y = rand(0..3)
28     @acceleration_y 1
29   end
30  
31   def setup
32     @image = Image["rect.png"]
33   end
34 end
35  
36 class Paint < Chingu::GameState
37  
38   def initialize
39     @ground_y $window.height+20
40     super
41   end
42  
43   def setup
44     super
45     IO.readlines("media/ml").each do |line|
46       arr = line.chomp.split("x")
47       x = arr[0].to_i
48       y = arr[1].to_i
49       w = arr[2].to_i
50       h = arr[3].to_i
51       r = arr[4][0...2].to_i(16)
52       g = arr[4][2...4].to_i(16)
53       b = arr[4][4...6].to_i(16)
54

      pix = Pix.create(:x => x, :y => y, :width => w, :height=> h,

 :color => Color.argb(255, r, g, b))

55     end
56     self.input = { :space => :drop }
57   end
58  
59   def drop
60     Pix.each { |pix| pix.drop }
61   end
62  
63   def update
64     Pix.each do |p|
65       if p.y >= @ground_y
66         slower = p.velocity_y / 3
67         p.velocity_y = -(slower + rand(slower))
68         if rand(2) == 0
69           p.velocity_x = rand(0.4)
70           p.acceleration_x = -(rand(0.05))
71         else
72           p.velocity_x = -rand(0.4)
73           p.acceleration_x = (rand(0.05))
74         end
75       end
76     end
77     super
78   end
79 end
80  
81 MonaLisa.new.show

你可能感兴趣的:(Ruby版,蒙娜丽莎的微笑)