File: collision.rb

package info (click to toggle)
ruby-sdl 2.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 4,344 kB
  • ctags: 4,200
  • sloc: cpp: 7,598; ansic: 4,475; ruby: 2,258; sh: 102; makefile: 97
file content (97 lines) | stat: -rw-r--r-- 1,842 bytes parent folder | download | duplicates (4)
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
require 'sdl'

SDL.init( SDL::INIT_VIDEO )
screen = SDL::Screen.open(640,480,16,SDL::SWSURFACE)
SDL::WM::set_caption('collision.rb','collision.rb icon')
$image = SDL::Surface.load_bmp("icon.bmp")
$image.set_color_key( SDL::SRCCOLORKEY ,0)
$image = $image.display_format
$cMap = $image.make_collision_map

class Sprite

  attr_reader :x, :y

  def initialize(screen)
    @screen = screen
    @x=rand(screen.w)
    @y=rand(screen.h)
    @dx=rand(11)-5
    @dy=rand(11)-5
  end
  
  def move
    @x, @dx = move_coord(@x, @dx, xMax)
    @y, @dy = move_coord(@y, @dy, yMax)
  end

  def bounce
    @dx *= -1
    @dy *= -1
    move
  end

  def draw
    SDL::Surface.blit($image,0,0,$image.w,$image.h,@screen,@x,@y)
  end
  
  def collide_with?(sprite)
    $cMap.collision_check(@x, @y, $cMap, sprite.x, sprite.y) != nil
  end

  private

  def move_coord(coord, delta, max)
    coord += delta
    if coord >= max then
      delta *= -1
      coord = max - 1
    end
    if coord < 0 then
      delta *= -1
      coord = 0
    end
    [coord, delta]
  end
  
  def xMax
    @screen.w - $image.w
  end

  def yMax
    @screen.h - $image.h
  end
  
end

def detect_collisions(sprites)
  collisions = []
  for i in (0 ... sprites.size - 1) do
    for j in (i + 1 ... sprites.size) do
      if sprites[i].collide_with?(sprites[j])
        collisions << sprites[i]
        collisions << sprites[j]
      end
    end
  end
  collisions.uniq
end

sprites = (1..8).collect {Sprite.new(screen)}

background = screen.format.map_rgb(64, 64, 64)
while true
  while event = SDL::Event.poll
    case event
    when SDL::Event::KeyDown, SDL::Event::Quit
      exit
    end
  end

  screen.fill_rect(0,0,640,480,background)
  sprites.each {|i| i.move}
  detect_collisions(sprites).each {|i| i.bounce}
  sprites.each {|i| i.draw}
  screen.update_rect(0,0,0,0)
end