Class: Player

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyhop.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(level) ⇒ Player

Returns a new instance of Player.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rubyhop.rb', line 9

def initialize level
  @level = level
  @window = @level.window
  # position
  start!
  @gravity  = -0.25
  @hop      = 7.5
  # sounds
  @sound    = Gosu::Sample.new @window, get_my_file("hop.mp3")
  @gameover = Gosu::Sample.new @window, get_my_file("gameover.mp3")
  # images
  @rise = Gosu::Image.new @window, get_my_file("rubyguy-rise.png")
  @fall = Gosu::Image.new @window, get_my_file("rubyguy-fall.png")
  @dead = Gosu::Image.new @window, get_my_file("rubyguy-dead.png")
end

Instance Attribute Details

#aliveObject

Returns the value of attribute alive.



8
9
10
# File 'lib/rubyhop.rb', line 8

def alive
  @alive
end

#xObject

Returns the value of attribute x.



8
9
10
# File 'lib/rubyhop.rb', line 8

def x
  @x
end

#yObject

Returns the value of attribute y.



8
9
10
# File 'lib/rubyhop.rb', line 8

def y
  @y
end

Instance Method Details

#die!Object



36
37
38
39
40
41
42
43
# File 'lib/rubyhop.rb', line 36

def die!
  if @alive
    # Set velocity to one last hop
    @velocity = 5.0
    @gameover.play
    @alive = false
  end
end

#drawObject



55
56
57
# File 'lib/rubyhop.rb', line 55

def draw
  image.draw @x - 32, @y - 32, 1000 - @x
end

#hopObject



24
25
26
27
28
29
# File 'lib/rubyhop.rb', line 24

def hop
  if @alive
    @sound.play
    @velocity += @hop
  end
end

#imageObject



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rubyhop.rb', line 58

def image
  if @alive
    if @velocity >= 0
      @rise
    else
      @fall
    end
  else
    @dead
  end
end

#start!Object



30
31
32
33
34
35
# File 'lib/rubyhop.rb', line 30

def start!
  @x = @window.width/3
  @y = @window.height/2
  @velocity = 0.0
  @alive = true
end

#updateObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rubyhop.rb', line 44

def update
  @velocity += @gravity
  @y -= @velocity
  if @alive && (@y < 32 || @y > @window.height - 32)
    die!
  end
  if @y > 1000
    # kick out to loading screen to try again?
    @level.fail!
  end
end