用Ruby实现动画与硬币系统模拟
立即解锁
发布时间: 2025-08-21 02:25:29 订阅数: 1 


实用Ruby项目:探索编程的无限可能
### 用 Ruby 实现动画与硬币系统模拟
#### 1. Ruby 动画制作
在 Ruby 中,我们可以构建一个强大的动画框架。首先,我们有 `GridDrawer` 类,它为动画绘制提供了基础功能。
```ruby
class GridDrawer
def step
if ! @thread
@thread = Thread.new { self.instance_eval(&@block) }
Thread.pass until @thread.stop?
elsif @thread.alive?
@thread.run
Thread.pass until @thread.stop?
end
return nil
end
def wait
Thread.stop
return nil
end
end
```
这个类不仅提供了 `wait` 方法,还使用 `instance_eval` 来评估代码块,使得代码块可以调用如 `north`、`draw` 和 `wait` 等方法,而无需显式引用对象实例。
为了进一步完善 `GridDrawer`,我们添加了一些辅助方法:
```ruby
class GridDrawer
def pendown
@pen = true
end
def penup
@pen = false
end
def j(x, y, z); jump(x, y, z); end
def jump(x, y, z)
@x, @y, @z = x, y, z
end
def m(xd, yd, zd); move(xd, yd, zd); end
def move(xd, yd, zd)
@x += xd
@y += yd
@z += zd
end
end
```
这些方法允许我们在不留下轨迹的情况下移动绘图光标。我们还为 `jump` 和 `move` 方法提供了单字母简写,这样即使有人使用子类或开放类重新定义主方法,这些简写也会自动更新。
接下来,我们进行第一个动画测试。以下是代码框架:
```ruby
anim = Animation.new(800, 800)
bg = Rect.new(0, 0, "100%", "100%", :fill => "#CCCCCC")
anim.add(bg)
cubes = SortedSVG.new
anim.add(cubes)
griddrawer = GridDrawer.new(cubes, Cube) do
# Do something here!
end
anim.step{ griddrawer.step }
anim.step{ puts anim.frame }
anim.last("animation", 20)
```
我们创建了一个 800x800 的动画,使用矩形类添加了一个中性灰色背景,并创建了一个 `SortedSVG` 容器来保持立方体的顺序,确保前面的立方体不会被后面的立方体遮挡。
`SortedSVG` 类继承自 `SVGObject`,并重写了 `add` 方法以在 3D 空间中对内容进行排序:
```ruby
class SortedSVG < SVGObject
def initialize
super(:g)
end
def add(obj)
@contents.push(obj)
@contents.sort!
return self
end
end
```
同时,我们需要确保 `Cube` 对象有一个比较方法,以便在 3D 顺序中对它们进行排序:
```ruby
class Cube
attr_reader :x, :y, :z
def <=>(other)
return (x + y + z) <=> (other.x + other.y + other.z)
end
end
```
为了节省时间,我们使用 `last` 方法,它会执行所有动画步骤,但只渲染最后一帧:
```ruby
class Animation
def last(dir, frames)
Dir.mkdir(dir) rescue nil
frames.times do |n|
@frame = n
run_callbacks
end
render("#{dir}/last")
end
end
```
我们可以用动画来写一个消息,例如绘制字母 R:
```ruby
griddrawer = GridDrawer.new(cubes, Cube) do
move(5, 4, 0)
draw
north(6)
east(2)
se
south(2)
west(2)
south
se(2)
end
anim.step{ griddrawer.step }
anim.last("animation", 20)
```
为了更好地管理字母绘制代码,我们创建了 `LetterDrawer` 子类:
```ruby
class LetterDrawer < GridDrawer
def r
move(0, 6, 0)
draw
north(6)
east(2)
se
south(2)
west(2)
south
se(2)
move(3, -6, 0)
end
end
```
使用 `LetterDrawer` 来绘制消息:
```ruby
letterdrawer = LetterDrawer.new(Cube, cubes) do
jump(5, -2, 0)
r
u
b
y
jump(17, 8, 0)
r
u
l
e
s
end
anim.step{ letterdrawer.step }
anim.step{ puts anim.frame }
anim.last("animation", 132)
```
以下是动画制作的步骤总结:
1. 创建动画对象和背景。
2. 创建 `SortedSVG` 容器和 `GridDrawer` 或 `LetterDrawer` 对象。
3. 定义动画内容。
4. 执行动画步骤并渲染最后一帧。
#### 2. 动画拼接工具
不同操作系统有不同的动画拼接工具,以下是一些常见的工具及使用方法:
| 工具名称 | 适用系统 | 使用方法 | 注意事项 |
| ---- | ---- | ---- | ---- |
| ImageMagick | 通用 | `convert –delay 25 *.svg ruby.mpg`<br>`convert –delay 25 *.svg ruby.m2v`<br>`convert –delay
0
0
复制全文
相关推荐










