Class: Chess2PNG

Inherits:
Object
  • Object
show all
Defined in:
lib/chess2png.rb,
lib/chess2png/version.rb

Constant Summary collapse

BOARD_SIZE =
8
VERSION =
"0.0.2"

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Chess2PNG

Returns a new instance of Chess2PNG.



7
8
9
10
11
# File 'lib/chess2png.rb', line 7

def initialize(options = {})
  @pieces = options.delete(:pieces) || default_pieces
  @background = options.delete(:background) || default_background
  @square_size = options.delete(:square_size) || 61
end

Instance Method Details

#default_backgroundObject



57
58
59
60
61
# File 'lib/chess2png.rb', line 57

def default_background
  root = File.dirname(__FILE__)

  File.join(root, "../assets/background.png")
end

#default_piecesObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/chess2png.rb', line 37

def default_pieces
  root = File.dirname(__FILE__)

  {
    'P' => File.join(root, "../assets/Chess_plt60.png"),
    'R' => File.join(root, "../assets/Chess_rlt60.png"),
    'N' => File.join(root, "../assets/Chess_nlt60.png"),
    'B' => File.join(root, "../assets/Chess_blt60.png"),
    'Q' => File.join(root, "../assets/Chess_qlt60.png"),
    'K' => File.join(root, "../assets/Chess_klt60.png"),

    'p' => File.join(root, "../assets/Chess_pdt60.png"),
    'r' => File.join(root, "../assets/Chess_rdt60.png"),
    'n' => File.join(root, "../assets/Chess_ndt60.png"),
    'b' => File.join(root, "../assets/Chess_bdt60.png"),
    'q' => File.join(root, "../assets/Chess_qdt60.png"),
    'k' => File.join(root, "../assets/Chess_kdt60.png")
  }
end

#encode(board) ⇒ Object



13
14
15
16
17
# File 'lib/chess2png.rb', line 13

def encode(board)
  ChunkyPNG::Image.from_file(@background).tap do |image|
    self.encode_to_image(board, image)
  end
end

#encode_to_image(board, image) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/chess2png.rb', line 19

def encode_to_image(board, image)
  BOARD_SIZE.times do |x|
    BOARD_SIZE.times do |y|
      piece_image = self.piece_to_image(board[x + y * BOARD_SIZE])

      if piece_image
        image.compose!(piece_image, x * @square_size, (BOARD_SIZE - 1) * @square_size - y * @square_size)
      end
    end
  end
end

#load_image(path) ⇒ Object



63
64
65
66
67
# File 'lib/chess2png.rb', line 63

def load_image(path)
  @image_cache ||= {}
  @image_cache[path] ||= ChunkyPNG::Image.from_file(path)
  @image_cache[path]
end

#piece_to_image(piece) ⇒ Object



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

def piece_to_image(piece)
  @pieces.map do |piece, path|
    [ piece, load_image(path) ]
  end.to_h[piece]
end