Skip to content

Instantly share code, notes, and snippets.

@madogiwa0124
Created January 18, 2018 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madogiwa0124/63cdf85c40dfe8daee0198301d8aa4af to your computer and use it in GitHub Desktop.
Save madogiwa0124/63cdf85c40dfe8daee0198301d8aa4af to your computer and use it in GitHub Desktop.
ぷよぷよの連結数チェックプログラム by ruby
$bord = [['b','b',nil,'r'],
['b','r','r','b'],
['g','r','b','r'],
['b','r','g','b']] # r: 赤, g: 緑, b: 青, nil: なし
$count = 0 # 連結数 TODO:グローバル変数を使わない実装に変更する
# ぷよの情報を保持するクラス
class Puyo
attr_accessor :color, :position
def initialize(color, position)
@color = color
@position = position
end
# 隣り合うぷよを取得する
def get_tonari_puyo
max_x = $bord[@position[:y]].length - 1
max_y = $bord.length - 1
min_x,min_y = 0, 0
y,x = @position[:y],@position[:x]
ue = y > min_y ? Puyo.new($bord[y-1][x], { y: y-1, x: x }) : nil
migi = x < max_x ? Puyo.new($bord[y][x+1], { y: y, x: x+1 }) : nil
sita = y < max_y ? Puyo.new($bord[y+1][x], { y: y+1, x: x }) : nil
hidari = x > min_x ? Puyo.new($bord[y][x-1], { y: y, x: x-1 }) : nil
{ue: ue, migi: migi, sita: sita, hidari: hidari}
end
end
# 同じ色かつ隣り合っているぷよの個数を再帰的に検証する
def check(current_puyo, rireki_puyo)
$count += 1
rensa_puyo = current_puyo.get_tonari_puyo.select do |key, puyo|
rireki_positions = rireki_puyo.map{ |puyo| puyo.position }
mada_puyo = !rireki_positions.include?(puyo&.position)
same_color = current_puyo.color == puyo&.color
mada_puyo && same_color
end
rireki_puyo << current_puyo
unless rensa_puyo.empty?
rensa_puyo.each do |key, puyo|
check(puyo, rireki_puyo)
end
end
end
# 連結数checkの呼び出しメソッド
def calc(y, x)
rireki_puyo = []
current_puyo = Puyo.new($bord[y][x], {y: y, x: x })
rireki_puyo << current_puyo
check(current_puyo, rireki_puyo)
$count
end
p calc(3, 1) #4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment