Last active
April 12, 2018 16:27
-
-
Save obelisk68/fcbbbabe86b9693543b4213ba2458d1e to your computer and use it in GitHub Desktop.
RubyPico 用ライフゲーム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LifeGame | |
W, H = 124, 38 | |
def initialize(n) | |
@field = new_field | |
scatter(n) | |
end | |
def set_cell(x, y) | |
@field[y + 1][x + 1] = 1 | |
end | |
def get_cell(x, y) | |
@field[y + 1][x + 1] | |
end | |
def new_field | |
Array.new(H + 2) {Array.new(W + 2, 0)} | |
end | |
def scatter(n) | |
co = 0 | |
while co < n | |
x, y = rand(W), rand(H) | |
if get_cell(x, y).zero? | |
set_cell(x, y) | |
co += 1 | |
end | |
end | |
end | |
def next | |
nxf = new_field | |
each_cell do |x, y| | |
n = alive_cells(x, y) | |
if get_cell(x, y).zero? | |
nxf[y + 1][x + 1] = 1 if n == 3 | |
else | |
nxf[y + 1][x + 1] = 1 if n == 2 or n == 3 | |
end | |
end | |
@field = nxf | |
end | |
def alive_cells(x, y) | |
get_cell(x - 1, y - 1) + get_cell(x, y - 1) + get_cell(x + 1, y - 1) + | |
get_cell(x - 1, y) + get_cell(x + 1, y) + | |
get_cell(x - 1, y + 1) + get_cell(x, y + 1) + get_cell(x + 1, y + 1) | |
end | |
def each_cell | |
H.times do |y| | |
W.times {|x| yield(x, y)} | |
end | |
end | |
def generate_field_string | |
st = l = "*" * (W + 2) + "\n" | |
H.times do |y| | |
st += "*" + @field[y + 1][1..-2].map {|c| c.zero? ? " " : "O"}.join + "*\n" | |
end | |
st + l | |
end | |
def run(wait) | |
loop do | |
clearprint generate_field_string | |
self.next | |
sleep(wait) | |
end | |
end | |
end | |
LifeGame.new(650).run(0.7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment