forked from ippa/chingu
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example18_animation_trait.rb
104 lines (86 loc) · 2.49 KB
/
example18_animation_trait.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env ruby
require 'rubygems' rescue nil
$LOAD_PATH.unshift File.join(File.expand_path(__FILE__), "..", "..", "lib")
require 'chingu'
include Gosu
include Chingu
#
# animation-trait example
#
class Game < Chingu::Window
def initialize
super(400, 400)
self.input = { :escape => :exit }
switch_game_state(Play)
end
end
class Play < Chingu::GameState
trait :timer
def setup
Droid.create(:x => 200, :y => 300, :factor => 4, :alpha => 100)
every(1000) { Spaceship.create(:x => 10, :y => 300, :velocity_x => 1) }
every(1000) { Plane.create(:x => 10, :y => 350 + rand(20), :velocity => [1,0]) }
every(500) { FireBullet.create(:x => 10, :y => 370, :velocity_x => 1) }
every(500) { Star.create(:x => 400, :y => 400, :velocity => [-2,-rand*2]) }
every(1400) { Heli.create(:x => 40, :y => 40, :velocity_x => 1) }
end
def update
super
game_objects.select { |game_object| game_object.outside_window? }.each(&:destroy)
$window.caption = "game_objects: #{game_objects.size}"
end
def draw
fill(Gosu::Color::GRAY)
super
end
end
class Actor < GameObject
trait :velocity
def setup
@image = Image["#{self.filename}.png"]
@zorder = 10
end
end
class Spaceship < Actor; end # spaceship.png will be loaded
class Plane < Actor; end # plane.png will be loaded
class FireBullet < Actor; end # fire_bullet.png will be loaded
#
# droid_11x15.png will be loaded and animated with :delay parameter, each frame beeing 11 x 15 pixels
#
class Droid < GameObject
trait :velocity
trait :animation, :delay => 200, :size => [11,15]
def update
@image = self.animation.next if self.animation
end
end
#
# heli.png will be loaded
# since it doesn't contain any framesize information, chingu will assume same width and height
#
class Heli < GameObject
trait :velocity
trait :animation, :delay => 200, :size => [32,32]
def update
@image = self.animation.next if self.animation
end
end
#
# star_25x25_default.png and star_25x25_explode.png will be loaded.
# Access the 2 animation-"states" with self.animations[:default] and self.animations[:explode]
# self.animation will point to self.animations[:default]
#
class Star < Actor
trait :animation, :delay => 100
def setup
self.animations[:explode].loop = false
end
def update
if @x < $window.width/2 || @y < $window.height/2
@image = self.animations[:explode].next
else
@image = self.animations[:default].next
end
end
end
Game.new.show