Class: Elus::Game

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Game

Returns a new instance of Game.

Raises:



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

def initialize(options = {})
  rules_generator = options[:generator]
  @board = options[:board]
  @free = options[:free]
  raise Elus::Invalid, "Wrong Board or Free set: #{@board}, #{@free}" unless [@board, @free].all? {|set| Array === set}  # Check if all pieces are correct
  raise Elus::Invalid, "Wrong Game Pieces: #{@board}, #{@free}" unless (@board + @free).all? {|piece| Piece === piece}  # Check if all pieces are correct
  raise Elus::Invalid, "Wrong number of Game Pieces: #{@board}, #{@free}" unless @board.size >= 3 and @free.size == 3  # Check for correct Board/Free size
  raise Elus::Invalid, "Wrong Rules generator" unless rules_generator.respond_to? :generate_rules
  
  @rules = rules_generator.generate_rules
  test_rules
  count_moves
end

Instance Method Details

#count_movesObject

Count Moves



18
19
20
21
22
23
# File 'lib/elus/game.rb', line 18

def count_moves
  @moves = @free.map do |piece| 
    count = @rules.count {|rule| piece == rule.apply(@board.last)}
    count > 0 ? "#{piece.name}(#{count})" : nil
  end.compact
end

#finished?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/elus/game.rb', line 45

def finished? 
  @board.size>=8  
end

#hintObject



40
41
42
43
# File 'lib/elus/game.rb', line 40

def hint
  "Rules(#{@rules.size}):\n" + @rules.map(&:name).join("\n") +"\n" +
  "Moves(#{@moves.size}):\n" + @moves.join("\n") + "\n"
end

#move(piece, new_free = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/elus/game.rb', line 25

def move(piece, new_free=nil)
  if new_free # The move was right!
    @board << piece
    @free = new_free
  else
    @free.delete(piece)
  end  
  test_rules
  count_moves
end

#stateObject



36
37
38
# File 'lib/elus/game.rb', line 36

def state
  "Free:\n" + @free.join("\n") + "\nBoard:\n" + @board.join("\n") + "\n"
end

#valid_move?(piece) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/elus/game.rb', line 49

def valid_move? piece 
  @free.include? piece
end