WIP

A17

created at 2016.10.13
updated at 約1年 ago
vsanna / public lesson_paiza

result

  • passed: 10 / 10
  • 回答時間: 77分47秒
  • バイト数: 1876 Byte
  • スコア: 74点

反省

あとでかく

code

require 'pp'
require 'byebug'

class Game
  attr_accessor :height, :width, :block_num, :blocks, :field

  def initialize(height, width, block_num)
    @height = height
    @width = width
    @block_num = block_num
    @field = set_field
    @blocks = []
  end

  def set_field
    @field = []
    @height.times do |h|
      @field[h] = Array.new(@width, 0)
    end
    @field
  end

  def set_blocks
    @block_num.times do |i|
      height, width, initial_x = gets.chomp.split(' ').map(&:to_i)
      add_block(Block.new(height, width, initial_x))
    end
  end

  def add_block(block)
    @blocks << block
  end

  def play
    @blocks.each do |b|
      # 次の場所に移動できるか判断
      # no ならposition確定
      #   次へ
      # yes なら+1
      self.down(0, b)
    end
  end

  def down(row, b)
    # 下端まで到達したら終了
    if row + 1 >= @height
      modify_field(row, b)
      return
    end

    next_position_rows = @field[row + 1][(b.initial_x)..(b.initial_x + b.width - 1)]
    if next_position_rows.all?(&:zero?)
      self.down(row + 1, b)
    else
      # 場所確定
      modify_field(row, b)
    end
  end

  def modify_field(row, block)
    start_row = (row + 1 - block.height) < 0 ? 0 : (row + 1 - block.height)
    end_row = row
    (start_row..end_row).each do |current_row|
      @field[current_row][(block.initial_x)..(block.initial_x + block.width - 1)] = Array.new(block.width, 1)
    end
  end

  def output
    field.each do |row|
      puts row.map { |el| el.zero? ? '.' : '#' }.join("")
    end
  end
end

class Block
  attr_accessor :height, :width, :initial_x
  def initialize(height, width, initial_x)
    @height = height
    @width = width
    @initial_x = initial_x
  end
end


height, width, block_num = gets.chomp.split(' ').map(&:to_i)
game = Game.new(height, width, block_num)
game.set_blocks
game.play

game.output

shareシェアする

forumコメント

まだコメントはありません!
ログインしてコメントを残す
{{comment.user.name}} on {{commentCreatedAt()}}
{{message}}