Class: SpaceDozer::Game

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

Instance Method Summary collapse

Instance Method Details

#over?Boolean

A game is complete when any of these conditions are met

  • the game has been stopped via #stop

  • all of the player's dozers are dead

  • all of the aliens are dead

Returns:

  • (Boolean)

66
67
68
# File 'lib/spacedozer/game.rb', line 66

def over?
  stopped? || @dozers.zero? || !@map.any?(&:alien?)
end

#playObject


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
# File 'lib/spacedozer/game.rb', line 18

def play
  turn = Time.now.to_f
  dozer = @map.find(&:dozer?) || begin
    @dozers -= 1
    @map.center.tap(&:dozer)
  end
  Console.keypress { |direction| @map.move dozer, direction }

  if (turn - @turn) >= @rate
    @map.select(&:alien?).each do |alien|
      empty_directions = @map.empty_directions(alien)
      dozer_directions = @map.dozer_directions(alien, dozer)
      dozer_directions.select! { |direction| empty_directions.include? direction }

      if dozer_directions.any?
        @map.move(alien, dozer_directions.sample)
      elsif empty_directions.any?
        @map.move(alien, empty_directions.sample)
      end
    end

    # @turns += 1
    # @rate -= 0.1 if (@turns % 50).zero?
    @turn = turn
  end

  @map.update &:changed?
end

#startObject


5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/spacedozer/game.rb', line 5

def start
  @map = Map.new

  @dozers = 3
  @status = 0
  @start  =
  @turn   = Time.now.to_f
  @rate = 0.75
  # @turns = 0

  @map.update
end

#statisticsObject (private)


82
83
84
85
86
87
88
89
# File 'lib/spacedozer/game.rb', line 82

def statistics
  {
    played: (@turn - @start),
    total:  (@map.score(:alien) * 20) - (@map.score(:dozer) * 100) - (@turn - @start),
    kills:  @map.score(:alien),
    dozers: @dozers
  }
end

#stoptrue

Set the @status to 1

Returns:

  • (true)

49
50
51
52
53
# File 'lib/spacedozer/game.rb', line 49

def stop
  @status = 1

  true
end

#stopped?Boolean

Returns:

  • (Boolean)

56
57
58
# File 'lib/spacedozer/game.rb', line 56

def stopped?
  @status == 1
end

#to_sObject


70
71
72
73
74
75
76
77
78
# File 'lib/spacedozer/game.rb', line 70

def to_s
  <<-SCOREBOARD.gsub(/^[ ]{8}/, '') % statistics
    +  %<kills>i Aliens squished (x20)
    +  %<dozers>i Dozers remaining (x100)
    -  %<played>i Seconds played (x1)
    ---------------------------
       %<total>i points
  SCOREBOARD
end